Skip to content

fix(db): reconcile schema ownership and integrity across engines (WI-2366) - #568

Open
stefan-ernst wants to merge 3 commits into
mainfrom
fix/wi-2366-schema-ownership
Open

stefan-ernst wants to merge 3 commits into
mainfrom
fix/wi-2366-schema-ownership

Conversation

@stefan-ernst

Copy link
Copy Markdown
Contributor

Reconciles the database schema findings from the 0.9.6 design review (WI-2366).

Priority fixes

1. One authoritative PostgreSQL bootstrap definition. base_tables_postgres.sql declared eleven tables before their owning domain files. Because the file runs first, CREATE TABLE IF NOT EXISTS won and silently discarded the domain definition. Four cascading foreign keys were lost (board_configurations.workspace_id/collection_id, test_folders.workspace_id, test_labels.workspace_id) and iteration_types kept an unread duration_days column with a nullable color. The duplicate stubs are removed; the domain files now own those tables. Migration 20261205_postgres_schema_authority reconciles orphan rows, restores the four keys, and aligns iteration_types with SQLite and the Go model.

2. configuration_set_item_types is the membership source of truth. Workflow resolution now goes through the submitting workspace's effective configuration set (assigned set, else the global default) and the junction, instead of an item-type-only join with an unordered LIMIT 1. Migration 20261208_item_type_membership_authority backfills the junction only for custom (non-built-in) scalar-only rows, so the seed's deliberate exclusion of Initiative from the simplified default set is preserved, then drops item_types.configuration_set_id.

3. Agent-binding creator deletion. SQLite declared created_by_user_id NOT NULL with ON DELETE SET NULL, so deleting a distinct creator failed there but nulled the row on PostgreSQL. The creator is a soft audit ref like the sibling agent tables: SQLite now allows the null and the model/reader use *int. Migration 20261206_agent_binding_creator_nullable rebuilds the SQLite table.

4. One owner and one configuration per board owner. board_configurations now has an exactly-one-owner CHECK and one partial unique index per owner. Migration 20261207_board_configuration_ownership merges duplicate configurations by moving their board_columns onto the lowest-id survivor (so columns are not lost), drops unreachable ownerless rows, then adds the constraints.

5. Atomic binding repository replacement. UpdateConfig's parent version bump and the delete-then-insert repository replacement now share one transaction, so a failure cannot publish a new profile_version with the old or a partial repository list.

Cleanup

  • Removed the stale SQLite request_types DDL that never applied.
  • Removed the duplicate SQLite workspace_time_project_categories junction and indexes.
  • Removed the unused milestones_existing*.sql bootstrap files and stale comments.
  • Removed the five duplicate SQLite items foreign keys on fresh installs.
  • Dropped the redundant PostgreSQL UNIQUE(configuration_set_id, notification_setting_id) after collapsing duplicates and ensuring the single-column upsert target exists (20261209_notification_setting_unique).
  • Corrected the notification_templates comments: template_type is still read by the notification cache refresh.

Deferred (documented in code)

  • Zammad legacy workspace scope (applies_to_all_workspaces, zammad_connection_workspaces): retained until every supported upgrade has run the 20260901_zammad_canonical_workspace_scope backfill.
  • Legacy notification-template columns (event_type, template_subject, template_body, template_variables, channel_type): need a deliberate audit of existing rows before removal.
  • Duplicate items foreign keys on already-installed SQLite databases: folded into a planned items rebuild.
  • Agent-binding scalar repository mirror: retirement waits for its rollback window to close.

Verification

Tests live in the companion core-tests PR. On SQLite the database, repository, services, handlers, and black-box suites pass. On PostgreSQL the database suite (including new fresh-install and upgrade-path tests), repository suite, and black-box suite pass. Two pre-existing PostgreSQL failures reproduce on the base commit and are unrelated to this change: TestCustomFieldIndexLimit and TestSLAOccurrenceNotificationDeliveryKeyDeduplicates.

