Magento 2

Magento 2's setup:upgrade --keep-generated Bug: Unpacking the 'Table Not Found' Error for New Modules

Diagram showing the Magento 2 setup:upgrade process with a missing object manager reset
Diagram showing the Magento 2 setup:upgrade process with a missing object manager reset

Unpacking Magento 2's setup:upgrade --keep-generated Bug: Why Your New Module Tables Might Go Missing

As e-commerce migration experts at Shopping Mover, we frequently navigate the intricate landscape of Magento 2 deployments and upgrades. Our mission is to ensure seamless transitions and robust platform performance for our clients, whether they're migrating from Magento 1, another platform, or simply upgrading their existing Magento 2 instance. In this pursuit, we often encounter subtle yet critical technical challenges that can significantly impact development and deployment workflows.

A recent GitHub issue (#41867) has brought to light a particularly vexing bug related to the bin/magento setup:upgrade --keep-generated command. This issue can cause newly enabled modules with declarative schema definitions and data patches to fail during their initial setup, leading to frustrating "table doesn't exist" errors. Understanding this bug is crucial for any Magento developer or system administrator aiming for smooth, error-free deployments.

The Core Problem: A Discrepancy in Module Recognition

The bug manifests when a new Magento 2 module, which includes both a db_schema.xml file declaring a new database table and a data patch that attempts to insert data into that table, is enabled for the first time using setup:upgrade --keep-generated in production mode. The expected behavior is that the command should gracefully create the table and then run the data patch successfully. However, the actual result is a fatal error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table '.keepgen_repro' doesn't exist, query was: INSERT INTO `keepgen_repro` (`code`) VALUES (?)

This error message is a clear indicator that the database table, despite being defined in the module's db_schema.xml, was not created before the data patch attempted to interact with it. What makes this bug particularly insidious is its "second run fixes it" behavior: if the command is executed a second time immediately after the first failure, it often completes successfully, creating the table and inserting the data. This anomaly strongly suggests a caching or state management issue within Magento's setup process.

Deep Dive into the Root Cause: The Object Manager's Stale State

The author of the GitHub issue, bluefairydevelopment, provided an excellent analysis of the problem's origin within Magento's core code, specifically within the Magento\Setup\Model\Installer class. The discrepancy lies in how the Installer handles module lists and object manager resets, particularly when the --keep-generated flag is used:

  • Module List Update: During setup:upgrade, the Installer::updateModulesSequence() method is responsible for updating the list of enabled modules in app/etc/config.php. This is a critical step for Magento to recognize new modules.
  • Object Manager's Role: Magento's Object Manager is a central component for dependency injection and service location. It holds a cached understanding of the system's configuration, including the list of active modules and their respective configurations (like db_schema.xml).
  • The Missing Reset: When setup:upgrade is run without the --keep-generated flag, a crucial step occurs: the object manager is reset after the config.php file is updated. This forces the object manager to rebuild its internal state, incorporating the newly enabled modules. Consequently, when the schema installation phase runs, the declarative schema reader correctly identifies and processes the db_schema.xml for the new module, creating the table.
  • The `--keep-generated` Anomaly: However, when setup:upgrade --keep-generated is executed, the object manager is not reset after config.php is updated. The object manager, and by extension, the declarative schema reader, continues to operate with a stale list of modules – one that existed *before* the new module was enabled. As a result, the new module's db_schema.xml is overlooked, and its table is never created.
  • The Data Patch Paradox: Simultaneously, the data patch execution loop within Installer::installDataFixtures() uses the Installer's own, updated module list. This means the data patch *does* recognize the new module and attempts to run, but it tries to insert data into a table that the schema installer, operating with its stale module list, never created. This leads directly to the "Base table or view not found" error.

The second successful run occurs because, by then, the system state (including the object manager's understanding of enabled modules) has implicitly caught up, allowing the schema to be applied correctly.

Impact on Magento Development, Deployments, and Migrations

This bug, though seemingly minor, can have significant repercussions:

  • Broken CI/CD Pipelines: Automated deployment scripts that rely on a single setup:upgrade --keep-generated command will fail, requiring manual intervention or a re-run, adding friction and delaying releases.
  • Developer Frustration: Developers encountering this for the first time will spend valuable hours debugging a seemingly inexplicable "table not found" error, questioning their module's schema definition or data patch logic.
  • Inconsistent Environments: In complex environments with multiple developers or staging servers, this bug can lead to inconsistent database schemas if not properly managed, making debugging even harder.
  • Migration Headaches: For large-scale Magento 2 migrations, where numerous custom modules and third-party extensions are being deployed and upgraded, this issue can introduce unexpected delays and complicate the migration timeline. Ensuring all modules are correctly installed and their schemas applied is paramount for a successful migration.

Workarounds and Mitigation Strategies

While a permanent fix is awaited in Magento's core, here are several strategies to mitigate the impact of this bug:

  1. Run setup:upgrade Twice: The simplest, albeit inelegant, workaround is to simply run bin/magento setup:upgrade --keep-generated a second time after the initial failure. This forces the system to re-evaluate, leading to successful schema creation and data patch application.
  2. Avoid --keep-generated for Initial Enablement: If feasible, for the *initial* enablement of a new module with declarative schema, consider running bin/magento setup:upgrade without the --keep-generated flag. This will trigger the full cleanup and object manager reset, ensuring the schema is applied correctly. Subsequent upgrades can then use --keep-generated.
  3. Manual Object Manager Reset (Less Reliable): While not a guaranteed fix for all scenarios, some developers might try to manually clear generated files or flush caches before running setup:upgrade --keep-generated, hoping to force a state refresh. However, the core issue is the specific timing of the object manager reset within the Installer class, which these external commands might not fully address.
  4. Implement a Custom Deployment Script: For robust CI/CD, consider a deployment script that explicitly checks for the module's table existence after the first setup:upgrade --keep-generated run and, if missing, triggers a second run or a more targeted schema update.
  5. Monitor for Core Patches: Keep an eye on the official Magento 2 GitHub repository for updates to issue #41867 and related pull requests (like #41276 and #41153). A core patch is the ultimate solution.

Best Practices for Robust Magento Deployments

Beyond this specific bug, maintaining a healthy Magento 2 environment requires adherence to best practices:

  • Thorough Testing: Always test module installations and upgrades in a staging environment that mirrors production as closely as possible.
  • Understand setup:upgrade Flags: Be aware of what each flag (e.g., --keep-generated, --safe-mode) does and its implications for your deployment strategy.
  • Version Control: Keep all module code, database schema, and configuration under strict version control.
  • Regular Backups: Always back up your database and file system before any major upgrade or module deployment.

This bug highlights the complexities inherent in large, modular systems like Magento 2. Understanding these nuances is key to building and maintaining high-performing e-commerce platforms.

Need Expert Magento Migration or Development Support?

At Shopping Mover, we specialize in navigating these intricate technical challenges. Whether you're planning a complex Magento migration, need assistance with module development, or require expert advice on optimizing your Adobe Commerce or Open Source instance, our team is equipped with the knowledge and experience to ensure your success. Don't let subtle bugs derail your e-commerce journey – partner with experts who understand the Magento ecosystem inside and out.

Share:

Start with the tools

Explore migration tools

See options, compare methods, and pick the path that fits your store.

Explore migration tools