…2366)

Give each PostgreSQL table one authoritative bootstrap definition. The
base_tables stub silently won board_configurations, test_folders,
test_labels and iteration_types, dropping four cascading foreign keys and
relaxing iteration_types; the domain files now own those tables and a
migration reconciles orphans and restores the keys.

Make configuration_set_item_types the item-type membership source. Workflow
resolution goes through the workspace's effective set, and the scalar
item_types.configuration_set_id is dropped after backfilling only custom
types, preserving the seed's deliberate exclusion of Initiative.

Align agent-binding creator deletion: SQLite now allows the creator to be
nulled, matching PostgreSQL and the soft-audit model, and the repository
reader handles NULL.

Enforce exactly one owner and at most one configuration per board owner,
reconciling duplicates without losing board columns.

Make agent-binding repository replacement atomic with the parent version
bump.

Cleanup: drop the stale SQLite request_types DDL, the duplicate
time-category junction, the unused milestone bootstrap files, duplicate
items foreign keys on fresh installs, and the redundant two-column
PostgreSQL notification-setting uniqueness.
@stefan-ernst

Copy link
Copy Markdown
Contributor Author

I’d request changes before merging. I reproduced five upgrade issues using the previous SQLite schema and the migration SQL from ac23c862:

  1. P1 — A board with both owners set blocks startup. The reconciliation keeps a row that is the sole configuration for both its workspace and its collection. SQLite then fails the copy with CHECK constraint failed: board_configurations_exactly_one_owner. PostgreSQL applies the same check to the same surviving row. Reconcile dual-owner rows before enforcing the constraint.
  2. P1 — A deleted configuration set blocks the item-type migration. The backfill copies a legacy scalar that had no foreign key into a junction that does. A custom type pointing to a deleted set caused FOREIGN KEY constraint failed. Join to configuration_sets so only existing parents are backfilled on either engine.
  3. P1 — An ownerless board’s columns can appear on a new board. The SQLite rebuild disables foreign keys before deleting ownerless configurations, so their columns and status mappings do not cascade. PRAGMA foreign_key_check reported the orphan column after migration; creating a new board reused the deleted ID and inherited that column. Delete the dependent rows explicitly or reconcile while cascades are enabled.
  4. P2 — The binding rebuild reuses deleted binding IDs. The table swap loses the sqlite_sequence high-water mark. After creating bindings 1 and 2 and deleting 2, the first post-upgrade binding received ID 2 again. agent_runs.binding_id deliberately survives deletion, so historical runs can count against the new binding’s daily budget. Preserve the original sequence across the swap.
  5. P2 — The backfill restores memberships an admin already removed. The NOT EXISTS predicate checks for the exact pair, not whether the type already has authoritative junction rows. A custom type moved from set A to B went from membership {B} to {A, B} after upgrade. Backfill only types with no junction membership at all.

The focused companion database and service tests passed on SQLite and PostgreSQL. I did not rerun the full suites.

Test commands
../core-tests-wi-2366/overlay.sh ../core-wi-2366 -- -tags=test -count=1 -run 'Test(Schema_|Migration_BoardConfigurationOwnershipReconciles|Migration_ItemTypeMembershipBackfillsCustomTypes|GetInitialStatusForItemTypeResolvesWorkspaceSet)' ./internal/database ./internal/services

../core-tests-wi-2366/scripts/native-postgres.sh run -- ../core-tests-wi-2366/overlay.sh ../core-wi-2366 -- -tags=test -count=1 -run 'Test(Schema_|Migration_BoardConfigurationOwnershipReconciles|Migration_ItemTypeMembershipBackfillsCustomTypes|Migration_PostgresSchemaAuthorityRestoresCascades|GetInitialStatusForItemTypeResolvesWorkspaceSet)' ./internal/database ./internal/services

Address the upgrade-path review findings:

- Normalize dual-owner board configurations to their workspace owner before
  the exactly-one-owner check, so such a row no longer blocks startup.
- Remove board columns (and their status mappings) left without a
  configuration. The SQLite rebuild runs with foreign keys off, so the
  ownerless-configuration delete did not cascade and a later board could
  inherit a deleted board's column.
- Preserve the sqlite_sequence high-water mark across the binding and board
  table rebuilds. A deleted binding's id is still referenced by historical
  agent runs and must not be reused.
- Backfill item-type membership only for custom types with no junction
  membership at all, and join configuration_sets so a scalar pointing at a
  deleted set cannot fail the foreign key.
@stefan-ernst

Copy link
Copy Markdown
Contributor Author

Thanks — all five are fixed in 908f5a0d (core) and 846cc90b (tests).

  1. Dual-owner board — boardConfigurationReconcileSQL now nulls collection_id on rows with both owners first (keeping the workspace owner, matching the repository's create precedence), so the surviving row satisfies the check on both engines.
  2. Deleted configuration set — the item-type backfill now joins configuration_sets, so a scalar pointing at a deleted set is skipped instead of failing the junction foreign key.
  3. Orphaned board columns — after deleting ownerless/duplicate configurations, the reconciliation removes board_columns whose configuration is gone and board_column_statuses whose column is gone. PRAGMA foreign_key_check is now clean; the new test asserts no orphan column or status row remains.
  4. Binding id reuse — both SQLite rebuilds read the original sqlite_sequence value before the swap and restore it (flooring at the old high-water mark) after the rename, so a deleted binding id is not handed to a new binding.
  5. Removed memberships — the backfill predicate is now NOT EXISTS (… WHERE csit.item_type_id = it.id), so a type that already has authoritative junction membership is left untouched.

New tests cover each case: dual-owner normalization + orphan cleanup, a scalar to a deleted set, a type already moved to another set, and sequence preservation across the binding rebuild. Ran the focused database and service tests on SQLite and PostgreSQL, plus the full internal/database, internal/repository, and internal/services suites on SQLite and internal/database on PostgreSQL — all green.

@stefan-ernst

Copy link
Copy Markdown
Contributor Author

Re-reviewed 908f5a0d. The five cases from my first review are addressed, and the focused migration tests passed on SQLite and PostgreSQL. The exactly-one-owner constraint matches how the application stores collection boards and workspace-default boards.

One remaining finding: iteration_types.color has a different default on fresh and upgraded PostgreSQL databases. The upgrade migration sets NOT NULL but retains the old DEFAULT '#6b7280'. I verified that INSERT INTO iteration_types (name) VALUES ('Sprint X') succeeds after upgrade and receives #6b7280; the fresh schema requires an explicit color.

Please add ALTER TABLE iteration_types ALTER COLUMN color DROP DEFAULT after backfilling existing nulls, and check column_default IS NULL in both the migration’s CheckPostgres predicate and the upgrade test. The test fixture should start with the historical default so it exercises the difference.

The base_tables stub defaulted iteration_types.color to '#6b7280' while
the fresh schema requires an explicit color. The alignment migration set
NOT NULL but left the default, so an upgraded PostgreSQL database accepted
a colorless insert that a fresh one rejects. Drop the default and require
column_default IS NULL in the migration check.
@stefan-ernst

Copy link
Copy Markdown
Contributor Author

Fixed in 07a9be89 (core) and 10797dc6 (tests).

20261205_postgres_schema_authority now runs ALTER TABLE iteration_types ALTER COLUMN color DROP DEFAULT after the null backfill and SET NOT NULL, and its CheckPostgres requires column_default IS NULL. The upgrade fixture starts from the historical color TEXT DEFAULT '#6b7280' and asserts the default is gone and a colorless insert fails; the fresh-install shape test checks the same. Full internal/database suites pass on SQLite and PostgreSQL.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant