diff --git a/.changeset/31699-connection-key-package.md b/.changeset/31699-connection-key-package.md new file mode 100644 index 00000000000..ec4c203e7c2 --- /dev/null +++ b/.changeset/31699-connection-key-package.md @@ -0,0 +1,40 @@ +--- +'@objectstack/metadata-protocol': patch +'@objectstack/service-automation': patch +'@objectstack/driver-mongodb': patch +'@objectstack/cli': patch +--- + +feat(service-automation, metadata-protocol, driver-mongodb, cli): a connector connection is unique per organization and instance, the instance being its package and name, and the connections that name no package keep one per organization through a runtime guard (ADR-0150 D4, D8 row R11, #31699) + +Clause-②: yes (widening) — additive CLI and in-process surfaces: `os migrate plan` lists a second runtime-owned index (and `--json` `schemaSyncIndexes` an entry for it), `os migrate duplicates` probes it, `os migrate stored-references bind` answers the refusal `duplicate` where it threw, and the exports and types listed under In-process APIs grow. The connector doors (the connect door, the OAuth callback, revoke, the connection list) and every automation request answer as before: the store still reads and writes by organization and name, and the one-holder backstop keeps every connector name to one package until #31699's last PR, so no second package's connection is written yet. +Metadata-protocol: none +Skills-docs: `content/docs/automation/connectors.mdx` says a connection is one per organization and instance; `content/docs/deployment/cli.mdx` lists the guard among the runtime-owned indexes and the bind's `duplicate` refusal. `skills/**` teaches "connect once per organization", which still holds per instance. + + + +Part of #31699 (ADR-0150 child B, PR 3a: the storage half). The maintainer's ruling on #31699: a connection is unique by package and name. The store, the connect door and the OAuth callback carry the package in the next PR; this one widens the key, stands the guard that keeps the package-less rows to one, and teaches the two writers of the package column what the wider key can refuse. + +**The key: `sys_connector_connection`.** + +- FROM one connection per `(organization_id, connector_name)` (`uniq_sys_connector_connection_organization_id_connector_name`) TO one per `(organization_id, connector_package, connector_name)`. On SQL the drift plan replaces the old key with one `replace_unique_index`, categorized `safe`, create-before-drop, and only once the guard below stands; until then `driver-sql`'s widening arm keeps the old key, so the table is never without a unique rule over its rows. The guard is built at schema sync after the table's drift is read, so on an upgraded database the old key retires on the NEXT sync that runs safe drift (a dev `autoMigrate: 'safe'` boot, or `os migrate apply`, which lists it). Measured on SQLite and PostgreSQL 16: with the guard, the plan is that one safe op and a re-plan is empty; two packages' connections of one name in one organization are admitted, a second connection of one package's instance is refused, and a second package-less connection is refused. On MariaDB the retirement is read from `driver-sql`'s source, not measured: its carrier column is read as a partial unique on the two columns, and on an upgraded MySQL-family database `connector_package` is a TEXT column, so the wide key is built over the driver's hash shadow. + +**The guard: `uniq_sys_connector_connection_packageless`.** + +- `connector_package` is NULL on every connection of an instance the environment authored or a plugin registers in code, and of a name the boot backfill could not bind. A SQL UNIQUE treats NULLs as distinct, so for exactly those connections the wider key constrains nothing. The guard keeps them to one per `(organization_id, connector_name)`, as the old key did: two of them would keep two refresh tokens for one instance, and a revoke would leave the other stored. +- Built as the permission-set grant's guard is (#32164), at `objectql:schema-synced`, on every kernel that runs the table's DDL; a pass that holds its DDL back builds nothing, a standing guard costs one catalog read, a refusal is reported once per boot. SQLite and PostgreSQL: a partial unique index `WHERE connector_package IS NULL`. MySQL 8.0.13+: a functional key part over the hash-shadow digest. MariaDB 10.3+: a UNIQUE key over an INVISIBLE generated column `uniq_sys_connector_connection_packageless__hash`. MongoDB: `driver-mongodb` builds it at collection sync (`RUNTIME_OWNED_UNIQUES`, `connector_package: null`), keyed `(connector_name)`, because Mongo materialized the earlier declaration's one column, so the widening arm there retires the old index once the guard stands. +- Refuse, never keep-one: a database already holding two package-less connections of one key keeps both; the build fails and logs, at `error`, the keys, the consequence and the query that lists them. `os migrate duplicates` lists this index too. It admits nothing the old key refused. + +**The writers of the table.** + +- The connection store's first connect (`ConnectorConnectionStore#connect`): the old key refused a second row of one instance in one organization; the wide key admits one when the boot backfill stamped the first connect's row with its package between a second connect's read and its insert. A connect that counts a second row after its insert now deletes its own row and is refused ("its connection changed while this connect was completing … begin the connect again"), nothing kept, as the old key refused it; when both racing connects count two rows, both can be refused and no row stands. Where the engine answers no id for the inserted row, or the delete fails, the connect is refused saying the instance was connected twice and to revoke until it reads as not connected. A first connect with no race is unchanged. +- The boot backfill (`stored-reference-package-backfill.ts`, row R11) binds a package-less connection to the one package that holds its name. Under the wider key that row can be a second row of one key, when a connection bound to that package already stands for the same organization and name (a database where a guard build was refused, `driver-memory`, a server with no form, or a pair a racing first connect left when its process died before taking its row back). The wider key makes that unique violation possible, and it would end R11's pass; it is now reported per row: the row is left as it is and listed in the report's new `duplicated` list, once a read confirms the row of that key that already names the holder, named in one `warn` line per pass. A dry run lists the same rows, counting the keys it has already bound in the pass. Any other failed write, a violation no such row confirms, and any violation on R8 or R9 (whose keys do not carry the package) still end the pass. +- `os migrate stored-references bind`: FROM a unique violation thrown as an error TO the refusal `duplicate`, naming the row, the package and the key, nothing written. + +**Declared limits.** + +- MySQL 8, upgraded databases: `driver-sql` reads the guard's functional key part as an expression, not as a partial guard, so the widening arm keeps the old key there. The old key keeps refusing what it refused, so an organization cannot connect a second package's instance of one name on such a database until `driver-sql` recognises the form. A database created fresh on MySQL 8 has the wide key and the guard and no old key. The permission-set grant's guard (#32164) shares this limit. MySQL before 8.0.13 and MariaDB before 10.3 build no form, keep the old key (or build it under the driver's generated name where it is missing) and say so at `error` each boot. +- `driver-memory` builds no guard (no raw-SQL seam), as for the grant: a pin measures that its unique check treats a NULL package as distinct, so two package-less connections of one instance are admitted there. +- The MySQL, MariaDB and real-mongod pins run in suites that run on `main` only, so they first run after this lands. + +**In-process APIs.** `@objectstack/metadata-protocol` exports `ensureConnectorConnectionPackagelessIndex`, `createConnectorConnectionGuardAtSchemaSync`, `buildConnectorConnectionPackagelessIndexSql`, `buildConnectorConnectionPackagelessIndexPresenceSql`, `buildConnectorConnectionPackagelessDuplicateProbeSql`, `buildConnectorConnectionOldKeySql`, `resolveConnectorConnectionIndexSeam`, `CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME`, `CONNECTOR_CONNECTION_PACKAGELESS_INDEX_COLUMNS`, `CONNECTOR_CONNECTION_OLD_KEY_INDEX_NAME` and the result, status and pass-outcome types. `@objectstack/service-automation`'s `StoredReferenceBackfillReport` gains `duplicated`. `@objectstack/cli`'s `BindRefusal` gains `'duplicate'`. All additive. diff --git a/content/docs/automation/connectors.mdx b/content/docs/automation/connectors.mdx index b081f8649be..594b14c82b7 100644 --- a/content/docs/automation/connectors.mdx +++ b/content/docs/automation/connectors.mdx @@ -754,7 +754,9 @@ a rotating refresh token is never spent twice. (`OS_BASE_URL` or `OS_AUTH_URL` plus `/api/v1/automation/connectors/oauth/callback`, or the automation plugin's `connectorOAuthRedirectUri`), never the request's; register that URI with the vendor. The refresh token is kept - encrypted in `sys_connector_connection`, one row per organization; it is + encrypted in `sys_connector_connection`, one row per organization and + instance, an instance being its package and name (one per organization for + an instance the environment authored or a plugin registers); it is not a sign-in account, and signing in never touches it. A run dispatches with its own organization's connection; a run with no organization uses the instance's only connection, and is refused when there are several. When the diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index e8c4d596aee..bff15155814 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -1189,23 +1189,37 @@ idempotent — but only the second takes time proportional to your data. #### Runtime-owned indexes apply builds -`os migrate apply` also builds one index of its own once that DDL is done: the -permission-set grant's package-less guard, which keeps one grant per user, -permission set and organization among the grants that name no package. -`os migrate plan` lists it in a section after the held-back work and before the -drift, the order `apply` performs them in: +`os migrate apply` also builds two indexes of its own once that DDL is done: +the permission-set grant's package-less guard, which keeps one grant per user, +permission set and organization among the grants that name no package, and the +connector connection's, which keeps one connection per organization and +connector instance among the connections that name no package. +`os migrate plan` lists them in a section after the held-back work and before +the drift, the order `apply` performs them in: ```text Runtime-owned indexes (built when you apply, after the work above) + sys_user_permission_set.uniq_sys_user_permission_set_packageless [unique (user_id, permission_set, organization_id) WHERE permission_set_package IS NULL] + + sys_connector_connection.uniq_sys_connector_connection_packageless [unique (organization_id, connector_name) WHERE connector_package IS NULL] ``` -The plan lists it only where `apply` would build it. An index that already +The plan lists each only where `apply` would build it. An index that already stands is not listed, because `apply` sends it no DDL. Nor is it listed when the plan has nothing else to apply, because `apply` then changes nothing at all; a -serving boot that runs schema sync builds it instead. Grants that would collide -under the index make the line read as refused, with how many: `apply` leaves +serving boot that runs schema sync builds it instead. Rows that would collide +under an index make its line read as refused, with how many: `apply` leaves those rows as they are, applies the rest, and `os migrate duplicates` lists them. + +Once a guard stands, the next safe sync (or `os migrate apply`) retires the key +it stands beside — the grant's `(user_id, permission_set, organization_id)`, the +connection's `(organization_id, connector_name)` — as one `replace_unique_index` +categorized safe, created before it is dropped. Until then that key stays and +keeps refusing a second package's grant or connection of one name. On an +upgraded MySQL database both old keys stay, because `driver-sql` does not read a +guard's functional key part as a guard there, so a second package's grant or +connection of one name stays refused on MySQL. A database created fresh on +MySQL never has the old keys. + Under `--json` the section is the `schemaSyncIndexes` array, whose entries carry `table`, `index`, `keyParts`, `rowScope` and a `status` of `build`, `blocked` or `unreadable`. @@ -1466,7 +1480,7 @@ where the data lives. | `os migrate meta --stored` | Replay the metadata conversion chain over this deployment's `sys_metadata` rows and rewrite the ones still carrying a pre-protocol shape. Hygiene, not a gate — nothing depends on it having run | | `os migrate security-catalog-overlays` | List the environment-wide permission-set and position rows (the legacy plurals `permissions` / `positions` included) stored over a name a configured package holds — the rows a v18 cold boot refuses — each with the package that holds its name; `--apply` deletes them, one history tombstone per row. Run it before the first v18 boot, with the flags and environment the deployment boots with: the platform security plugin's sets are held only where `os serve` composes it (an auth secret set, and the `auth` tier on), and the step takes `serve`'s `--preset` and `--dev` with `serve`'s meaning. Adopts nothing; exits 1 while it lists a row | | `os migrate packageless-overlays` | List the package-less view, dashboard, report, translation and email-template rows stored over a name exactly one installed package ships — the customizations Setup saved before ADR-0146 D11 closed that write — and with `--apply` move each into that package's paired `.custom` (created when absent) as a declared override, `basedOn` the base's installed version; the package-less row is deleted only after the moved one reads back as served. A name no package ships is environment metadata and is not touched; a name several packages ship, or one the pair already holds a row of, is listed and left with the reason. So is a view container (`list`, `listViews`, `form`, `formViews`): only a single view declares an override, so it is listed `cannot_declare` and never attempted, with the way out — save each of its views into the pair as a single view, then delete the container row. Takes `serve`'s `--preset` and `--dev`. Idempotent: a second run moves nothing. Run it once after upgrading | -| `os migrate stored-references` | List the stored references the upgrade left naming no package because the one resolution rule (ADR-0150 D3) refuses them: a user's permission-set assignment, an audience-binding suggestion, a managed sharing rule, a queue membership, an open approval request, a paused flow run, a flow credential, a flow dispatch key, a connector connection, an assignment cursor or a legacy email template whose name more than one package holds, each with its row id and every candidate by its qualified address (`namespace/name`). A suggestion a package wrote naming an environment-authored permission set, or one held only outside the package's declared dependencies, is listed with the fix and is never bindable. Also lists the packaged fields whose picklist the rule refuses (served with no options) the names two packages held before the one-holder rule, and each installed package whose namespace spells a literal segment of the address grammar (`actions`, `connectors`, `global`, `hooks`, `oauth`, `runs`, `trigger`): the boot keeps it with one warning, its items are read with `?package=ID`, and only a rename of its namespace gives them qualified addresses at the door that reads the literal (for `runs` that door is the inbound hook alone, reached at its bare address until then). Read-only, and `--json` prints the same bytes on every run. Run before the release's first boot, it reads a table that has no package column yet as nothing bound yet, lists the rows that boot's backfill will leave unbound, and says so once; it adds no column. A table this composition does not carry (automation, approvals) is named, not skipped: compose as `os serve` does, with `--preset`/`--dev`. Then `os migrate stored-references bind --table T --id ID --package P` writes the package you chose into that one row: it asks the rule again first and refuses, writing nothing, when the row is already bound, now resolves on its own, or the package is no longer a candidate (a stale report). Each bind leaves a `sys_audit_log` row; a second run writes nothing. Confirm with `--yes` | +| `os migrate stored-references` | List the stored references the upgrade left naming no package because the one resolution rule (ADR-0150 D3) refuses them: a user's permission-set assignment, an audience-binding suggestion, a managed sharing rule, a queue membership, an open approval request, a paused flow run, a flow credential, a flow dispatch key, a connector connection, an assignment cursor or a legacy email template whose name more than one package holds, each with its row id and every candidate by its qualified address (`namespace/name`). A suggestion a package wrote naming an environment-authored permission set, or one held only outside the package's declared dependencies, is listed with the fix and is never bindable. Also lists the packaged fields whose picklist the rule refuses (served with no options) the names two packages held before the one-holder rule, and each installed package whose namespace spells a literal segment of the address grammar (`actions`, `connectors`, `global`, `hooks`, `oauth`, `runs`, `trigger`): the boot keeps it with one warning, its items are read with `?package=ID`, and only a rename of its namespace gives them qualified addresses at the door that reads the literal (for `runs` that door is the inbound hook alone, reached at its bare address until then). Read-only, and `--json` prints the same bytes on every run. Run before the release's first boot, it reads a table that has no package column yet as nothing bound yet, lists the rows that boot's backfill will leave unbound, and says so once; it adds no column. A table this composition does not carry (automation, approvals) is named, not skipped: compose as `os serve` does, with `--preset`/`--dev`. Then `os migrate stored-references bind --table T --id ID --package P` writes the package you chose into that one row: it asks the rule again first and refuses, writing nothing, when the row is already bound, now resolves on its own, or the package is no longer a candidate (a stale report), and refuses (`duplicate`) a bind the table's unique key refuses because a row bound to that package already holds the key, such as a connector connection the instance already has in that organization. Each bind leaves a `sys_audit_log` row; a second run writes nothing. Confirm with `--yes` | | `os migrate duplicates` | Report business identifiers already minted twice across the organization partitions, and the rows blocking the boot-time NULL-safe index tightenings — a read-only inventory as JSON on stdout. Renumbers nothing and writes no row and no schema; run it before the boot-time tenancy repair, which overwrites part of the evidence | **The boot itself writes no row and no schema you did not ask for.** Each of these commands boots diff --git a/content/docs/permissions/tenant-audit-census.mdx b/content/docs/permissions/tenant-audit-census.mdx index 23f468e7c98..6770d31671e 100644 --- a/content/docs/permissions/tenant-audit-census.mdx +++ b/content/docs/permissions/tenant-audit-census.mdx @@ -132,7 +132,7 @@ are reported as `undecidable` rather than assumed either way. The same holds twice over for the context. An options argument spelled as a literal can be read; one spelled `options`, `{ ...opts }`, or handed through a -forwarding shim cannot, and **59 of the 311 sites are spelled that way**. A +forwarding shim cannot, and **59 of the 312 sites are spelled that way**. A context resolved from an inline literal or a local `const` can be tested for `isSystem`; one arriving from a helper call cannot. @@ -197,10 +197,10 @@ reproduce them. Where it disagrees, it disagrees on the page: | carried figure | where it survives | this census | | :--- | :--- | ---: | -| 175 write call sites | quoted in the merged changeset | **311** | +| 175 write call sites | quoted in the merged changeset | **312** | | 24 carrying no tenant context | quoted in the merged changeset | **3** provable and tenancy-enabled; **32** more whose options argument is unreadable | -| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **216 of 311** decidable, **95** undecidable | -| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 174 decidably elevated, 0 decidably not, 125 undecidable | +| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **217 of 312** decidable, **95** undecidable | +| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 175 decidably elevated, 0 decidably not, 125 undecidable | | 141 and 132, two independent re-derivations | the card that filed this work | — | **The differences are not reconciled, and deliberately so.** The old census's @@ -211,17 +211,17 @@ at any commit. Two structural facts do plausibly widen this reading against any hand or regex one, and both are counted in the generated tables below: the 62 sites reached -through an erased (`any`) receiver, and the 85 that name their object through a +through an erased (`any`) receiver, and the 86 that name their object through a `const` rather than inline. An instrument that read either the way a person does would report a smaller number and would not say so. The fourth row is the one worth flagging to anyone citing it. **The 135 / 77% figure has no surviving corroboration anywhere in the tree.** This census reads -174 of 311 (56%) as decidably elevated, with 125 more whose elevation is a +175 of 312 (56%) as decidably elevated, with 125 more whose elevation is a run-time fact — so the claim is neither confirmed nor refuted, and the honest answer is that a static reading cannot settle it. -⇒ **Cite `3 / 311`, and say what it is**: the sites whose options argument was +⇒ **Cite `3 / 312`, and say what it is**: the sites whose options argument was READ and holds no tenant context, against a decidably tenancy-enabled object. That is the control's provable yield surface. ⛔ Do not cite it as "the sites without tenant context" — **32 further sites** have an options argument this @@ -233,29 +233,29 @@ cannot read, and they are neither in nor out. | what | count | | :--- | ---: | -| write call sites on the application surface | **311** | -| …whose object name is statically decidable | 216 | +| write call sites on the application surface | **312** | +| …whose object name is statically decidable | 217 | | …whose object name is chosen at run time | 95 | -| …against an object with tenancy ENABLED | 209 | +| …against an object with tenancy ENABLED | 210 | | …against an object that declares tenancy off | 7 | -| threading a tenant context | 240 | +| threading a tenant context | 241 | | PROVABLY carrying none (options read, no context key) | **12** | | …of those, against a decidably tenancy-enabled object | **3** | | options argument UNREADABLE — may or may not carry one | 59 | | …of those, against a decidably tenancy-enabled object | 32 | -| threading a decidably ELEVATED (`isSystem`) context | 174 | +| threading a decidably ELEVATED (`isSystem`) context | 175 | | threading a context that is decidably NOT elevated | 0 | | threading a context whose elevation is a run-time fact | 125 | | how the instrument reached the site | count | | :--- | ---: | -| receiver carried a readable engine type | 249 | +| receiver carried a readable engine type | 250 | | receiver erased, placed by the object NAME | 52 | | receiver erased, placed by an `object: string` PARAMETER | 5 | | receiver erased, placed by an `UNTYPED_RECEIVERS` row | 5 | | object name spelled inline | 131 | -| object name spelled through a `const` | 85 | +| object name spelled through a `const` | 86 | | object name is an `object: string` parameter | 10 | | object name is some other run-time expression | 85 | @@ -307,13 +307,13 @@ holds still. They are required to be HERE and to say WHEN they were true; their values are not compared. The reasoning, and the measurement behind it, are in `scripts/check-tenant-audit-census.mjs`. -Measured on 2026-11-13 at `fc310c98b`. +Measured on 2026-11-14 at `2dfdbbe5b`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1150 | -| engine-shaped types recognised | 136 | +| tracked non-test sources scanned | 1157 | +| engine-shaped types recognised | 138 | | declared objects in the registry | 137 | -| same-named calls subtracted as non-engine | 293 | +| same-named calls subtracted as non-engine | 296 | {/* END GENERATED: tenant-audit-census */} diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md index cf6cd6ec297..853083471fb 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md @@ -33,17 +33,17 @@ silent, and `node scripts/tenant-audit-census.mjs --write` is the resolution. | Measure | Value | |---|---:| -| Write call sites | 311 | -| Object name statically decidable | 216 | +| Write call sites | 312 | +| Object name statically decidable | 217 | | Object name chosen at run time | 95 | -| Against a tenancy-enabled object | 209 | +| Against a tenancy-enabled object | 210 | | Against an object declaring tenancy off | 7 | -| Threading a tenant context | 240 | +| Threading a tenant context | 241 | | Provably carrying none | 12 | | …and decidably tenancy-enabled | 3 | | Options argument unreadable | 59 | | …and decidably tenancy-enabled | 32 | -| Threading a decidably elevated context | 174 | +| Threading a decidably elevated context | 175 | | Threading a decidably non-elevated context | 0 | | Threading a context of undecidable elevation | 125 | @@ -90,14 +90,14 @@ holds still. They are required to be HERE and to say WHEN they were true; their values are not compared. The reasoning, and the measurement behind it, are in `scripts/check-tenant-audit-census.mjs`. -Measured on 2026-11-13 at `fc310c98b`. +Measured on 2026-11-14 at `2dfdbbe5b`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1150 | -| engine-shaped types recognised | 136 | +| tracked non-test sources scanned | 1157 | +| engine-shaped types recognised | 138 | | declared objects in the registry | 137 | -| same-named calls subtracted as non-engine | 293 | +| same-named calls subtracted as non-engine | 296 | ## Every site @@ -237,6 +237,7 @@ Measured on 2026-11-13 at `fc310c98b`. | `packages/services/service-automation/src/builtin/crud-nodes.ts` | `delete` | `objectName` | undecidable | context, elevation undecidable | 1 | | `packages/services/service-automation/src/builtin/crud-nodes.ts` | `insert` | `objectName` | undecidable | context, elevation undecidable | 1 | | `packages/services/service-automation/src/builtin/crud-nodes.ts` | `update` | `objectName` | undecidable | context, elevation undecidable | 1 | +| `packages/services/service-automation/src/connector-connections.ts` | `delete` | `sys_connector_connection` | enabled | elevated | 1 | | `packages/services/service-automation/src/connector-connections.ts` | `delete` | `sys_connector_connection` | enabled | context, elevation undecidable | 1 | | `packages/services/service-automation/src/connector-connections.ts` | `insert` | `sys_connector_connection` | enabled | context, elevation undecidable | 1 | | `packages/services/service-automation/src/connector-connections.ts` | `update` | `sys_connector_connection` | enabled | context, elevation undecidable | 1 | diff --git a/packages/cli/src/commands/migrate/duplicates.contract.test.ts b/packages/cli/src/commands/migrate/duplicates.contract.test.ts index bb5e63dff93..67ff334c4f7 100644 --- a/packages/cli/src/commands/migrate/duplicates.contract.test.ts +++ b/packages/cli/src/commands/migrate/duplicates.contract.test.ts @@ -261,7 +261,7 @@ describe('#8928 os migrate duplicates — the report document', () => { }); }); - it('names the six runtime-managed indexes (five built at kernel:ready, the grant guard at schema sync), and the migration behind each — none for the retired sys_view_definition (ADR-0131 D13)', async () => { + it('names the seven runtime-managed indexes (five built at kernel:ready, the grant and connection guards at schema sync), and the migration behind each — none for the retired sys_view_definition (ADR-0131 D13)', async () => { const report = await collect(); expect( report.runtimeIndexPreflight.map((p) => `${p.migration}:${p.table}:${p.index}`), @@ -278,6 +278,9 @@ describe('#8928 os migrate duplicates — the report document', () => { // One package-less grant per (user_id, permission_set, organization_id), // ADR-0150 D4 (#32164): the grant key gained its package column. 'ensureUserPermissionSetPackagelessIndex:sys_user_permission_set:uniq_sys_user_permission_set_packageless', + // One package-less connection per (organization_id, connector_name), + // ADR-0150 D8 row R11 (#31699): the connection key gained its package column. + 'ensureConnectorConnectionPackagelessIndex:sys_connector_connection:uniq_sys_connector_connection_packageless', ]); }); diff --git a/packages/cli/src/commands/migrate/duplicates.integration.test.ts b/packages/cli/src/commands/migrate/duplicates.integration.test.ts index de456f8c89c..97e851d853a 100644 --- a/packages/cli/src/commands/migrate/duplicates.integration.test.ts +++ b/packages/cli/src/commands/migrate/duplicates.integration.test.ts @@ -319,11 +319,13 @@ describe('#8928 os migrate duplicates — against a really booted stack', () => // sees that something is blocked without reading every entry. expect(produced.summary.runtimeIndexesBlocked).toBe(1); expect(produced.summary.runtimeIndexBlockingRows).toBe(2); - // `sys_setting` is absent on this fixture; whatever each status, the six + // `sys_setting` is absent on this fixture; whatever each status, the seven // indexes (the fifth is the activation ledger's package-less index, the - // sixth the permission-set grant's, ADR-0150 D4, #32164) are all accounted for. - expect(produced.runtimeIndexPreflight).toHaveLength(6); + // sixth the permission-set grant's, ADR-0150 D4, #32164, the seventh the + // connector connection's, ADR-0150 D4, #31699) are all accounted for. + expect(produced.runtimeIndexPreflight).toHaveLength(7); expect(produced.runtimeIndexPreflight.map((entry) => entry.migration)).toContain('ensureUserPermissionSetPackagelessIndex'); + expect(produced.runtimeIndexPreflight.map((entry) => entry.migration)).toContain('ensureConnectorConnectionPackagelessIndex'); expect(produced.reportVersion).toBe(2); // The whole run — boot included — wrote nothing. If a future change arms a diff --git a/packages/cli/src/commands/migrate/stored-references.integration.test.ts b/packages/cli/src/commands/migrate/stored-references.integration.test.ts index d852deba998..8fbcaa51d0a 100644 --- a/packages/cli/src/commands/migrate/stored-references.integration.test.ts +++ b/packages/cli/src/commands/migrate/stored-references.integration.test.ts @@ -418,6 +418,41 @@ describe('os migrate stored-references bind', () => { expect((await shareRow(db)).package_id).toBe(A); }, CASE_TIMEOUT_MS); + // [#31699] A table whose unique key carries the package column (R1's grant, + // R11's connection) refuses a bind that would make the row a second row of + // one key. The bind says so by name and writes nothing, never a crash. + // Simulated on R5's row: the update is refused the way the database refuses + // it (a UNIQUE constraint failure), as the connection table's widened key does. + it('a bind the database refuses as a unique violation is refused by name (`duplicate`), writing nothing', async () => { + const db = caseDb(); + const share = await shareRow(db); + const stack = await bootSchemaStack({ + jsonOutput: true, databaseUrl: `file:${db}`, projectRoot: dir, + composeHostStack: true, composeServedPlatform: true, composeAuthGatedSecurity: true, + }); + try { + const engine = stack.kernel.getService('objectql') as StoredReferenceEngine & { registry: any }; + const refusing: StoredReferenceEngine = { + find: (object, options) => engine.find(object, options), + update: async () => { + throw Object.assign(new Error('UNIQUE constraint failed: sys_sharing_rule.package_id'), { code: 'SQLITE_CONSTRAINT_UNIQUE' }); + }, + }; + const outcome = await bindStoredPackageReference(refusing, engine.registry, { table: 'sys_sharing_rule', id: String(share.id), packageId: B }); + expect(outcome).toMatchObject({ outcome: 'refused', reason: 'duplicate' }); + expect((outcome as { message: string }).message).toContain('would be a second one'); + expect((outcome as { candidates?: Array<{ packageId?: string }> }).candidates?.map((c) => c.packageId)).toEqual([A, B]); + + // CONTROL: any other refused write is still thrown. + const failing: StoredReferenceEngine = { ...refusing, update: async () => { throw new Error('disk full'); } }; + await expect(bindStoredPackageReference(failing, engine.registry, { table: 'sys_sharing_rule', id: String(share.id), packageId: B })) + .rejects.toThrow('disk full'); + } finally { + await stack.shutdown(); + } + expect((await shareRow(db)).package_id ?? null).toBeNull(); + }, CASE_TIMEOUT_MS); + it('CONTROL: a database of one package has nothing to bind', async () => { writeArtifact(CONTROL); const db = caseDb(controlDb); diff --git a/packages/cli/src/utils/schema-sync-indexes.integration.test.ts b/packages/cli/src/utils/schema-sync-indexes.integration.test.ts index 76aa1ae709f..b6d48a1cf66 100644 --- a/packages/cli/src/utils/schema-sync-indexes.integration.test.ts +++ b/packages/cli/src/utils/schema-sync-indexes.integration.test.ts @@ -74,8 +74,9 @@ afterEach(async () => { }); describe('[#32460] which indexes the plan reads: the ones apply builds', () => { - it('lists the grant guard, which schema sync builds, and not the activation ledger guard, which only a serving boot builds', () => { - expect(SCHEMA_SYNC_INDEX_MIGRATIONS).toEqual(['ensureUserPermissionSetPackagelessIndex']); + it('lists the grant and connection guards, which schema sync builds, and not the activation ledger guard, which only a serving boot builds', () => { + // [#31699] The connector connection's package-less guard rides the grant's seam. + expect(SCHEMA_SYNC_INDEX_MIGRATIONS).toEqual(['ensureUserPermissionSetPackagelessIndex', 'ensureConnectorConnectionPackagelessIndex']); // Each one is described by the preflight, which every other field is read from. const described = runtimeIndexProbes().map((p) => p.migration); for (const migration of SCHEMA_SYNC_INDEX_MIGRATIONS) expect(described).toContain(migration); @@ -101,6 +102,21 @@ describe('[#32460] collectSchemaSyncIndexes: a step only where apply would build }]); }); + it('[#31699] a connection table missing its guard: one build step on it, described from the preflight', async () => { + await knex.raw( + 'CREATE TABLE sys_connector_connection (id TEXT PRIMARY KEY, organization_id TEXT NOT NULL, ' + + 'connector_name TEXT NOT NULL, connector_package TEXT)', + ); + expect(await collectSchemaSyncIndexes(input())).toEqual([{ + migration: 'ensureConnectorConnectionPackagelessIndex', + table: 'sys_connector_connection', + index: 'uniq_sys_connector_connection_packageless', + keyParts: ['organization_id', 'connector_name'], + rowScope: 'connector_package IS NULL', + status: 'build', + }]); + }); + it('the guard already stands: no step, because the build sends no DDL', async () => { await createGrantTable(); await knex.raw(buildUserPermissionSetPackagelessIndexSql('better-sqlite3')); @@ -137,8 +153,14 @@ describe('[#32460] collectSchemaSyncIndexes: a step only where apply would build it('a seam that answers nothing: unreadable, never read as "already stands"', async () => { const dead = { config: { client: 'better-sqlite3' }, execute: async () => { throw new Error('connection reset'); } }; + // Every owner reads through the one dead seam, so each says so (#31699 added the connection table's). expect(await collectSchemaSyncIndexes(input({ engine: engineOf(dead) }))).toEqual([ expect.objectContaining({ index: GUARD, status: 'unreadable', detail: expect.stringContaining('connection reset') }), + expect.objectContaining({ + index: 'uniq_sys_connector_connection_packageless', + status: 'unreadable', + detail: expect.stringContaining('connection reset'), + }), ]); }); diff --git a/packages/cli/src/utils/schema-sync-indexes.operator-text-21418.test.ts b/packages/cli/src/utils/schema-sync-indexes.operator-text-21418.test.ts index 7d26e325f58..8559cd54bc2 100644 --- a/packages/cli/src/utils/schema-sync-indexes.operator-text-21418.test.ts +++ b/packages/cli/src/utils/schema-sync-indexes.operator-text-21418.test.ts @@ -101,11 +101,15 @@ describe('[#21418] the runtime-owned index listing prints no bound value', () => // The refusal came from the guard's own catalog statement, after the preflight answered. expect(statements.at(-1)).toContain("type = 'index'"); - expect(steps).toHaveLength(1); - expect(steps[0]!.status).toBe('unreadable'); - expect(steps[0]!.detail).toContain('database is locked'); - expect(steps[0]!.detail).not.toContain(SENTINEL); - expect(steps[0]!.detail).not.toContain('refused to run a raw statement'); + // One step per guard schema sync builds: the grant's, and the connector + // connection's (#31699), each read through the same refusing seam. + expect(steps.map((s) => s.migration)).toEqual(['ensureUserPermissionSetPackagelessIndex', 'ensureConnectorConnectionPackagelessIndex']); + for (const step of steps) { + expect(step.status).toBe('unreadable'); + expect(step.detail).toContain('database is locked'); + expect(step.detail).not.toContain(SENTINEL); + expect(step.detail).not.toContain('refused to run a raw statement'); + } const line = plain(steps); expect(line).toContain('database is locked'); @@ -115,10 +119,12 @@ describe('[#21418] the runtime-owned index listing prints no bound value', () => it('a refused engine read: the step is unreadable, its detail and its line carry no sentinel', async () => { const steps = await collectSchemaSyncIndexes({ ...deferredWithWork, engine: () => { throw rawStatementFault(); } }); - expect(steps).toHaveLength(1); - expect(steps[0]!.status).toBe('unreadable'); - expect(steps[0]!.detail).toContain('database is locked'); - expect(steps[0]!.detail).not.toContain(SENTINEL); + expect(steps.map((s) => s.migration)).toEqual(['ensureUserPermissionSetPackagelessIndex', 'ensureConnectorConnectionPackagelessIndex']); + for (const step of steps) { + expect(step.status).toBe('unreadable'); + expect(step.detail).toContain('database is locked'); + expect(step.detail).not.toContain(SENTINEL); + } expect(plain(steps)).not.toContain(SENTINEL); }); }); diff --git a/packages/cli/src/utils/schema-sync-indexes.ts b/packages/cli/src/utils/schema-sync-indexes.ts index c306cac1915..17a73112dc6 100644 --- a/packages/cli/src/utils/schema-sync-indexes.ts +++ b/packages/cli/src/utils/schema-sync-indexes.ts @@ -98,6 +98,10 @@ const SCHEMA_SYNC_INDEX_OWNERS: Readonly> = seam: (mp, engine) => mp.resolveUserPermissionSetIndexSeam(engine), presenceSql: (mp, client) => mp.buildUserPermissionSetPackagelessIndexPresenceSql(client), }, + ensureConnectorConnectionPackagelessIndex: { + seam: (mp, engine) => mp.resolveConnectorConnectionIndexSeam(engine), + presenceSql: (mp, client) => mp.buildConnectorConnectionPackagelessIndexPresenceSql(client), + }, }; /** The migrations {@link collectSchemaSyncIndexes} reads, for the pin that holds the list to its rule. */ diff --git a/packages/cli/src/utils/stored-package-references.ts b/packages/cli/src/utils/stored-package-references.ts index 6e56e981857..a9dfce0fc82 100644 --- a/packages/cli/src/utils/stored-package-references.ts +++ b/packages/cli/src/utils/stored-package-references.ts @@ -99,7 +99,7 @@ import type { PackageScopedHolder, PackageScopedResolution } from '@objectstack/core'; import { PACKAGE_SCOPED_TYPES } from '@objectstack/core'; import { resolvePackageScopedName, type PackageScopedRegistry } from '@objectstack/objectql'; -import { keysetWalk } from '@objectstack/types'; +import { isUniqueViolationError, keysetWalk } from '@objectstack/types'; import { isCustomizationPackage, validateNamespaceNotAddressLiteral } from '@objectstack/spec/kernel'; import { ITEM_KEY_DISCRIMINATORS, installedManifestsOf } from '@objectstack/metadata-core'; import { judgesPackageLessRows, packageLessRowOwners, pairMemberOwners } from '@objectstack/metadata-protocol'; @@ -591,7 +591,7 @@ export interface BindRequest { /** Why a bind wrote nothing. */ export type BindRefusal = | 'unknown-table' | 'report-only' | 'table-not-carried' | 'no-such-row' | 'already-bound' | 'not-asked' - | 'no-name' | 'resolved' | 'not-held' | 'environment-only' | 'outside-closure' | 'not-a-candidate'; + | 'no-name' | 'resolved' | 'not-held' | 'environment-only' | 'outside-closure' | 'not-a-candidate' | 'duplicate'; /** What one bind did. */ export type BindOutcome = @@ -678,11 +678,23 @@ export async function bindStoredPackageReference( // landed between the re-ask above and this one (another bind, a boot's // backfill) wins: this one updates 0 rows and refuses, naming what is stored. // A bound row is never moved, concurrency included. - const written = await engine.update(reference.table, { [packageColumn]: request.packageId }, { - where: { id: { $eq: row.id }, [packageColumn]: { $null: true } }, - multi: true, - context: SYSTEM_CTX, - }); + let written: unknown; + try { + written = await engine.update(reference.table, { [packageColumn]: request.packageId }, { + where: { id: { $eq: row.id }, [packageColumn]: { $null: true } }, + multi: true, + context: SYSTEM_CTX, + }); + } catch (e: unknown) { + // [#31699] A table whose unique key carries the package column (R1's + // grant, R11's connection) refuses a bind that would make the row a second + // row of one key: another row of the same key already names the package. + // Said as what it is, never a crash; the row stays naming no package. + if (!isUniqueViolationError(e)) throw e; + return refuse('duplicate', `${reference.table} "${request.id}" cannot be bound to "${request.packageId}": another row of ` + + `the same key already names that package in ${packageColumn}, so this row would be a second one. Review the pair ` + + 'and remove the row that should not stand. Nothing written.', candidates); + } if (rowsWritten(written) === 0) { const now = await engine.find(reference.table, { where: { id: request.id }, limit: 1, fields: ['id', packageColumn], context: SYSTEM_CTX }); const stored = Array.isArray(now) ? (now[0] as Row | undefined)?.[packageColumn] : undefined; diff --git a/packages/drivers/driver-memory/src/memory-connector-connection-packageless.test.ts b/packages/drivers/driver-memory/src/memory-connector-connection-packageless.test.ts new file mode 100644 index 00000000000..ce21110243e --- /dev/null +++ b/packages/drivers/driver-memory/src/memory-connector-connection-packageless.test.ts @@ -0,0 +1,84 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0150 D4 and D8 row R11, #31699] `sys_connector_connection`'s key gained + * its package column — `(organization_id, connector_package, connector_name)`, + * `unique: 'global'` — and on this driver that is a DECLARED LIMIT, measured + * here, as the grant key's is (`memory-user-permission-set-packageless.test.ts`). + * + * On SQL and Mongo a runtime guard keeps the connections that name no package to + * one per organization and instance (`metadata-protocol`'s + * `connector-connection-packageless-index.ts`, `driver-mongodb`'s + * `RUNTIME_OWNED_UNIQUES`). This driver has no raw-SQL seam for that migration + * and no runtime-owned uniques, so the guard is not built here, and a NULL key + * part exempts a row from the declared key: two package-less connections of one + * instance in one organization are ADMITTED. This file asserts the admission so + * that a future guard seam on this driver turns it red and the limit is + * withdrawn on purpose, not by accident. The connection store is the table's one + * writer and reads before it writes (`service-automation`'s + * `connector-connections.ts`: a connect updates the row it finds), so it writes + * no second row of a connected instance on any driver. + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { InMemoryDriver } from './memory-driver.js'; +import { uniqueConstraintsFromDeclaredIndexes } from './memory-unique-constraint.js'; + +const TABLE = 'sys_connector_connection'; +const NEW_FIELDS = ['organization_id', 'connector_package', 'connector_name']; + +/** The connection object, reduced to what schema sync reads, under a given unique declaration. */ +const connections = (indexes: Array<{ fields: string[]; unique: 'global' | 'organization' }>) => ({ + name: TABLE, + fields: { + id: { type: 'text' }, + organization_id: { type: 'text' }, + connector_name: { type: 'text' }, + connector_package: { type: 'text' }, + }, + indexes, +}); +const current = connections([{ fields: NEW_FIELDS, unique: 'global' }]); +// The earlier declaration listed no organization column; on this driver it was read as the listed column alone. +const previous = connections([{ fields: ['connector_name'], unique: 'organization' }]); + +async function lands(driver: InMemoryDriver, row: Record): Promise { + try { + await driver.create(TABLE, { organization_id: 'org_1', connector_name: 'github', ...row }); + return true; + } catch { + return false; + } +} + +describe('[#31699] driver-memory and the connection key that gained its package column (a declared limit)', () => { + let now: InMemoryDriver; + let old: InMemoryDriver; + + beforeEach(async () => { + now = new InMemoryDriver(); + await now.syncSchema(TABLE, current); + old = new InMemoryDriver(); + await old.syncSchema(TABLE, previous); + }); + + it('reads the declaration as a plain, NULL-distinct column list', () => { + expect(uniqueConstraintsFromDeclaredIndexes(current)).toEqual([{ columns: NEW_FIELDS, nullSafeColumns: [] }]); + }); + + it('packaged connections: two packages admitted, one package twice refused (the key working as declared)', async () => { + expect(await lands(now, { id: 'p1', connector_package: 'com.acme.crm' })).toBe(true); + expect(await lands(now, { id: 'p2', connector_package: 'com.acme.hr' })).toBe(true); + expect(await lands(now, { id: 'p3', connector_package: 'com.acme.crm' })).toBe(false); + }); + + it('THE DECLARED LIMIT: two package-less connections of one instance in one organization are admitted here, where the old key refused the second', async () => { + expect(await lands(old, { id: 'a', connector_package: null })).toBe(true); + expect(await lands(old, { id: 'b', connector_package: null })).toBe(false); + + expect(await lands(now, { id: 'a', connector_package: null })).toBe(true); + // Measured: the NULL package is distinct. SQL and Mongo refuse this row through their runtime guard. + expect(await lands(now, { id: 'b', connector_package: null })).toBe(true); + expect(await now.count(TABLE)).toBe(2); + }); +}); diff --git a/packages/drivers/driver-mongodb/src/mongodb-connector-connection-packageless.test.ts b/packages/drivers/driver-mongodb/src/mongodb-connector-connection-packageless.test.ts new file mode 100644 index 00000000000..8900981724e --- /dev/null +++ b/packages/drivers/driver-mongodb/src/mongodb-connector-connection-packageless.test.ts @@ -0,0 +1,194 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [ADR-0150 D4 and D8 row R11, #31699] ADR-0150 gives `sys_connector_connection` +// the key `(organization_id, connector_package, connector_name)`, which this +// driver builds NULL-distinct (#29278), so under it a connection naming no +// package is constrained no longer. The collection also carries +// `uniq_sys_connector_connection_packageless`: one such connection per +// `(connector_name)` — the key this driver built for the earlier +// `{ fields: ['connector_name'], unique: 'organization' }` (verbatim: no +// row-level tenancy here, #3724), so the widening arm reads it as that key's +// guard. See `RUNTIME_OWNED_UNIQUES` in `mongodb-schema.ts`; the SQL copy is +// metadata-protocol's `connector-connection-packageless-index.ts`. +// +// Two suites, as the grant's `mongodb-user-permission-set-packageless.test.ts` +// has them: the DDL shape and the widening arm against a recording fake `Db` +// (every lane), and the server's answer against a real mongod (opt-in, #5517). + +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import type { Db } from 'mongodb'; +import type { MongoMemoryServer } from 'mongodb-memory-server'; +import { syncCollectionSchema } from './mongodb-schema.js'; +import { MongoDBDriver } from './mongodb-driver.js'; +import { createTestMongod } from './test-mongod.js'; + +const CONNECTIONS = 'sys_connector_connection'; +const GUARD = 'uniq_sys_connector_connection_packageless'; +const NON_NULL_TYPES = [ + 'double', 'string', 'object', 'array', 'binData', 'objectId', 'bool', 'date', + 'regex', 'javascript', 'int', 'timestamp', 'long', 'decimal', 'minKey', 'maxKey', +]; +const nonNull = (fields: string[]) => Object.fromEntries(fields.map((f) => [f, { $type: NON_NULL_TYPES }])); + +const OLD_FIELDS = ['connector_name']; +const NEW_FIELDS = ['organization_id', 'connector_package', 'connector_name']; +const OLD_UNIQUE = `idx_${OLD_FIELDS.join('_')}_unique`; +const NEW_UNIQUE = `idx_${NEW_FIELDS.join('_')}_unique`; + +/** The connection object as service-automation declares it, reduced to what schema sync reads. */ +const connectionSchema = { + name: CONNECTIONS, + fields: { + organization_id: { type: 'text', required: true }, + connector_name: { type: 'text', required: true }, + connector_package: { type: 'text' }, + }, + indexes: [{ fields: NEW_FIELDS, unique: 'global' as const }], +}; +/** The declaration an earlier release synced. */ +const oldConnectionSchema = { ...connectionSchema, indexes: [{ fields: OLD_FIELDS, unique: 'organization' as const }] }; + +/** The old unique exactly as an earlier release's sync built it (verbatim, NULL-distinct, #29278). */ +const oldUnique = { name: OLD_UNIQUE, key: { connector_name: 1 }, unique: true, partialFilterExpression: nonNull(OLD_FIELDS) }; + +/** A stateful recording `Db`, as the grant suite's. */ +function statefulDb(seed: Array>, collection = CONNECTIONS) { + const live = new Map>(seed.map((i) => [i.name as string, i])); + const ops: string[] = []; + const created: Array<{ spec: Record; options: Record }> = []; + const db = { + listCollections: () => ({ toArray: async () => [{ name: collection }] }), + createCollection: async () => {}, + collection: () => ({ + createIndex: async (spec: Record, options: Record) => { + created.push({ spec, options }); + const name = options.name as string; + if (!live.has(name)) { + ops.push(`create ${name}`); + live.set(name, { ...options, key: spec }); + } + }, + indexes: async () => [...live.values()], + dropIndex: async (name: string) => { + ops.push(`drop ${name}`); + live.delete(name); + }, + }), + } as unknown as Db; + return { db, ops, created, names: () => [...live.keys()].sort() }; +} + +describe('the package-less connection index — DDL (recording Db, runs on every lane)', () => { + it('the connection collection gets a partial unique on the old key (connector_name) over connections whose package is null or missing', async () => { + const { db, created } = statefulDb([]); + await syncCollectionSchema(db, CONNECTIONS, connectionSchema, { logger: { warn: vi.fn() } }); + + const guard = created.filter((c) => c.options.name === GUARD); + expect(guard).toHaveLength(1); + expect(Object.keys(guard[0].spec)).toEqual(OLD_FIELDS); + expect(guard[0].options).toEqual({ + name: GUARD, + unique: true, + partialFilterExpression: { ...nonNull(OLD_FIELDS), connector_package: null }, + }); + expect(created.find((c) => c.options.name === NEW_UNIQUE)?.options) + .toMatchObject({ unique: true, partialFilterExpression: nonNull(NEW_FIELDS) }); + }); + + it('no other collection gets it, whatever it declares', async () => { + const { db, created } = statefulDb([], 'lead'); + await syncCollectionSchema(db, 'lead', { ...connectionSchema, name: 'lead' }, { logger: { warn: vi.fn() } }); + expect(created.some((c) => c.options.name === GUARD)).toBe(false); + }); +}); + +describe('the widening arm — an upgraded connection collection (recording Db, runs on every lane)', () => { + it('retires the old (connector_name) unique AFTER the wider key and the package-less guard are created', async () => { + const { db, ops, names } = statefulDb([oldUnique]); + const logger = { warn: vi.fn() }; + await syncCollectionSchema(db, CONNECTIONS, connectionSchema, { logger }); + + expect(names()).not.toContain(OLD_UNIQUE); + expect(names()).toEqual(expect.arrayContaining([NEW_UNIQUE, GUARD])); + expect(ops.at(-1)).toBe(`drop ${OLD_UNIQUE}`); + expect(ops.indexOf(`create ${GUARD}`)).toBeLessThan(ops.indexOf(`drop ${OLD_UNIQUE}`)); + expect(logger.warn).toHaveBeenCalledTimes(1); + expect(logger.warn.mock.calls[0][1]).toEqual({ collection: CONNECTIONS, retired: OLD_UNIQUE, oldKey: OLD_FIELDS, newKey: NEW_FIELDS }); + }); + + it('CONTROL — the same shapes on another collection (no guard) keep the old unique', async () => { + const { db, ops } = statefulDb([oldUnique], 'lead'); + await syncCollectionSchema(db, 'lead', { ...connectionSchema, name: 'lead' }, { logger: { warn: vi.fn() } }); + expect(ops).not.toContain(`drop ${OLD_UNIQUE}`); + }); +}); + +// --------------------------------------------------------------------------- +// Against a real mongod (opt-in, #5517) +// --------------------------------------------------------------------------- + +const sharedMongod: MongoMemoryServer | undefined = await createTestMongod('MongoDB connection package-less'); + +afterAll(async () => { + await sharedMongod?.stop(); +}); + +async function outcome(write: () => Promise): Promise<'ok' | number> { + try { + await write(); + return 'ok'; + } catch (error: any) { + return typeof error?.code === 'number' ? error.code : -1; + } +} + +describe.skipIf(!sharedMongod)('the package-less connection index — against a real mongod', () => { + const mongod = sharedMongod as MongoMemoryServer; + let driver: MongoDBDriver; + let oldDriver: MongoDBDriver; + + beforeAll(async () => { + driver = new MongoDBDriver({ url: mongod.getUri(), database: 'connection_packageless' }); + await driver.connect(); + await driver.syncSchema(CONNECTIONS, connectionSchema); + oldDriver = new MongoDBDriver({ url: mongod.getUri(), database: 'connection_packageless_old_key' }); + await oldDriver.connect(); + await oldDriver.syncSchema(CONNECTIONS, oldConnectionSchema); + }, 90_000); + + afterAll(async () => { + await driver?.disconnect(); + await oldDriver?.disconnect(); + }); + + const coll = (d: MongoDBDriver) => ((d as any).db as Db).collection(CONNECTIONS); + const row = (id: string, extra: Record) => ({ id, organization_id: 'org_1', connector_name: 'github', ...extra }); + + it('side by side with the old key: refuses what it refused among package-less rows, and admits a second package\'s instance of the name', async () => { + const rows: Array<[string, Record]> = [ + ['n1', {}], + ['n2', {}], + ['n3', { connector_package: null }], + ['p1', { connector_package: 'com.acme.crm' }], + ['p2', { connector_package: 'com.acme.hr' }], + ['p3', { connector_package: 'com.acme.crm' }], + ]; + const answers: Array<{ id: string; old: 'ok' | number; now: 'ok' | number }> = []; + for (const [id, extra] of rows) { + answers.push({ + id, + old: await outcome(() => coll(oldDriver).insertOne(row(id, extra))), + now: await outcome(() => coll(driver).insertOne(row(id, extra))), + }); + } + expect(answers).toEqual([ + { id: 'n1', old: 'ok', now: 'ok' }, + { id: 'n2', old: 11000, now: 11000 }, + { id: 'n3', old: 11000, now: 11000 }, + // The old (connector_name) key refused every second row of the name. + { id: 'p1', old: 11000, now: 'ok' }, + { id: 'p2', old: 11000, now: 'ok' }, + { id: 'p3', old: 11000, now: 11000 }, + ]); + }); +}); diff --git a/packages/drivers/driver-mongodb/src/mongodb-schema.ts b/packages/drivers/driver-mongodb/src/mongodb-schema.ts index f7ebf7d8668..39e061c4a99 100644 --- a/packages/drivers/driver-mongodb/src/mongodb-schema.ts +++ b/packages/drivers/driver-mongodb/src/mongodb-schema.ts @@ -490,6 +490,15 @@ interface IndexDef { * organization is exempt through that part's non-null type list, as it was * under the old three-part unique this driver built NULL-distinct. * + * `sys_connector_connection` is the same case on the connector connection + * (ADR-0150 D8 row R11, #31699): its key `(organization_id, connector_package, + * connector_name)` gained the nullable package column. This driver built the + * earlier `{ fields: ['connector_name'], unique: 'organization' }` verbatim, as + * `(connector_name)` alone (no row-level tenancy here, #3724), so the guard is + * keyed on exactly that — the narrower key {@link retireWidenedUniques} asks a + * guard of — over the connections naming no package + * (`connector-connection-packageless-index.ts` on SQL keys it per organization). + * * Keyed by collection name, never a generic rule: it widens nothing any other * collection declares. */ @@ -523,6 +532,19 @@ const RUNTIME_OWNED_UNIQUES: Readonly [{ + name: CONNECTIONS, + fields: { + // As service-automation declares them: the package-id width class. + organization_id: { type: 'text', required: true, maxLength: 255 }, + connector_name: { type: 'text', required: true, maxLength: 255 }, + connector_package: { type: 'text', maxLength: 255 }, + }, + indexes, +}]; + +describe('the connection key widened by its package column — a real SQLite database', () => { + let driver: SqlDriver | undefined; + afterEach(async () => { + await driver?.disconnect(); + driver = undefined; + }); + + const uniqueIndexes = async (): Promise> => + (driver as any).knex.raw( + `SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = '${CONNECTIONS}' AND name LIKE 'uniq_%' ORDER BY name`, + ); + const columnsOf = (sql: string | null) => /\(([^)]*)\)/.exec(sql ?? '')?.[1]?.replace(/`/g, '') ?? ''; + const drift = async () => ((await driver!.detectManagedDrift()) as any[]).filter((e) => e.table === CONNECTIONS); + const lands = async (id: string, pkg: string | null): Promise => { + try { + await (driver as any).knex(CONNECTIONS).insert({ id, organization_id: 'org_1', connector_name: 'github', connector_package: pkg }); + return true; + } catch { + return false; + } + }; + + async function upgraded(next = NEW_INDEXES as unknown[]): Promise<{ oldName: string; newName: string }> { + driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + (driver as any).logger = { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() }; + // The database an earlier release built… + await driver.initObjects(connections(OLD_INDEXES) as any); + const before = await uniqueIndexes(); + expect(before.map((i) => [i.name, columnsOf(i.sql)])).toEqual([[OLD_KEY_NAME, 'organization_id, connector_name']]); + // …booted by this release's declaration. + await driver.initObjects(connections(next) as any); + const after = await uniqueIndexes(); + const newName = after.find((i) => columnsOf(i.sql) === 'organization_id, connector_package, connector_name')?.name; + expect(newName).toBeTruthy(); + return { oldName: before[0].name, newName: newName! }; + } + + it('the old key\'s name is the one metadata-protocol builds where its guard has no form', () => { + expect(buildIndexName(CONNECTIONS, ['organization_id', 'connector_name'], true)).toBe(OLD_KEY_NAME); + }); + + it('without the package-less guard the old key is KEPT: no replace, no orphan drop', async () => { + const { oldName } = await upgraded(); + const plan = await drift(); + expect(plan).toEqual([]); + expect((await uniqueIndexes()).map((i) => i.name)).toContain(oldName); + // Still refusing what it refused, the second package's connection among it. + expect(await lands('a', 'com.acme.crm')).toBe(true); + expect(await lands('b', 'com.acme.hr')).toBe(false); + expect(await lands('c', null)).toBe(false); + }); + + it('with the guard: one SAFE replace, applied without allowDestructive; re-plan empty; nothing the old key refused among package-less rows is admitted', async () => { + const { oldName, newName } = await upgraded(); + await (driver as any).knex.raw(GUARD_SQL); + + const plan = await drift(); + expect(plan.map((e) => [e.op.type, e.category])).toEqual([['replace_unique_index', 'safe']]); + expect(plan[0].op).toMatchObject({ dropIndexNames: [oldName], createIndexName: newName }); + expect(plan[0].message).toContain('connector_package is nullable'); + + const { applied, skipped } = await driver!.applyMigrationEntries(plan); + expect([applied.length, skipped]).toEqual([1, []]); + expect((await uniqueIndexes()).map((i) => i.name).sort()).toEqual([GUARD_NAME, newName].sort()); + expect(await drift()).toEqual([]); + + expect(await lands('n1', null)).toBe(true); + expect(await lands('n2', null)).toBe(false); + expect(await lands('p1', 'com.acme.crm')).toBe(true); + expect(await lands('p2', 'com.acme.hr')).toBe(true); + expect(await lands('p3', 'com.acme.crm')).toBe(false); + + // A second boot of this release leaves everything as it is. + await driver!.initObjects(connections(NEW_INDEXES) as any); + expect(await drift()).toEqual([]); + }); + + it('CONTROL — spelled `unique: \'organization\'`, the old key is an orphan whose drop is DESTRUCTIVE, and a safe apply keeps it', async () => { + const { oldName } = await upgraded([{ fields: ['connector_package', 'connector_name'], unique: 'organization' }]); + await (driver as any).knex.raw(GUARD_SQL); + const plan = await drift(); + expect(plan.map((e) => [e.op.type, e.category])).toEqual([['drop_index', 'destructive']]); + expect(plan[0].op).toMatchObject({ indexName: oldName }); + await driver!.applyMigrationEntries(plan.filter((e) => e.category === 'safe')); + expect(await lands('a', 'com.acme.crm')).toBe(true); + expect(await lands('b', 'com.acme.hr')).toBe(false); + }); +}); + +// ── The live cells ───────────────────────────────────────────────────────── + +/** `buildConnectorConnectionPackagelessIndexSql('mysql2')` in metadata-protocol, verbatim. */ +const MYSQL_GUARD_SQL = + `CREATE UNIQUE INDEX ${GUARD_NAME} ON ${CONNECTIONS} ` + + '((CASE WHEN connector_package IS NULL THEN unhex(sha2(concat(organization_id, 0x1f, connector_name), 256)) END))'; + +for (const cell of [PG_CELL, MYSQL_CELL]) { + declareDialectCell(cell, 'connection key widened by its package column (#31699)', (c) => { + describe(`the connection key widened by its package column on ${c.label}`, () => { + let live: SqlDriver | undefined; + afterEach(async () => { + await live?.execute(`drop table if exists ${CONNECTIONS}`).catch(() => {}); + await live?.disconnect().catch(() => {}); + live = undefined; + }); + + const lands = async (id: string, pkg: string | null): Promise => { + try { + await (live as any).knex(CONNECTIONS).insert({ id, organization_id: 'org_1', connector_name: 'github', connector_package: pkg }); + return true; + } catch { + return false; + } + }; + const drift = async () => ((await live!.detectManagedDrift()) as any[]).filter((e) => e.table === CONNECTIONS); + + it(c.id === 'pg' + ? 'with the guard: one SAFE replace, applied; re-plan empty; a second package admitted, a second package-less row refused' + : 'DECLARED LIMIT: the functional guard is not read as the partial guard, so the old key is KEPT and still refuses a second package', + async () => { + live = new SqlDriver(c.config()); + (live as any).logger = { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() }; + await live.execute(`drop table if exists ${CONNECTIONS}`); + await live.initObjects(connections(OLD_INDEXES) as any); + await live.initObjects(connections(NEW_INDEXES) as any); + expect(await drift()).toEqual([]); + await live.execute(c.id === 'pg' ? GUARD_SQL : MYSQL_GUARD_SQL); + + const plan = await drift(); + if (c.id === 'pg') { + expect(plan.map((e) => [e.op.type, e.category])).toEqual([['replace_unique_index', 'safe']]); + expect(plan[0].op).toMatchObject({ dropIndexNames: [OLD_KEY_NAME] }); + const { applied, skipped } = await live.applyMigrationEntries(plan); + expect([applied.length, skipped]).toEqual([1, []]); + expect(await drift()).toEqual([]); + expect(await lands('p1', 'com.acme.crm')).toBe(true); + expect(await lands('p2', 'com.acme.hr')).toBe(true); + expect(await lands('p3', 'com.acme.crm')).toBe(false); + expect(await lands('n1', null)).toBe(true); + expect(await lands('n2', null)).toBe(false); + } else { + // Nothing offered — neither the replace nor an orphan drop of either index. + expect(plan.filter((e) => String(e.op.type).endsWith('_index'))).toEqual([]); + expect(await lands('p1', 'com.acme.crm')).toBe(true); + expect(await lands('p2', 'com.acme.hr')).toBe(false); + expect(await lands('n1', null)).toBe(false); + } + }); + }); + }); +} diff --git a/packages/metadata-protocol/src/index.ts b/packages/metadata-protocol/src/index.ts index 7c745a51ef8..2b102ceb6a5 100644 --- a/packages/metadata-protocol/src/index.ts +++ b/packages/metadata-protocol/src/index.ts @@ -107,6 +107,28 @@ export type { UserPermissionSetGuardPassOutcome, } from './migrations/user-permission-set-packageless-index.js'; +// [ADR-0150 D4 and D8 row R11, #31699] `sys_connector_connection`'s one +// connection per (organization_id, connector_name) among the connections that +// name no package — the grant guard's case on the connection table, whose key +// ADR-0150 D4 widens with the NULL-distinct `connector_package`. +export { + ensureConnectorConnectionPackagelessIndex, + createConnectorConnectionGuardAtSchemaSync, + buildConnectorConnectionPackagelessIndexSql, + buildConnectorConnectionPackagelessIndexPresenceSql, + buildConnectorConnectionPackagelessDuplicateProbeSql, + resolveConnectorConnectionIndexSeam, + buildConnectorConnectionOldKeySql, + CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME, + CONNECTOR_CONNECTION_PACKAGELESS_INDEX_COLUMNS, + CONNECTOR_CONNECTION_OLD_KEY_INDEX_NAME, +} from './migrations/connector-connection-packageless-index.js'; +export type { + EnsureConnectorConnectionPackagelessIndexResult, + EnsureConnectorConnectionPackagelessIndexStatus, + ConnectorConnectionGuardPassOutcome, +} from './migrations/connector-connection-packageless-index.js'; + // [#8629] `sys_setting`'s declared ROW IDENTITY, delivered as a runtime // NULL-safe UNIQUE migration — the `ensureOverlayIndex` paradigm again, for the // object whose `user_id` key part is NULL on every tenant- and global-scope row diff --git a/packages/metadata-protocol/src/migrations/connector-connection-packageless-index.live-mysql.test.ts b/packages/metadata-protocol/src/migrations/connector-connection-packageless-index.live-mysql.test.ts new file mode 100644 index 00000000000..cd140c12ec8 --- /dev/null +++ b/packages/metadata-protocol/src/migrations/connector-connection-packageless-index.live-mysql.test.ts @@ -0,0 +1,159 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The connector connection table's package-less index on a LIVE MySQL / + * MariaDB (ADR-0150 D4 and D8 row R11, #31699) — the grant guard's live file + * (`user-permission-set-packageless-index.live-mysql.test.ts`) on this table. + * + * - MySQL (8.0.13+) builds the functional key part over the digest; MariaDB a + * UNIQUE key over an INVISIBLE generated column carrying it. A second + * package-less connection of one `(organization_id, connector_name)` is + * refused, two packages are admitted, and a second boot finds the key in + * `information_schema.statistics` and sends no DDL. + * - Over real rows: among package-less connections nothing the old + * `(organization_id, connector_name)` key refused is admitted. The old key is + * built in a sibling table as `driver-sql` builds a plain UNIQUE over TEXT + * columns here (a hash-shadow column and a UNIQUE key over it). + * + * Needs `OS_TEST_MYSQL_URL` and reports a named SKIP without one; + * `OS_EXPECT_LIVE_DIALECT_MATRIX=1` turns a missing URL into a failure. Runs in + * its own database (`currentLiveMysqlDatabase`). + */ + +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import mysql from 'mysql2/promise'; + +import { + CONNECTOR_CONNECTION_TABLE, + buildConnectorConnectionPackagelessIndexPresenceSql, + ensureConnectorConnectionPackagelessIndex, +} from './connector-connection-packageless-index.js'; +import { currentLiveMysqlDatabase } from './live-mysql-database.testkit.js'; +import type { IndexExec } from './partial-index-probe.js'; + +const MYSQL_URL = process.env.OS_TEST_MYSQL_URL; +const EXPECT_LIVE = process.env.OS_EXPECT_LIVE_DIALECT_MATRIX === '1'; + +if (EXPECT_LIVE && !MYSQL_URL) { + describe('connection package-less index — live MySQL / MariaDB', () => { + it('OS_TEST_MYSQL_URL must be set on a runner that declared it provisioned', () => { + throw new Error('OS_EXPECT_LIVE_DIALECT_MATRIX=1 without OS_TEST_MYSQL_URL: the live cell would have been skipped.'); + }); + }); +} + +const quietLogger = () => ({ error: vi.fn(), warn: vi.fn(), info: vi.fn() }); + +/** The sibling table carrying the key this one replaced. */ +const OLD_KEY_TABLE = 'old_key_connector_connection'; + +describe.skipIf(!MYSQL_URL)('connection package-less index on a LIVE MySQL / MariaDB', () => { + let conn: mysql.Connection; + let database: string; + let mariadb = false; + const exec: IndexExec = async (sql: string) => (await conn.query(sql))[0]; + + const insertInto = async (table: string, id: string, pkg: string | null, org = 'org_1'): Promise => { + try { + await conn.query( + `INSERT INTO ${table} (id, organization_id, connector_name, connector_package) ` + + "VALUES (?, ?, 'github', ?)", + [id, org, pkg], + ); + return true; + } catch { + return false; + } + }; + const insert = (id: string, pkg: string | null, org = 'org_1') => + insertInto(CONNECTOR_CONNECTION_TABLE, id, pkg, org); + + beforeAll(async () => { + database = currentLiveMysqlDatabase(); + conn = await mysql.createConnection(MYSQL_URL!); + await conn.query(`CREATE DATABASE IF NOT EXISTS \`${database}\``); + await conn.query(`USE \`${database}\``); + const [rows] = await conn.query('SELECT VERSION() AS v'); + mariadb = /mariadb/i.test(String((rows as Array<{ v: string }>)[0]?.v)); + }); + + afterAll(async () => { + if (!conn) return; + await conn.query(`DROP DATABASE IF EXISTS \`${database}\``); + await conn.end(); + }); + + beforeEach(async () => { + for (const table of [CONNECTOR_CONNECTION_TABLE, OLD_KEY_TABLE]) { + await conn.query(`DROP TABLE IF EXISTS ${table}`); + await conn.query( + `CREATE TABLE ${table} (id VARCHAR(255) PRIMARY KEY, organization_id TEXT NOT NULL, ` + + 'connector_name TEXT NOT NULL, connector_package TEXT)', + ); + } + // The old key, as driver-sql keys plain parts over TEXT columns on MySQL. + await conn.query( + `ALTER TABLE ${OLD_KEY_TABLE} ADD COLUMN uniq_old_key__hash VARBINARY(32) GENERATED ALWAYS AS ` + + '(unhex(sha2(concat(organization_id, 0x1f, connector_name), 256))) VIRTUAL, ' + + 'ADD UNIQUE KEY uniq_old_key (uniq_old_key__hash)', + ); + }); + + it('MySQL builds the functional key part, MariaDB the INVISIBLE carrier (second package-less connection refused, two packages admitted)', async () => { + const log = quietLogger(); + const presence = buildConnectorConnectionPackagelessIndexPresenceSql('mysql2')!; + expect(await exec(presence)).toHaveLength(0); + expect(await ensureConnectorConnectionPackagelessIndex(exec, log, { client: 'mysql2' })).toEqual({ status: 'created' }); + // `information_schema.statistics` lists the functional key and MariaDB's key over its carrier alike. + expect((await exec(presence) as unknown[]).length).toBeGreaterThan(0); + if (mariadb) { + // The carrier never reaches `SELECT *` (INVISIBLE). + await insert('a0', null); + const [rows] = await conn.query(`SELECT * FROM ${CONNECTOR_CONNECTION_TABLE}`); + expect(Object.keys((rows as Array>)[0] ?? {})).toEqual([ + 'id', 'organization_id', 'connector_name', 'connector_package', + ]); + await conn.query(`DELETE FROM ${CONNECTOR_CONNECTION_TABLE}`); + } + expect(await insert('a', null)).toBe(true); + expect(await insert('b', null)).toBe(false); + expect(await insert('p1', 'com.acme.crm')).toBe(true); + expect(await insert('p2', 'com.acme.hr')).toBe(true); + // A second boot finds it in the catalog and sends nothing the server would refuse: no CREATE, no ALTER. + const seen: string[] = []; + const recording: IndexExec = (sql: string) => (seen.push(sql), exec(sql)); + expect(await ensureConnectorConnectionPackagelessIndex(recording, log, { client: 'mysql2' })).toEqual({ status: 'created' }); + expect(seen.filter((sql) => /^\s*(CREATE|ALTER|DROP)\b/i.test(sql))).toEqual([]); + expect(log.error).not.toHaveBeenCalled(); + }); + + it('among package-less connections admits nothing the old key refused; the store alone admits a packaged connection beside a package-less one', async () => { + expect(await ensureConnectorConnectionPackagelessIndex(exec, quietLogger(), { client: 'mysql2' })).toEqual({ status: 'created' }); + const rows: Array<[string, string | null]> = [ + ['n1', null], + ['n2', null], + // The fixture builds the guard alone, not the declared key, so only + // the packaged row beside n1 is read here. + ['m1', 'com.acme.crm'], + ]; + const answers: Array<{ id: string; old: boolean; now: boolean }> = []; + for (const [id, pkg] of rows) { + answers.push({ id, old: await insertInto(OLD_KEY_TABLE, id, pkg), now: await insert(id, pkg) }); + } + expect(answers).toEqual([ + { id: 'n1', old: true, now: true }, + { id: 'n2', old: false, now: false }, + { id: 'm1', old: false, now: true }, + ]); + }); + + it('existing package-less duplicates: conflict, no row touched', async () => { + await insert('a', null); + await insert('b', null); + const log = quietLogger(); + expect((await ensureConnectorConnectionPackagelessIndex(exec, log, { client: 'mysql2' })).status).toBe('conflict'); + const [rows] = await conn.query(`SELECT COUNT(*) AS n FROM ${CONNECTOR_CONNECTION_TABLE}`); + expect(Number((rows as Array<{ n: number }>)[0]?.n)).toBe(2); + expect(log.error).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/metadata-protocol/src/migrations/connector-connection-packageless-index.live-postgres.test.ts b/packages/metadata-protocol/src/migrations/connector-connection-packageless-index.live-postgres.test.ts new file mode 100644 index 00000000000..a0402f746d1 --- /dev/null +++ b/packages/metadata-protocol/src/migrations/connector-connection-packageless-index.live-postgres.test.ts @@ -0,0 +1,208 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The connector connection table's package-less index on a LIVE PostgreSQL + * (ADR-0150 D4 and D8 row R11, #31699) — the dialect whose answer the SQLite + * suite cannot give. The grant guard's live file + * (`user-permission-set-packageless-index.live-postgres.test.ts`) on this table. + * + * - The partial form is built; a second package-less connection of one + * `(organization_id, connector_name)` is refused, the instance of two + * packages is admitted, and a second boot is a no-op. + * - The catalog read before any DDL: absent, then present, and a second boot + * with a write open on the table sends no DDL, where `CREATE … IF NOT + * EXISTS` would wait for the table's SHARE lock (a 2 s `lock_timeout` fails it). + * - Measured over real rows: among package-less connections nothing the old + * `(organization_id, connector_name)` key refused is admitted. The old key is + * built as knex compiles it here (a UNIQUE constraint) in a sibling table, and + * both tables take the same rows. + * - Existing duplicates fail the build with the keys named, and no row is + * touched. + * + * Needs `OS_TEST_POSTGRES_URL` and reports a named SKIP without one; + * `OS_EXPECT_LIVE_DIALECT_MATRIX=1` turns a missing URL into a failure, as in + * the sibling live files. Runs in its own schema, named by + * `currentLiveMysqlDatabase` (the per-file resolver these files share). + */ + +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import pg from 'pg'; + +import { + CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME, + CONNECTOR_CONNECTION_TABLE, + buildConnectorConnectionPackagelessIndexPresenceSql, + ensureConnectorConnectionPackagelessIndex, +} from './connector-connection-packageless-index.js'; +import { currentLiveMysqlDatabase } from './live-mysql-database.testkit.js'; +import type { IndexExec } from './partial-index-probe.js'; + +const PG_URL = process.env.OS_TEST_POSTGRES_URL; +const EXPECT_LIVE = process.env.OS_EXPECT_LIVE_DIALECT_MATRIX === '1'; + +if (EXPECT_LIVE && !PG_URL) { + describe('connection package-less index — live PostgreSQL', () => { + it('OS_TEST_POSTGRES_URL must be set on a runner that declared it provisioned', () => { + throw new Error('OS_EXPECT_LIVE_DIALECT_MATRIX=1 without OS_TEST_POSTGRES_URL: the live cell would have been skipped.'); + }); + }); +} + +const quietLogger = () => ({ error: vi.fn(), warn: vi.fn(), info: vi.fn() }); + +/** The sibling table carrying the key this one replaced. */ +const OLD_KEY_TABLE = 'old_key_connector_connection'; + +describe.skipIf(!PG_URL)('connection package-less index on a LIVE PostgreSQL', () => { + let client: pg.Client; + const exec: IndexExec = (sql: string) => client.query(sql); + let schema: string; + + const insertInto = async ( + table: string, + id: string, + pkg: string | null, + org = 'org_1', + ): Promise => { + try { + await client.query( + `INSERT INTO ${table} (id, organization_id, connector_name, connector_package) ` + + "VALUES ($1, $2, 'github', $3)", + [id, org, pkg], + ); + return true; + } catch { + return false; + } + }; + const insert = (id: string, pkg: string | null, org = 'org_1') => + insertInto(CONNECTOR_CONNECTION_TABLE, id, pkg, org); + + beforeAll(async () => { + schema = currentLiveMysqlDatabase(); + client = new pg.Client({ connectionString: PG_URL }); + await client.connect(); + await client.query(`CREATE SCHEMA IF NOT EXISTS "${schema}"`); + await client.query(`SET search_path TO "${schema}"`); + }); + + afterAll(async () => { + if (!client) return; + await client.query('SET search_path TO "$user", public'); + await client.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`); + await client.end(); + }); + + beforeEach(async () => { + for (const table of [CONNECTOR_CONNECTION_TABLE, OLD_KEY_TABLE]) { + await client.query(`DROP TABLE IF EXISTS ${table}`); + await client.query( + `CREATE TABLE ${table} (id TEXT PRIMARY KEY, organization_id TEXT NOT NULL, ` + + 'connector_name TEXT NOT NULL, connector_package TEXT)', + ); + } + // The declared key as knex compiles it on PostgreSQL: a UNIQUE constraint. + await client.query( + `ALTER TABLE ${CONNECTOR_CONNECTION_TABLE} ADD CONSTRAINT uniq_sys_connector_connection_declared ` + + 'UNIQUE (organization_id, connector_package, connector_name)', + ); + // The key it replaced, the same way. + await client.query( + `ALTER TABLE ${OLD_KEY_TABLE} ADD CONSTRAINT uniq_old_key ` + + 'UNIQUE (organization_id, connector_name)', + ); + }); + + it('builds the partial index; a second package-less connection is refused, two packages admitted', async () => { + expect(await insert('a', null)).toBe(true); + expect(await insert('b', null)).toBe(true); // the hole, before the index + await client.query(`DELETE FROM ${CONNECTOR_CONNECTION_TABLE} WHERE id = 'b'`); + + const log = quietLogger(); + expect(await ensureConnectorConnectionPackagelessIndex(exec, log, { client: 'pg' })).toEqual({ status: 'created' }); + const { rows } = await client.query<{ indexdef: string }>( + `SELECT pg_get_indexdef(to_regclass('"${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME}"')) AS indexdef`, + ); + expect(rows[0]?.indexdef).toContain('(organization_id, connector_name) WHERE (connector_package IS NULL)'); + + expect(await insert('b', null)).toBe(false); + expect(await insert('p1', 'com.acme.crm')).toBe(true); + expect(await insert('p2', 'com.acme.hr')).toBe(true); + expect(await insert('p1b', 'com.acme.crm')).toBe(false); + // A second boot is a no-op. + expect(await ensureConnectorConnectionPackagelessIndex(exec, log, { client: 'pg' })).toEqual({ status: 'created' }); + expect(log.error).not.toHaveBeenCalled(); + }); + + it('reads the catalog before any DDL: absent, then present; a second boot sends no DDL while a write holds the table', async () => { + const presence = buildConnectorConnectionPackagelessIndexPresenceSql('pg')!; + expect((await client.query(presence)).rows).toHaveLength(0); + expect(await ensureConnectorConnectionPackagelessIndex(exec, quietLogger(), { client: 'pg' })).toEqual({ status: 'created' }); + expect((await client.query(presence)).rows).toHaveLength(1); + + // `CREATE UNIQUE INDEX IF NOT EXISTS` waits for the table's SHARE lock + // before it finds the name taken, so with an open write it would block + // here and fail at the timeout; the catalog read does not wait. + const writer = new pg.Client({ connectionString: PG_URL }); + await writer.connect(); + try { + await writer.query(`SET search_path TO "${schema}"`); + await writer.query('BEGIN'); + await writer.query( + `INSERT INTO ${CONNECTOR_CONNECTION_TABLE} (id, organization_id, connector_name, connector_package) ` + + "VALUES ('w1', 'org_9', 'github', 'com.acme.crm')", + ); + await client.query("SET lock_timeout = '2s'"); + const seen: string[] = []; + const recording: IndexExec = (sql: string) => (seen.push(sql), client.query(sql)); + const log = quietLogger(); + expect(await ensureConnectorConnectionPackagelessIndex(recording, log, { client: 'pg' })).toEqual({ status: 'created' }); + expect(seen.filter((sql) => /^\s*(CREATE|ALTER|DROP)\b/i.test(sql))).toEqual([]); + expect(log.error).not.toHaveBeenCalled(); + } finally { + await client.query('RESET lock_timeout'); + await writer.query('ROLLBACK'); + await writer.end(); + } + }); + + // What the store alone admits that the old key refused, a packaged + // connection beside a package-less one; the connection store, the table's + // one writer, updates the row it finds and never writes it. + it('among package-less connections admits nothing the old key refused; a second package\'s instance is admitted', async () => { + expect(await ensureConnectorConnectionPackagelessIndex(exec, quietLogger(), { client: 'pg' })).toEqual({ status: 'created' }); + const rows: Array<[string, string | null]> = [ + ['n1', null], + ['n2', null], + ['m1', 'com.acme.crm'], + ['m2', 'com.acme.crm'], + ['h1', 'com.acme.hr'], + ]; + const answers: Array<{ id: string; old: boolean; now: boolean }> = []; + for (const [id, pkg] of rows) { + answers.push({ id, old: await insertInto(OLD_KEY_TABLE, id, pkg), now: await insert(id, pkg) }); + } + expect(answers).toEqual([ + { id: 'n1', old: true, now: true }, + { id: 'n2', old: false, now: false }, + { id: 'm1', old: false, now: true }, + { id: 'm2', old: false, now: false }, + { id: 'h1', old: false, now: true }, + ]); + }); + + it('existing package-less duplicates: conflict naming the key, no row touched', async () => { + await insert('a', null); + await insert('b', null); + const log = quietLogger(); + expect((await ensureConnectorConnectionPackagelessIndex(exec, log, { client: 'pg' })).status).toBe('conflict'); + expect( + (await client.query(`SELECT id, connector_package FROM ${CONNECTOR_CONNECTION_TABLE} ORDER BY id`)).rows, + ).toEqual([ + { id: 'a', connector_package: null }, + { id: 'b', connector_package: null }, + ]); + expect(log.error).toHaveBeenCalledTimes(1); + expect(String(log.error.mock.calls[0]?.[0] ?? '')).toContain('organization_id=org_1, connector_name=github (2 connections)'); + }); +}); diff --git a/packages/metadata-protocol/src/migrations/connector-connection-packageless-index.test.ts b/packages/metadata-protocol/src/migrations/connector-connection-packageless-index.test.ts new file mode 100644 index 00000000000..05344b99701 --- /dev/null +++ b/packages/metadata-protocol/src/migrations/connector-connection-packageless-index.test.ts @@ -0,0 +1,615 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { DatabaseSync } from 'node:sqlite'; +import { inspect } from 'node:util'; + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; + +import { + CONNECTOR_CONNECTION_OLD_KEY_INDEX_NAME, + CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME, + CONNECTOR_CONNECTION_PACKAGELESS_SHADOW_COLUMN, + CONNECTOR_CONNECTION_TABLE, + buildConnectorConnectionOldKeySql, + buildConnectorConnectionPackagelessDuplicateProbeSql, + buildConnectorConnectionPackagelessIndexPresenceSql, + buildConnectorConnectionPackagelessIndexSql, + buildConnectorConnectionPackagelessMariaDbKeySql, + buildConnectorConnectionPackagelessMariaDbSql, + createConnectorConnectionGuardAtSchemaSync, + ensureConnectorConnectionPackagelessIndex, +} from './connector-connection-packageless-index.js'; +import type { IndexExec } from './partial-index-probe.js'; + +/** + * The guard's own catalog read (`buildConnectorConnectionPackagelessIndexPresenceSql`), + * told apart from the table-presence read the recording fixtures below answer + * "present": only the guard's read names the index. Those fixtures answer it + * with no row, so the build they exercise still runs. + */ +const isGuardPresenceRead = (sql: string): boolean => + /^SELECT 1 FROM /.test(sql) && sql.includes(`'${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME}'`); + +/** A statement that changes the schema, as opposed to a read. */ +const isDdl = (sql: string): boolean => /^\s*(CREATE|ALTER|DROP)\b/i.test(sql); + +/** + * `sys_connector_connection` — one connection per `(organization_id, + * connector_name)` among the connections that name no package, beside the + * NULL-distinct `(organization_id, connector_package, connector_name)` key + * ADR-0150 D4 gives the connection (#31699), which these fixtures declare. + * + * Real SQLite (`node:sqlite`), because the claim is about what a UNIQUE index + * does with NULLs over real rows. PostgreSQL and MySQL are measured in the + * `.live-postgres` / `.live-mysql` siblings. + */ +describe('sys_connector_connection: one package-less connection per (organization_id, connector_name)', () => { + let db: DatabaseSync; + let exec: IndexExec; + + /** + * What `SqlDriver.syncDeclaredIndexes` builds on SQLite for the declared key + * `{ fields: ['organization_id', 'connector_package', 'connector_name'], unique: 'global' }`: + * a plain, NULL-distinct UNIQUE. + */ + const DECLARED_INDEX_DDL = + 'CREATE UNIQUE INDEX `uniq_sys_connector_connection_declared` on `sys_connector_connection` ' + + '(`organization_id`, `connector_package`, `connector_name`)'; + /** The key this one replaced, as the driver built it for `{ fields: ['connector_name'], unique: 'organization' }`. */ + const OLD_INDEX_DDL = + 'CREATE UNIQUE INDEX `uniq_sys_connector_connection_old` on `sys_connector_connection` ' + + '(`organization_id`, `connector_name`)'; + + const createTable = (handle: DatabaseSync, ddl: string): void => { + handle.exec(`CREATE TABLE ${CONNECTOR_CONNECTION_TABLE} ( + id TEXT PRIMARY KEY, organization_id TEXT NOT NULL, connector_name TEXT NOT NULL, connector_package TEXT + );`); + handle.exec(ddl); + }; + const insertInto = (handle: DatabaseSync) => ( + id: string, + pkg: string | null, + org = 'org_1', + name = 'github', + ): boolean => { + try { + handle + .prepare( + `INSERT INTO ${CONNECTOR_CONNECTION_TABLE} (id, organization_id, connector_name, connector_package) VALUES (?, ?, ?, ?)`, + ) + .run(id, org, name, pkg); + return true; + } catch { + return false; + } + }; + let insert: ReturnType; + const indexDdl = (name: string): string | undefined => + (db.prepare("SELECT sql FROM sqlite_master WHERE type='index' AND name=?").get(name) as { sql?: string } | undefined) + ?.sql ?? undefined; + const logger = () => ({ error: vi.fn(), warn: vi.fn(), info: vi.fn() }); + + beforeEach(() => { + db = new DatabaseSync(':memory:'); + createTable(db, DECLARED_INDEX_DDL); + insert = insertInto(db); + // A SELECT answers its rows (as knex's raw terminal does), so the + // duplicated keys a refusal names are read from real rows. + exec = async (sql: string) => (/^\s*SELECT/i.test(sql) ? db.prepare(sql).all() : db.exec(sql)); + }); + + afterEach(() => db.close()); + + it('without it, the declared key admits two package-less connections of one instance (the hole this closes)', () => { + expect(insert('a', null)).toBe(true); + expect(insert('b', null)).toBe(true); + }); + + it('with it, a second package-less connection of one (organization, instance) is refused', async () => { + const log = logger(); + expect(await ensureConnectorConnectionPackagelessIndex(exec, log, { client: 'better-sqlite3' })).toEqual({ status: 'created' }); + expect(indexDdl(CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME)).toContain('(organization_id, connector_name) WHERE connector_package IS NULL'); + + expect(insert('a', null)).toBe(true); + expect(insert('b', null)).toBe(false); + // Another organization or instance is another key. + expect(insert('c', null, 'org_2')).toBe(true); + expect(insert('d', null, 'org_1', 'slack')).toBe(true); + expect(log.error).not.toHaveBeenCalled(); + }); + + it('leaves packaged connections to the declared key: two packages admitted, one package twice refused', async () => { + await ensureConnectorConnectionPackagelessIndex(exec, logger(), { client: 'better-sqlite3' }); + expect(insert('p1', 'com.acme.crm')).toBe(true); + expect(insert('p2', 'com.acme.hr')).toBe(true); + expect(insert('p1b', 'com.acme.crm')).toBe(false); + }); + + /** + * Measured side by side over the same rows: among connections that name no + * package, the old `(organization_id, connector_name)` key and the new key + * plus this index answer every row alike. + * + * What the store alone admits that the old key refused: a connection naming + * a package beside one naming none, for one organization and instance. The + * connection store is the table's one writer and reads before it writes (a + * connect updates the row it finds, `service-automation`'s + * `connector-connections.ts`), so it never writes that row; this pin names + * the store's own answer, so a later guard turns it red. + */ + it('among package-less connections admits nothing the old key refused; the store alone admits a packaged connection beside a package-less one', async () => { + const old = new DatabaseSync(':memory:'); + try { + createTable(old, OLD_INDEX_DDL); + const insertOld = insertInto(old); + await ensureConnectorConnectionPackagelessIndex(exec, logger(), { client: 'better-sqlite3' }); + + const rows: Array<[string, string | null]> = [ + ['n1', null], + ['n2', null], // a second package-less connection of the instance + ['m1', 'com.acme.crm'], // a packaged connection beside n1 + ['m2', 'com.acme.crm'], // that package twice + ['h1', 'com.acme.hr'], // a second package's instance of the name + ]; + const answers = rows.map(([id, pkg]) => ({ id, old: insertOld(id, pkg), now: insert(id, pkg) })); + + expect(answers).toEqual([ + { id: 'n1', old: true, now: true }, + { id: 'n2', old: false, now: false }, + // The store alone: admitted beside n1, where the old key refused it. + { id: 'm1', old: false, now: true }, + { id: 'm2', old: false, now: false }, + // What the ruling asks for: one organization connects both packages' instances. + { id: 'h1', old: false, now: true }, + ]); + } finally { + old.close(); + } + }); + + it('is idempotent: a second boot keeps the index and reports created', async () => { + await ensureConnectorConnectionPackagelessIndex(exec, logger(), { client: 'better-sqlite3' }); + const first = indexDdl(CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME); + expect(await ensureConnectorConnectionPackagelessIndex(exec, logger(), { client: 'better-sqlite3' })).toEqual({ status: 'created' }); + expect(indexDdl(CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME)).toBe(first); + // The declared key is untouched: this index replaces nothing. + expect(indexDdl('uniq_sys_connector_connection_declared')).toBe(DECLARED_INDEX_DDL); + }); + + it('existing duplicates: refuses, names the keys, deletes and re-stamps nothing, and gives the listing query', async () => { + insert('a', null); + insert('b', null); + insert('c', 'com.acme.crm'); + const log = logger(); + + const result = await ensureConnectorConnectionPackagelessIndex(exec, log, { client: 'better-sqlite3' }); + + expect(result.status).toBe('conflict'); + expect(indexDdl(CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME)).toBeUndefined(); + expect(db.prepare(`SELECT id, connector_package FROM ${CONNECTOR_CONNECTION_TABLE} ORDER BY id`).all()).toEqual([ + { id: 'a', connector_package: null }, + { id: 'b', connector_package: null }, + { id: 'c', connector_package: 'com.acme.crm' }, + ]); + const message = String(log.error.mock.calls[0]?.[0] ?? ''); + expect(message).toContain('existing connections violate'); + expect(message).toContain('organization_id=org_1, connector_name=github (2 connections)'); + expect(message).toContain('no package is guessed'); + expect(message).toContain(buildConnectorConnectionPackagelessDuplicateProbeSql()); + expect(message).toContain('os migrate duplicates'); + expect(db.prepare(buildConnectorConnectionPackagelessDuplicateProbeSql()).all()).toEqual([ + { organization_id: 'org_1', connector_name: 'github', duplicate_rows: 2 }, + ]); + + // Re-runnable: once an operator revokes the extra connection, the next boot builds it. + db.prepare(`DELETE FROM ${CONNECTOR_CONNECTION_TABLE} WHERE id = 'b'`).run(); + expect(await ensureConnectorConnectionPackagelessIndex(exec, logger(), { client: 'better-sqlite3' })).toEqual({ status: 'created' }); + }); + + it('names ten duplicated keys, then how many more', async () => { + for (let i = 0; i < 12; i++) { + insert(`a${i}`, null, 'org_1', `conn_${String(i).padStart(2, '0')}`); + insert(`b${i}`, null, 'org_1', `conn_${String(i).padStart(2, '0')}`); + } + const log = logger(); + expect((await ensureConnectorConnectionPackagelessIndex(exec, log, { client: 'better-sqlite3' })).status).toBe('conflict'); + const message = String(log.error.mock.calls[0]?.[0] ?? ''); + expect(message.match(/\(2 connections\)/g)).toHaveLength(10); + expect(message).toContain('; and 2 more'); + }); + + it('a kernel without the table, or without a SQL driver, is a silent no-op', async () => { + db.exec(`DROP TABLE ${CONNECTOR_CONNECTION_TABLE}`); + const log = logger(); + expect(await ensureConnectorConnectionPackagelessIndex(exec, log)).toEqual({ status: 'absent' }); + expect(await ensureConnectorConnectionPackagelessIndex(undefined, log)).toEqual({ status: 'no-driver' }); + expect(log.error).not.toHaveBeenCalled(); + expect(log.warn).not.toHaveBeenCalled(); + }); + + /** + * [#31699, as the grant guard's #32164 MF6 pins] The ensurer each kernel's + * schema-sync event runs, over an engine whose driver serves this table the + * way `SqlDriver` does: `execute` for raw SQL, `config.client` for the + * dialect, `schemaDdlDeferred` while a one-shot CLI boot holds DDL back. + */ + describe('createConnectorConnectionGuardAtSchemaSync: once per pass, on every kernel that performs the DDL', () => { + const engineOver = (driver: { schemaDdlDeferred?: boolean }) => ({ + getDriverForObject: (table: string) => (table === CONNECTOR_CONNECTION_TABLE ? driver : undefined), + }); + const sqliteDriver = () => ({ + schemaDdlDeferred: false as boolean, + config: { client: 'better-sqlite3' }, + execute: (sql: string) => exec(sql), + }); + + it('a pass whose driver holds DDL back (a dry run, or apply before its confirmation) builds nothing and latches nothing; the pass after the flush builds it', async () => { + const driver = sqliteDriver(); + driver.schemaDdlDeferred = true; + const log = logger(); + const ensure = createConnectorConnectionGuardAtSchemaSync(engineOver(driver), log); + + expect(await ensure()).toBe('held-back'); + expect(indexDdl(CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME)).toBeUndefined(); + + driver.schemaDdlDeferred = false; // the flush performed what was held back + expect(await ensure()).toBe('created'); + expect(indexDdl(CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME)).toBeDefined(); + expect(log.error).not.toHaveBeenCalled(); + expect(log.warn).not.toHaveBeenCalled(); + }); + + it('`created` never latches: a guard the table lost (a SQLite table rebuild drops it) is built again by the next pass, silently', async () => { + const log = logger(); + const ensure = createConnectorConnectionGuardAtSchemaSync(engineOver(sqliteDriver()), log); + expect(await ensure()).toBe('created'); + + db.exec(`DROP INDEX ${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME}`); + expect(await ensure()).toBe('created'); + expect(indexDdl(CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME)).toBeDefined(); + expect(log.error).not.toHaveBeenCalled(); + expect(log.warn).not.toHaveBeenCalled(); + }); + + it('a later pass over a table the guard stands on reads the catalog and issues no DDL (a metadata:reloaded re-sync locks nothing)', async () => { + const statements: string[] = []; + const driver = { ...sqliteDriver(), execute: (sql: string) => (statements.push(sql), exec(sql)) }; + const log = logger(); + const ensure = createConnectorConnectionGuardAtSchemaSync(engineOver(driver), log); + + expect(await ensure()).toBe('created'); + expect(statements.filter(isDdl)).toEqual([buildConnectorConnectionPackagelessIndexSql('better-sqlite3')]); + + statements.length = 0; + expect(await ensure()).toBe('created'); + expect(statements.filter(isDdl)).toEqual([]); + expect(statements).toContain(buildConnectorConnectionPackagelessIndexPresenceSql('better-sqlite3')); + expect(indexDdl(CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME)).toBeDefined(); + expect(log.error).not.toHaveBeenCalled(); + expect(log.warn).not.toHaveBeenCalled(); + }); + + it('a refused catalog read never skips the build: the pass builds as it did without the read', async () => { + const driver = { + ...sqliteDriver(), + execute: (sql: string) => (isGuardPresenceRead(sql) ? Promise.reject(new Error('no such table: sqlite_master')) : exec(sql)), + }; + const ensure = createConnectorConnectionGuardAtSchemaSync(engineOver(driver), logger()); + + expect(await ensure()).toBe('created'); + expect(indexDdl(CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME)).toBeDefined(); + }); + + it('a refusal latches: reported once, and a later pass in the same boot neither tries again nor says it twice', async () => { + insert('a', null); + insert('b', null); + const log = logger(); + const ensure = createConnectorConnectionGuardAtSchemaSync(engineOver(sqliteDriver()), log); + + expect(await ensure()).toBe('conflict'); + expect(await ensure()).toBe('refused-earlier'); + expect(log.error).toHaveBeenCalledTimes(1); + expect(indexDdl(CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME)).toBeUndefined(); + + // The next boot is a new ensurer, and tries again. + db.prepare(`DELETE FROM ${CONNECTOR_CONNECTION_TABLE} WHERE id = 'b'`).run(); + expect(await createConnectorConnectionGuardAtSchemaSync(engineOver(sqliteDriver()), logger())()).toBe('created'); + }); + + it('an engine with no SQL driver for the table: a silent no-op, never latched', async () => { + const log = logger(); + const ensure = createConnectorConnectionGuardAtSchemaSync({ getDriverForObject: () => undefined }, log); + expect(await ensure()).toBe('no-driver'); + expect(await ensure()).toBe('no-driver'); + expect(log.error).not.toHaveBeenCalled(); + expect(log.warn).not.toHaveBeenCalled(); + }); + }); +}); + +describe('the MySQL-family arms (statement and verdict)', () => { + const presentTable: IndexExec = async (sql: string) => { + if (isGuardPresenceRead(sql)) return [[], []]; + if (/information_schema|sqlite_master|to_regclass|WHERE 1 = 0/i.test(sql)) return [[{ present: 1 }]]; + throw new Error('unexpected'); + }; + + it('the guard read per dialect: an index of its name on this table, in the schema the unqualified DDL resolves; no arm for an unknown client', () => { + expect(buildConnectorConnectionPackagelessIndexPresenceSql('better-sqlite3')).toBe( + `SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = '${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME}' ` + + `AND tbl_name = '${CONNECTOR_CONNECTION_TABLE}'`, + ); + expect(buildConnectorConnectionPackagelessIndexPresenceSql('pg')).toBe( + 'SELECT 1 FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid ' + + `WHERE i.indrelid = to_regclass('"${CONNECTOR_CONNECTION_TABLE}"') AND c.relname = '${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME}'`, + ); + expect(buildConnectorConnectionPackagelessIndexPresenceSql('mysql2')).toBe( + 'SELECT 1 FROM information_schema.statistics ' + + `WHERE table_schema = DATABASE() AND table_name = '${CONNECTOR_CONNECTION_TABLE}' ` + + `AND index_name = '${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME}'`, + ); + expect(buildConnectorConnectionPackagelessIndexPresenceSql('oracledb')).toBeUndefined(); + expect(buildConnectorConnectionPackagelessIndexPresenceSql(undefined)).toBeUndefined(); + }); + + it('a guard the catalog names is left alone: no version read, no CREATE, no ALTER', async () => { + const seen: string[] = []; + const exec: IndexExec = async (sql) => { + seen.push(sql); + if (isGuardPresenceRead(sql)) return [[{ 1: 1 }], []]; + return presentTable(sql); + }; + expect(await ensureConnectorConnectionPackagelessIndex(exec, { warn: vi.fn(), error: vi.fn() }, { client: 'mysql2' })) + .toEqual({ status: 'created' }); + expect(seen.filter(isDdl)).toEqual([]); + expect(seen.some((q) => /VERSION\(\)/.test(q))).toBe(false); + }); + + it('a client with no catalog arm builds as before (the read never guesses a spelling)', async () => { + const seen: string[] = []; + // The table's fallback probe answers a result set (present); every statement succeeds. + const exec: IndexExec = async (sql) => (seen.push(sql), []); + expect(await ensureConnectorConnectionPackagelessIndex(exec, { warn: vi.fn(), error: vi.fn() }, { client: 'oracledb' })) + .toEqual({ status: 'created' }); + expect(seen.filter(isDdl)).toEqual([buildConnectorConnectionPackagelessIndexSql('oracledb')]); + expect(seen.some(isGuardPresenceRead)).toBe(false); + }); + + it("MySQL takes a functional key part over the driver's own digest, NULL for a packaged connection", () => { + expect(buildConnectorConnectionPackagelessIndexSql('mysql2')).toBe( + `CREATE UNIQUE INDEX ${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME} ON ${CONNECTOR_CONNECTION_TABLE} ` + + '((CASE WHEN connector_package IS NULL THEN ' + + 'unhex(sha2(concat(organization_id, 0x1f, connector_name), 256)) END))', + ); + expect(buildConnectorConnectionPackagelessIndexSql('pg')).toBe( + `CREATE UNIQUE INDEX IF NOT EXISTS ${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME} ON ${CONNECTOR_CONNECTION_TABLE} ` + + '(organization_id, connector_name) WHERE connector_package IS NULL', + ); + expect(buildConnectorConnectionPackagelessIndexSql(undefined)).toContain('WHERE connector_package IS NULL'); + }); + + it('an index of that name already there (ER_DUP_KEYNAME) is the index being in place', async () => { + const exec: IndexExec = async (sql) => { + if (sql.startsWith('CREATE')) throw Object.assign(new Error(`Duplicate key name '${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME}'`), { errno: 1061 }); + return presentTable(sql); + }; + expect(await ensureConnectorConnectionPackagelessIndex(exec, { warn: vi.fn(), error: vi.fn() }, { client: 'mysql2' })) + .toEqual({ status: 'created' }); + }); + + /** A server with no guard form: the guard's CREATE is a syntax error, the old key's plain CREATE runs. */ + const noGuardForm = (oldKey: (sql: string) => unknown = () => []) => { + const ran: string[] = []; + const exec: IndexExec = async (sql) => { + if (sql.startsWith('CREATE')) { + ran.push(sql); + if (sql.includes(CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME)) { + throw new Error("You have an error in your SQL syntax; check the manual near '(CASE WHEN'"); + } + return oldKey(sql); + } + return presentTable(sql); + }; + return { exec, ran }; + }; + + it('a server with no form at all keeps the old two-column key in its place: built where missing, reported at error', async () => { + const { exec, ran } = noGuardForm(); + const log = { warn: vi.fn(), error: vi.fn() }; + const result = await ensureConnectorConnectionPackagelessIndex(exec, log, { client: 'mysql2' }); + expect(result).toMatchObject({ status: 'unsupported', oldKey: 'kept' }); + expect(ran[ran.length - 1]).toBe(buildConnectorConnectionOldKeySql('mysql2')); + expect(buildConnectorConnectionOldKeySql('mysql2')).toBe( + `CREATE UNIQUE INDEX ${CONNECTOR_CONNECTION_OLD_KEY_INDEX_NAME} ON ${CONNECTOR_CONNECTION_TABLE} (organization_id, connector_name)`, + ); + expect(log.error).toHaveBeenCalledTimes(1); + const message = String(log.error.mock.calls[0]?.[0] ?? ''); + expect(message).toContain('is NOT enforced by an index of its own'); + expect(message).toContain(`'${CONNECTOR_CONNECTION_OLD_KEY_INDEX_NAME}' stands in its place`); + expect(message).toContain("a second package's connector instance of the same name"); + }); + + it('an old key already there (an upgraded database, ER_DUP_KEYNAME) is kept as it is', async () => { + const { exec } = noGuardForm(() => { + throw Object.assign(new Error(`Duplicate key name '${CONNECTOR_CONNECTION_OLD_KEY_INDEX_NAME}'`), { errno: 1061 }); + }); + const log = { warn: vi.fn(), error: vi.fn() }; + expect(await ensureConnectorConnectionPackagelessIndex(exec, log, { client: 'mysql2' })) + .toMatchObject({ status: 'unsupported', oldKey: 'kept' }); + expect(String(log.error.mock.calls[0]?.[0] ?? '')).toContain('stands in its place'); + }); + + it('an old key that cannot be built either says nothing guards, with its own driver text', async () => { + const { exec } = noGuardForm(() => { + throw Object.assign(new Error("Duplicate entry 'org_1-github' for key"), { errno: 1062 }); + }); + const log = { warn: vi.fn(), error: vi.fn() }; + const result = await ensureConnectorConnectionPackagelessIndex(exec, log, { client: 'mysql2' }); + expect(result).toMatchObject({ status: 'unsupported', oldKey: 'failed' }); + expect(result.oldKeyDetail).toContain('Duplicate entry'); + const message = String(log.error.mock.calls[0]?.[0] ?? ''); + expect(message).toContain('could not be built in its place either'); + expect(message).toContain("revoking one leaves the other's refresh token stored"); + }); + + it('the old key statement elsewhere is idempotent by IF NOT EXISTS', () => { + expect(buildConnectorConnectionOldKeySql('pg')).toBe( + `CREATE UNIQUE INDEX IF NOT EXISTS ${CONNECTOR_CONNECTION_OLD_KEY_INDEX_NAME} ON ${CONNECTOR_CONNECTION_TABLE} (organization_id, connector_name)`, + ); + }); +}); + +/** + * [#21418] The three `operatorFacingErrorText()` sites in this migration — the + * CREATE's failure detail, the old key's failure detail where the guard has no + * form (`oldKeyDetail`), and the schema-sync ensurer's own catch — and the + * presence read's detail it also reports: a value bound into a refused raw + * statement reaches neither the returned result nor the `error` line. The + * fixture is the raw terminal's envelope, as + * `raw-exec-operator-detail-16657.test.ts` builds it for the sibling migrations. + */ +describe('[#21418] a bound sentinel reaches no carrier this migration writes', () => { + const SENTINEL = 'SENTINEL-21418-BOUND-VALUE'; + + /** knex's message for a refused raw statement: values inlined, then the dialect's words. */ + const knexDump = (sql: string, params: readonly unknown[], diagnostic: string): string => { + let i = 0; + return `${sql.replace(/\?/g, () => `'${String(params[i++])}'`)} - ${diagnostic}`; + }; + + /** `rawStatementFaultError`'s shape: a composed envelope, the dialect text on a non-enumerable cause. */ + function rawStatementFault(dialect: string, causeCode = 'SQLITE_ERROR'): Error { + const err = Object.assign(new Error('The database refused to run a raw statement.'), { + code: 'DATABASE_ERROR', + status: 500, + }); + const cause = Object.assign(new Error(dialect), { code: causeCode }); + Object.defineProperty(err, 'cause', { value: cause, enumerable: false, writable: true, configurable: true }); + return err; + } + + const carriers = (result: unknown, log: { error: ReturnType; warn: ReturnType }) => + [inspect(result, { depth: 8 }), ...[...log.error.mock.calls, ...log.warn.mock.calls].map((c) => inspect(c, { depth: 8 }))].join('\n'); + + const presentTable = async (sql: string) => { + if (isGuardPresenceRead(sql)) return []; + if (/information_schema|sqlite_master|to_regclass|WHERE 1 = 0/i.test(sql)) return [[{ present: 1 }]]; + return []; + }; + + it('[the fixture] the raw path really carries the sentinel on the cause the helper reads', () => { + const thrown = rawStatementFault(knexDump('select ? as v', [SENTINEL], 'no such column: v')); + expect((thrown as { cause?: Error }).cause?.message).toContain(SENTINEL); + expect(thrown.message).not.toContain(SENTINEL); + }); + + it.each([ + ['failed', 'no such column: v', 'SQLITE_ERROR'], + ['unsupported', 'near "WHERE": syntax error', 'SQLITE_ERROR'], + ] as const)('the CREATE refused (%s): the result detail and the error line carry the dialect text, never the bound value', async (status, diagnostic, code) => { + const exec: IndexExec = async (sql) => { + if (sql.startsWith('CREATE')) throw rawStatementFault(knexDump(`${sql} -- ?`, [SENTINEL], diagnostic), code); + return presentTable(sql); + }; + const log = { error: vi.fn(), warn: vi.fn() }; + const result = await ensureConnectorConnectionPackagelessIndex(exec, log, { client: 'better-sqlite3' }); + expect(result.status).toBe(status); + expect(result.detail).toContain(diagnostic); + // On `unsupported` the old key's CREATE is refused the same way: its own detail, the second site. + if (status === 'unsupported') expect(result.oldKeyDetail).toContain(diagnostic); + expect(log.error).toHaveBeenCalled(); + expect(carriers(result, log)).not.toContain(SENTINEL); + }); + + it("the schema-sync ensurer's own catch (a throw no collaborator is meant to raise): its error line carries the dialect text, never the bound value", async () => { + const fault = rawStatementFault(knexDump('select ? as v', [SENTINEL], 'no such column: v')); + // A driver whose raw-SQL surface cannot even be read: the seam lookup, + // the first thing a pass asks, throws straight into the ensurer's backstop. + const driver = { + get execute(): never { + throw fault; + }, + }; + const engine = { getDriverForObject: (table: string) => (table === CONNECTOR_CONNECTION_TABLE ? driver : undefined) }; + const log = { error: vi.fn(), warn: vi.fn() }; + + const outcome = await createConnectorConnectionGuardAtSchemaSync(engine, log)(); + + // Reached the catch, not some other branch: its own line, its own outcome. + expect(outcome).toBe('failed'); + expect(log.error).toHaveBeenCalledTimes(1); + expect(String(log.error.mock.calls[0]?.[0] ?? '')).toContain('connector connection index migration skipped'); + expect((log.error.mock.calls[0]?.[1] as Error | undefined)?.message).toContain('no such column: v'); + expect(carriers(outcome, log)).not.toContain(SENTINEL); + }); + + it('the presence read refused: the failed result and its error line carry no bound value', async () => { + const exec: IndexExec = async () => { + throw rawStatementFault(knexDump('select ? as v', [SENTINEL], 'no such column: v')); + }; + const log = { error: vi.fn(), warn: vi.fn() }; + const result = await ensureConnectorConnectionPackagelessIndex(exec, log, { client: 'better-sqlite3' }); + expect(result.status).toBe('failed'); + expect(log.error).toHaveBeenCalled(); + expect(carriers(result, log)).not.toContain(SENTINEL); + }); +}); + +describe('the MariaDB arm (INVISIBLE generated carrier + UNIQUE key)', () => { + const mariadb = (onDdl: (sql: string) => unknown) => { + const seen: string[] = []; + const exec: IndexExec = async (sql: string) => { + seen.push(sql); + if (isGuardPresenceRead(sql)) return [[], []]; + if (/information_schema|sqlite_master|to_regclass|WHERE 1 = 0/i.test(sql)) return [[{ present: 1 }]]; + if (/^SELECT VERSION\(\)/.test(sql)) return [[{ version: '11.8.9-MariaDB-ubu2404' }]]; + return onDdl(sql); + }; + return { exec, seen }; + }; + const ddl = (seen: string[]) => seen.filter((q) => /^(ALTER|CREATE)/.test(q)); + + it('the carrier is named as driver-sql names a hash shadow (index name + __hash), so its differ owns it', () => { + expect(CONNECTOR_CONNECTION_PACKAGELESS_SHADOW_COLUMN).toBe(`${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME}__hash`); + }); + + it('one ALTER adds the INVISIBLE column (the digest, NULL for a packaged connection) and the UNIQUE key over it', () => { + expect(buildConnectorConnectionPackagelessMariaDbSql()).toBe( + `ALTER TABLE ${CONNECTOR_CONNECTION_TABLE} ADD COLUMN ${CONNECTOR_CONNECTION_PACKAGELESS_SHADOW_COLUMN} VARBINARY(32) ` + + 'GENERATED ALWAYS AS (CASE WHEN connector_package IS NULL THEN ' + + 'unhex(sha2(concat(organization_id, 0x1f, connector_name), 256)) END) ' + + 'VIRTUAL INVISIBLE, ' + + `ADD UNIQUE KEY ${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME} (${CONNECTOR_CONNECTION_PACKAGELESS_SHADOW_COLUMN})`, + ); + }); + + it('MariaDB takes that form, never the MySQL functional statement it refuses', async () => { + const { exec, seen } = mariadb(() => [[]]); + const log = { warn: vi.fn(), error: vi.fn() }; + expect(await ensureConnectorConnectionPackagelessIndex(exec, log, { client: 'mysql2' })).toEqual({ status: 'created' }); + expect(ddl(seen)).toEqual([buildConnectorConnectionPackagelessMariaDbSql()]); + expect(log.error).not.toHaveBeenCalled(); + }); + + it('a second boot (ER_DUP_FIELDNAME) re-keys the standing column, and a key already there (ER_DUP_KEYNAME) is the index in place', async () => { + const { exec, seen } = mariadb((sql) => { + if (sql.includes('ADD COLUMN')) throw Object.assign(new Error("Duplicate column name 'x'"), { errno: 1060, code: 'ER_DUP_FIELDNAME' }); + throw Object.assign(new Error("Duplicate key name 'x'"), { errno: 1061, code: 'ER_DUP_KEYNAME' }); + }); + expect(await ensureConnectorConnectionPackagelessIndex(exec, { warn: vi.fn(), error: vi.fn() }, { client: 'mysql2' })) + .toEqual({ status: 'created' }); + expect(ddl(seen)).toEqual([buildConnectorConnectionPackagelessMariaDbSql(), buildConnectorConnectionPackagelessMariaDbKeySql()]); + }); + + it('existing duplicates (ER_DUP_ENTRY) are a conflict: reported at error with the listing query, nothing deleted', async () => { + const { exec, seen } = mariadb((sql) => { + if (/^ALTER/.test(sql)) throw Object.assign(new Error(`Duplicate entry 'x' for key '${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME}'`), { errno: 1062, code: 'ER_DUP_ENTRY' }); + return [[{ duplicate_keys: 1, duplicate_rows: 2 }]]; + }); + const log = { warn: vi.fn(), error: vi.fn() }; + const result = await ensureConnectorConnectionPackagelessIndex(exec, log, { client: 'mysql2' }); + expect(result.status).toBe('conflict'); + expect(String(log.error.mock.calls[0]?.[0] ?? '')).toContain(buildConnectorConnectionPackagelessDuplicateProbeSql()); + expect(seen.some((q) => /^(DELETE|DROP|UPDATE)/i.test(q))).toBe(false); + }); +}); diff --git a/packages/metadata-protocol/src/migrations/connector-connection-packageless-index.ts b/packages/metadata-protocol/src/migrations/connector-connection-packageless-index.ts new file mode 100644 index 00000000000..75e480f17f6 --- /dev/null +++ b/packages/metadata-protocol/src/migrations/connector-connection-packageless-index.ts @@ -0,0 +1,571 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `sys_connector_connection` — one connection per `(organization_id, + * connector_name)` among the connections that name no package, delivered at + * runtime (ADR-0150 D4 and D8 row R11, ADR-0120 D4, #31699). + * + * ## What is broken without it + * + * A connector instance is identified by `(package, name)` (ADR-0150 D4), so the + * connection's declared key is `(organization_id, connector_package, + * connector_name)`: one organization may connect both packages' instances of one + * name (the maintainer's ruling on #31699, "unique by package and name"). + * `connector_package` is NULL on every connection of an instance the + * environment authored or a plugin registers in code, and of a name the + * stored-reference backfill could not bind (the column's documented "empty", + * never a sentinel). A SQL UNIQUE treats NULLs as distinct, so for exactly those + * connections the declared key constrains nothing. The key it replaced, + * `(organization_id, connector_name)`, held them to one. Two of them would keep + * two refresh tokens for one instance in one organization, and a revoke that + * deletes one would leave the other stored. + * + * ## Why THIS route + * + * The same as `sys_user_permission_set`'s grant guard + * (`user-permission-set-packageless-index.ts`, #32164), whose docblock carries + * the full argument, and the activation ledger's before it + * (`activation-ledger-packageless-index.ts`, with the per-dialect + * measurements). `IndexSchema` can say neither "NULL-safe" for a non-tenant + * column nor `WHERE`, so the declared surface cannot carry it: this runtime + * migration ADDS an index beside the declared key and replaces nothing. + * + * Its key is the old key's columns in the old key's order, because that is + * what `driver-sql`'s widening arm (`widenedUniqueReplacements`) asks of the + * guard before it retires the old key (`hasPartialUniqueGuard`: a partial + * UNIQUE on exactly the narrower columns). Measured on SQLite: with this index + * standing, the drift plan is one `replace_unique_index`, categorized `safe`; + * without it, the arm keeps the old key and plans nothing. + * + * ## When — at schema sync, on every kernel that runs the table's DDL + * + * As the grant guard: `metadata-protocol`'s assembly runs + * {@link createConnectorConnectionGuardAtSchemaSync} on + * `objectql:schema-synced`, so the guard follows the table's DDL wherever that + * runs, a pass that performs no DDL builds nothing (`'held-back'`), a standing + * guard costs one catalog read, and a refusal is reported once per boot. + * + * ## The index, per dialect + * + * - SQLite and PostgreSQL: a partial unique index, + * `(organization_id, connector_name) WHERE connector_package IS NULL`. + * - MySQL (8.0.13+): a functional key part over the driver's hash-shadow digest, + * NULL for a packaged connection, which UNIQUE then exempts. ⚠ `driver-sql` + * reads that key part as an expression, not as a partial guard, so on MySQL + * the widening arm keeps the old key (a declared limit; the grant guard + * shares it). The old key keeps refusing what it refused, nothing more. + * - MariaDB: a UNIQUE key over an INVISIBLE generated column carrying that + * digest, `uniq_sys_connector_connection_packageless__hash` (MariaDB 10.3+), + * which `driver-sql` reads as a partial unique on the two columns. + * - `driver-mongodb` builds its own copy at collection sync (`mongodb-schema.ts`, + * `RUNTIME_OWNED_UNIQUES`). Mongo materialized the earlier declaration's + * columns verbatim, `(connector_name)` alone, so its guard is keyed on that. + * - `driver-memory` is no SQL host (`no-driver`): a declared limit, pinned in + * `driver-memory`'s `memory-connector-connection-packageless.test.ts`. + * + * ## What it admits — nothing the old key refused + * + * Both key parts are required, plain columns, so no connection escapes this + * index or the declared key by a NULL organization or name. Two package-less + * connections of one instance in one organization are refused, as they were. + * The table first shipped after plain organization keys (18.3.0), so no + * released database carries the old key in ADR-0120 D3's NULL-safe form. + * + * ## The old key retires on the next boot (or `os migrate apply`) + * + * The widening arm offers to retire the old key only once this index stands, + * because the gained column is nullable. On SQL the drift plan is read during + * the table's sync, before this index is built, so on an upgraded database the + * old key is retired by the NEXT sync that runs safe drift (dev + * `autoMigrate: 'safe'`, or `os migrate apply`); until then it keeps refusing + * what it refused. + * + * ## A dialect with no form keeps the old key + * + * MySQL before 8.0.13 and MariaDB before 10.3 can build no form of this index + * (`'unsupported'`). There the old key stays, or is built under the name + * `driver-sql` generates for it ({@link CONNECTOR_CONNECTION_OLD_KEY_INDEX_NAME}) + * where it is missing, so the widening arm reads it as the superseded key once + * this index can stand. It refuses everything this index would, and also an + * organization's connection of a second package's instance of the same name: a + * declared limit of those servers. + * + * ## Refuse, never keep-one (ADR-0120 D4) + * + * The build fails only on a database that already holds two package-less + * connections of one `(organization_id, connector_name)`, which the old key + * refused, so they were written after it was retired. Nothing here deletes, + * re-stamps or guesses a package for either: the operator gets the key that is + * not enforced, the consequence, the duplicated keys (an organization id and an + * instance name, no secret), and the query that lists the rows + * ({@link buildConnectorConnectionPackagelessDuplicateProbeSql}, also what + * `os migrate duplicates` runs through `runtime-index-preflight.ts`). + * Re-runnable: an existing index is left as it is, and a refused build is tried + * again on the next boot. + */ + +import { operatorFacingErrorText } from '@objectstack/types'; + +import { + classifyIndexFailure, + countDuplicateKeys, + describeDuplicateKeys, + isSchemaDdlHeldBackForTable, + logProblem, + resolveIndexSeamForTable, + type IndexExec, + type IndexMigrationLogger, + type PartialIndexStatus, +} from './partial-index-probe.js'; +import { catalogFamilyOf, isResultSet, normalizeRows, readTablePresence } from './read-probe.js'; +import { isDuplicateColumnName, isDuplicateKeyName, isMariaDb } from './activation-ledger-packageless-index.js'; + +/** The one table this migration touches. */ +export const CONNECTOR_CONNECTION_TABLE = 'sys_connector_connection'; + +/** + * The index name. Its own name, never one the driver generates: the widened + * key's narrower predecessor is the driver's generated name for + * `(organization_id, connector_name)`, and claiming that name would let + * the widening arm read this index as the superseded one. + */ +export const CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME = 'uniq_sys_connector_connection_packageless'; + +/** + * The old two-column key's name: what `driver-sql`'s `buildIndexName` generates + * for `(organization_id, connector_name)` on this table, which the earlier + * `{ fields: ['connector_name'], unique: 'organization' }` declaration built + * (pinned against it in `connector-connection-packageless-index.test.ts`). + * Built only where this index cannot be (module doc, "A dialect with no form"). + */ +export const CONNECTOR_CONNECTION_OLD_KEY_INDEX_NAME = 'uniq_sys_connector_connection_organization_id_connector_name'; + +/** The key columns, in key order — the old key's, so the widening arm reads this index as its guard. */ +export const CONNECTOR_CONNECTION_PACKAGELESS_INDEX_COLUMNS = ['organization_id', 'connector_name'] as const; + +/** The rows the index covers. */ +export const CONNECTOR_CONNECTION_PACKAGELESS_ROW_SCOPE = 'connector_package IS NULL'; + +/** + * MariaDB's carrier column for the index. It must be the name `driver-sql`'s + * `hashShadowColumnFor` derives from the index name — the index name plus + * `__hash` — or the drift differ reads it as an orphan column. + */ +export const CONNECTOR_CONNECTION_PACKAGELESS_SHADOW_COLUMN = `${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME}__hash`; + +/** How many duplicated keys a refusal names before it says how many more there are. */ +const NAMED_DUPLICATE_KEYS = 10; + +/** The digest both MySQL-family forms key: the driver's own hash-shadow digest. */ +function packagelessDigest(): string { + return `unhex(sha2(concat(${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_COLUMNS.join(', 0x1f, ')}), 256))`; +} + +/** + * The MariaDB statement: one `ALTER TABLE` adding the INVISIBLE generated + * carrier and the UNIQUE key over it, so the column never stands without its + * key. A second boot answers ER_DUP_FIELDNAME, which the caller follows with + * {@link buildConnectorConnectionPackagelessMariaDbKeySql}. + */ +export function buildConnectorConnectionPackagelessMariaDbSql(): string { + return ( + `ALTER TABLE ${CONNECTOR_CONNECTION_TABLE} ADD COLUMN ${CONNECTOR_CONNECTION_PACKAGELESS_SHADOW_COLUMN} VARBINARY(32) ` + + `GENERATED ALWAYS AS (CASE WHEN ${CONNECTOR_CONNECTION_PACKAGELESS_ROW_SCOPE} THEN ${packagelessDigest()} END) ` + + `VIRTUAL INVISIBLE, ` + + `ADD UNIQUE KEY ${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME} (${CONNECTOR_CONNECTION_PACKAGELESS_SHADOW_COLUMN})` + ); +} + +/** The key alone, over a carrier column that already stands (a second boot after ER_DUP_FIELDNAME). */ +export function buildConnectorConnectionPackagelessMariaDbKeySql(): string { + return ( + `ALTER TABLE ${CONNECTOR_CONNECTION_TABLE} ADD UNIQUE KEY ${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME} ` + + `(${CONNECTOR_CONNECTION_PACKAGELESS_SHADOW_COLUMN})` + ); +} + +/** + * `CREATE UNIQUE INDEX …` for the connected dialect. `client` is the knex client + * name; anything not MySQL-family takes the partial form. + */ +export function buildConnectorConnectionPackagelessIndexSql(client?: string): string { + const columns = CONNECTOR_CONNECTION_PACKAGELESS_INDEX_COLUMNS; + if (catalogFamilyOf(client) === 'mysql') { + // No `IF NOT EXISTS` for CREATE INDEX on MySQL: an existing index + // answers ER_DUP_KEYNAME, which the caller reads as "already there". + return ( + `CREATE UNIQUE INDEX ${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME} ON ${CONNECTOR_CONNECTION_TABLE} ` + + `((CASE WHEN ${CONNECTOR_CONNECTION_PACKAGELESS_ROW_SCOPE} THEN ${packagelessDigest()} END))` + ); + } + return ( + `CREATE UNIQUE INDEX IF NOT EXISTS ${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME} ` + + `ON ${CONNECTOR_CONNECTION_TABLE} (${columns.join(', ')}) WHERE ${CONNECTOR_CONNECTION_PACKAGELESS_ROW_SCOPE}` + ); +} + +/** + * The old two-column key, for a dialect this index has no form on (module doc, + * "A dialect with no form"). No `IF NOT EXISTS` on MySQL, where an existing + * index answers ER_DUP_KEYNAME. + */ +export function buildConnectorConnectionOldKeySql(client?: string): string { + const ifNotExists = catalogFamilyOf(client) === 'mysql' ? '' : 'IF NOT EXISTS '; + return ( + `CREATE UNIQUE INDEX ${ifNotExists}${CONNECTOR_CONNECTION_OLD_KEY_INDEX_NAME} ON ${CONNECTOR_CONNECTION_TABLE} ` + + `(${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_COLUMNS.join(', ')})` + ); +} + +/** The fallback "is this table here?" statement, for a dialect `read-probe.ts` has no catalog arm for. */ +export function buildConnectorConnectionPresenceSql(): string { + return `SELECT 1 FROM ${CONNECTOR_CONNECTION_TABLE} WHERE 1 = 0`; +} + +/** + * The catalog statement that answers "does the guard already stand on the + * table?" with no DDL: one row when an index of its name is on the table, none + * when not. `undefined` for a client `read-probe.ts` has no catalog arm for, a + * guessed spelling being that module's fence; the build then runs as before. + * Each arm resolves the table the way the unqualified DDL does: SQLite's + * connection catalog, PostgreSQL's search path (`to_regclass`), the MySQL + * family's connected schema (`DATABASE()`), whose `statistics` lists the + * functional key and MariaDB's key over its carrier column alike. + */ +export function buildConnectorConnectionPackagelessIndexPresenceSql(client?: string): string | undefined { + const index = CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME; + const table = CONNECTOR_CONNECTION_TABLE; + switch (catalogFamilyOf(client)) { + case 'sqlite': + return `SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = '${index}' AND tbl_name = '${table}'`; + case 'postgres': + return ( + `SELECT 1 FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid ` + + `WHERE i.indrelid = to_regclass('"${table}"') AND c.relname = '${index}'` + ); + case 'mysql': + return ( + `SELECT 1 FROM information_schema.statistics ` + + `WHERE table_schema = DATABASE() AND table_name = '${table}' AND index_name = '${index}'` + ); + default: + return undefined; + } +} + +/** + * Does the guard already stand? Read before any DDL (module doc, "When"): + * `CREATE UNIQUE INDEX IF NOT EXISTS` takes PostgreSQL's SHARE lock on the + * table before it finds the name taken, so it waits behind every open write + * transaction on the connection table and holds every new writer behind it + * meanwhile (measured on PostgreSQL 16), and the MySQL family refuses its + * statement outright. A pass that finds the guard issues none of it. + * + * `'unknown'` (no catalog arm for the client, a refused read, no result set) + * is ⛔ never read as present: the build runs as it ran before this read + * existed, idempotent and reporting its own failure. The read only saves a + * statement; it never decides that the build may be skipped. + */ +async function readPackagelessIndexPresence(exec: IndexExec, client?: string): Promise<'present' | 'absent' | 'unknown'> { + const sql = buildConnectorConnectionPackagelessIndexPresenceSql(client); + if (sql === undefined) return 'unknown'; + let result: unknown; + try { + result = await exec(sql); + } catch { + return 'unknown'; + } + if (!isResultSet(result)) return 'unknown'; + return normalizeRows(result).length > 0 ? 'present' : 'absent'; +} + +/** + * The connections blocking the index, grouped by its key. A row whose key part + * is NULL conflicts with nothing under a UNIQUE index, so it is no duplicate to + * list (`organization_id` and `connector_name` are both required, so none is + * expected). One statement for every dialect. + */ +export function buildConnectorConnectionPackagelessDuplicateProbeSql(): string { + const columns = CONNECTOR_CONNECTION_PACKAGELESS_INDEX_COLUMNS; + return ( + `SELECT ${columns.join(', ')}, COUNT(*) AS duplicate_rows ` + + `FROM ${CONNECTOR_CONNECTION_TABLE} ` + + `WHERE ${CONNECTOR_CONNECTION_PACKAGELESS_ROW_SCOPE} AND ${columns.map((c) => `${c} IS NOT NULL`).join(' AND ')} ` + + `GROUP BY ${columns.join(', ')} HAVING COUNT(*) > 1` + ); +} + +/** This migration's statuses: the shared vocabulary plus `'absent'` (no such table on this kernel). */ +export type EnsureConnectorConnectionPackagelessIndexStatus = PartialIndexStatus | 'absent'; + +export interface EnsureConnectorConnectionPackagelessIndexResult { + status: EnsureConnectorConnectionPackagelessIndexStatus; + /** Driver error text, when there was one. */ + detail?: string; + /** + * On `'unsupported'` only: whether the old two-column key stands in its + * place (`'kept'`: built now or already there) or could not be built + * (`'failed'`, its driver text in `oldKeyDetail`). Module doc, "A dialect + * with no form". + */ + oldKey?: 'kept' | 'failed'; + oldKeyDetail?: string; +} + +/** Resolve the raw-SQL seam (and dialect) for `sys_connector_connection`. @see resolveIndexSeamForTable */ +export function resolveConnectorConnectionIndexSeam(engine: unknown): { exec: IndexExec; client?: string } | undefined { + return resolveIndexSeamForTable(engine, CONNECTOR_CONNECTION_TABLE); +} + +/** Build the MariaDB form; a second boot re-keys or finds the key in place. */ +async function buildOnMariaDb(exec: IndexExec): Promise { + try { + await exec(buildConnectorConnectionPackagelessMariaDbSql()); + } catch (err: unknown) { + if (!isDuplicateColumnName(err)) throw err; + await exec(buildConnectorConnectionPackagelessMariaDbKeySql()); + } +} + +/** + * The duplicated keys, as the clause a `'conflict'` line names them by (module + * doc, "Refuse, never keep-one"): the first {@link NAMED_DUPLICATE_KEYS}, then + * how many more. `''` when they cannot be read — the count and the query still + * say what to do. + */ +async function nameDuplicateKeys(exec: IndexExec): Promise { + try { + const result = await exec(buildConnectorConnectionPackagelessDuplicateProbeSql()); + if (!isResultSet(result)) return ''; + const rows = normalizeRows(result); + if (rows.length === 0) return ''; + const named = rows.slice(0, NAMED_DUPLICATE_KEYS).map((r) => + `organization_id=${String(r.organization_id)}, connector_name=${String(r.connector_name)} ` + + `(${String(r.duplicate_rows)} connections)`); + const more = rows.length > NAMED_DUPLICATE_KEYS ? `; and ${rows.length - NAMED_DUPLICATE_KEYS} more` : ''; + return `: ${named.join('; ')}${more}`; + } catch { + return ''; + } +} + +/** + * Ensure the package-less one-connection index (module doc). + * + * Idempotent: an existing index is left as it is, found by a catalog read + * before any DDL (`readPackagelessIndexPresence`), and reported `created`. + * Best-effort by design — a boot never fails because the index could not be + * built, so every branch returns a status instead of throwing, and every + * branch that leaves the guarantee unenforced says so at `error`. + */ +export async function ensureConnectorConnectionPackagelessIndex( + exec: IndexExec | undefined, + logger?: IndexMigrationLogger, + opts: { client?: string } = {}, +): Promise { + if (!exec) return { status: 'no-driver' }; + + const presence = await readTablePresence(exec, { + table: CONNECTOR_CONNECTION_TABLE, + client: opts.client, + fallbackSql: buildConnectorConnectionPresenceSql(), + }); + if (presence.verdict === 'absent') return { status: 'absent' }; + if (presence.verdict === 'unreadable') { + logProblem( + logger, + `[metadata-protocol] could not read whether "${CONNECTOR_CONNECTION_TABLE}" exists, so the index that keeps ` + + 'one connection per (organization_id, connector_name) among connections naming no package was NOT ensured ' + + 'this boot. This is not the table being absent, which is a normal, silent no-op. Verify by hand with: ' + + buildConnectorConnectionPresenceSql(), + presence.detail ?? '', + ); + return { status: 'failed', detail: presence.detail }; + } + + // A guard that already stands is left as it is without a statement that + // locks the table or is refused (`readPackagelessIndexPresence`). + if ((await readPackagelessIndexPresence(exec, opts.client)) === 'present') return { status: 'created' }; + + try { + if (catalogFamilyOf(opts.client) === 'mysql' && (await isMariaDb(exec))) await buildOnMariaDb(exec); + else await exec(buildConnectorConnectionPackagelessIndexSql(opts.client)); + return { status: 'created' }; + } catch (err: unknown) { + if (isDuplicateKeyName(err)) return { status: 'created' }; + const status = classifyIndexFailure(err); + const detail = operatorFacingErrorText(err); + const duplicates = + status === 'conflict' + ? describeDuplicateKeys(await countDuplicateKeys(exec, buildConnectorConnectionPackagelessDuplicateProbeSql())) + + (await nameDuplicateKeys(exec)) + : ''; + if (status === 'unsupported') { + const kept = await keepOldKey(exec, opts.client); + reportUnsupported(detail, logger, kept); + return { status, detail, ...kept }; + } + // `duplicates` reads " (N duplicated keys, held by M rows): organization_id=…; …" — the count, then the keys. + reportDegradation(status, detail, logger, duplicates); + return { status, detail }; + } +} + +/** + * What one schema-sync pass did about the guard + * ({@link createConnectorConnectionGuardAtSchemaSync}): the migration's own + * status, or + * + * - `'held-back'`: the driver behind the table holds this pass's DDL back (a + * dry run, or `os migrate apply` before its confirmation), so nothing was + * built and the next pass tries again; + * - `'refused-earlier'`: this kernel already reported a refusal, so the build + * is neither tried nor reported again until the next boot. + */ +export type ConnectorConnectionGuardPassOutcome = EnsureConnectorConnectionPackagelessIndexStatus | 'held-back' | 'refused-earlier'; + +/** The statuses that latch: each one was reported at `error`, and a second pass in one boot would only say it again. */ +const REFUSALS: ReadonlySet = new Set(['conflict', 'unsupported', 'failed']); + +/** + * [#31699] The guard as a kernel's schema sync builds it: one ensurer per + * kernel, run after each pass's DDL (`objectql:schema-synced`, module doc + * "When"). `metadata-protocol`'s assembly subscribes it on every kernel, + * whatever its `runPlatformMigrations` gate says, so the guard follows the + * table's DDL wherever that runs. + * + * - **A pass that performed no DDL builds nothing.** While the driver behind the + * table holds DDL back ({@link isSchemaDdlHeldBackForTable}) the answer is + * `'held-back'`, unlatched: the one-shot CLI boot triggers the event again + * once its flush has performed what was held back (`os migrate apply`), and + * a dry run never flushes. + * - **`created` never latches.** Every later pass re-checks the guard, because + * a pass can lose it: a SQLite table rebuild drops every index and recreates + * only the declared ones. While it stands the check is one catalog read and + * no DDL, so a `metadata:reloaded` re-sync neither locks the connection table nor + * sends a statement the server refuses. + * - **A refusal latches.** `conflict`, `unsupported` and `failed` were each + * reported at `error` once; the next boot tries again. + * - It never throws: a boot does not fail because the guard could not be built, + * so an unexpected throw is reported at `error` and latched as a refusal. + */ +export function createConnectorConnectionGuardAtSchemaSync( + engine: unknown, + logger: IndexMigrationLogger, +): () => Promise { + let refused = false; + return async () => { + if (refused) return 'refused-earlier'; + try { + if (isSchemaDdlHeldBackForTable(engine, CONNECTOR_CONNECTION_TABLE)) return 'held-back'; + const seam = resolveConnectorConnectionIndexSeam(engine); + const { status } = await ensureConnectorConnectionPackagelessIndex(seam?.exec, logger, { client: seam?.client }); + if (REFUSALS.has(status)) refused = true; + return status; + } catch (err: unknown) { + refused = true; + logProblem( + logger, + '[metadata-protocol] connector connection index migration skipped — the index that keeps one connection ' + + 'per (organization_id, connector_name) among connections naming no package was not ensured this boot, ' + + 'so two such connections of one connector instance can stand in one organization', + operatorFacingErrorText(err), + ); + return 'failed'; + } + }; +} + +/** Build (or find) the old two-column key where this index has no form. */ +async function keepOldKey( + exec: IndexExec, + client: string | undefined, +): Promise<{ oldKey: 'kept' | 'failed'; oldKeyDetail?: string }> { + try { + await exec(buildConnectorConnectionOldKeySql(client)); + return { oldKey: 'kept' }; + } catch (err: unknown) { + if (isDuplicateKeyName(err)) return { oldKey: 'kept' }; + return { oldKey: 'failed', oldKeyDetail: operatorFacingErrorText(err) }; + } +} + +/** + * The `'unsupported'` line: what still guards (the old key, kept or built), or, + * when that key could not be built either, that nothing does. `error` either + * way: once the connection's key is widened, that key alone admits what the old key + * refused. + */ +function reportUnsupported( + detail: string, + logger: IndexMigrationLogger | undefined, + kept: { oldKey: 'kept' | 'failed'; oldKeyDetail?: string }, +): void { + const key = `(${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_COLUMNS.join(', ')}) WHERE ${CONNECTOR_CONNECTION_PACKAGELESS_ROW_SCOPE}`; + const head = + `[metadata-protocol] this database cannot build '${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME}' on ` + + `"${CONNECTOR_CONNECTION_TABLE}" — it has no partial index, no functional key part and no INVISIBLE ` + + `column (MySQL before 8.0.13, or MariaDB before 10.3) — so ${key} is NOT enforced by an index of its own. `; + if (kept.oldKey === 'kept') { + logProblem( + logger, + head + + `The old (organization_id, connector_name) index '${CONNECTOR_CONNECTION_OLD_KEY_INDEX_NAME}' ` + + 'stands in its place (kept, or built where it was missing) and refuses every second connection naming no ' + + 'package, but it also refuses one organization a connection of a second package\'s connector instance of ' + + 'the same name, which an instance\'s (package, name) identity admits. Upgrade to MySQL 8.0.13+ or MariaDB 10.3+ and restart to build the ' + + 'index; the next safe sync then retires the old one.', + detail, + ); + return; + } + logProblem( + logger, + head + + `The old (organization_id, connector_name) index '${CONNECTOR_CONNECTION_OLD_KEY_INDEX_NAME}' could ` + + 'not be built in its place either, so two connections of one connector instance naming no package can ' + + 'stand in one organization, and revoking one leaves the other\'s refresh token stored. Fix the cause below, or list ' + + `the duplicates with: ${buildConnectorConnectionPackagelessDuplicateProbeSql()}, then restart.`, + kept.oldKeyDetail ?? detail, + ); +} + +/** + * Say what is NOT enforced and what fixes it (ADR-0120 D4's wording contract). + * Every arm is `error`: afterwards the platform looks healthy while two + * connections of one connector instance can stand in one organization. + */ +function reportDegradation( + status: Exclude, + detail: string, + logger: IndexMigrationLogger | undefined, + duplicates: string, +): void { + const key = `(${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_COLUMNS.join(', ')}) WHERE ${CONNECTOR_CONNECTION_PACKAGELESS_ROW_SCOPE}`; + const duplicateQuery = buildConnectorConnectionPackagelessDuplicateProbeSql(); + const consequence = + 'two connections of one connector instance naming no package can stand in one organization, and revoking ' + + 'one leaves the other\'s refresh token stored'; + + if (status === 'conflict') { + logProblem( + logger, + `[metadata-protocol] cannot build '${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME}' on ` + + `"${CONNECTOR_CONNECTION_TABLE}" — existing connections violate ${key}${duplicates}. Nothing is enforced on ` + + `that key, so ${consequence}. No connection is deleted, and no package is guessed for one: this migration ` + + 'keeps refusing until an operator revokes the connection that should not stand, or binds one to its ' + + `package ("os migrate stored-references bind"). List them with: ${duplicateQuery} — or run ` + + '"os migrate duplicates" — then restart (ADR-0120 D4).', + detail, + ); + return; + } + + logProblem( + logger, + `[metadata-protocol] could not build '${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME}' on ` + + `"${CONNECTOR_CONNECTION_TABLE}", so ${key} is not enforced and ${consequence}, while everything else ` + + 'looks healthy. Fix the cause below and restart.', + detail, + ); +} diff --git a/packages/metadata-protocol/src/migrations/runtime-index-preflight.test.ts b/packages/metadata-protocol/src/migrations/runtime-index-preflight.test.ts index a9ec875644a..de18d3fe9fc 100644 --- a/packages/metadata-protocol/src/migrations/runtime-index-preflight.test.ts +++ b/packages/metadata-protocol/src/migrations/runtime-index-preflight.test.ts @@ -164,6 +164,7 @@ describe('kernel:ready index pre-flight (#8725)', () => { // The fixture holds no activation ledger. 'uniq_sys_metadata_activation_packageless:table-absent', 'uniq_sys_user_permission_set_packageless:blocked', + 'uniq_sys_connector_connection_packageless:table-absent', ]); // The overlay conflict. [ADR-0131 C7b] The organization is no part of @@ -265,6 +266,7 @@ describe('kernel:ready index pre-flight (#8725)', () => { 'ensureNotificationPreferenceIdentityIndex:sys_notification_preference:uniq_sys_notification_preference_a22d7d27', 'ensureActivationLedgerPackagelessIndex:sys_metadata_activation:uniq_sys_metadata_activation_packageless', 'ensureUserPermissionSetPackagelessIndex:sys_user_permission_set:uniq_sys_user_permission_set_packageless', + 'ensureConnectorConnectionPackagelessIndex:sys_connector_connection:uniq_sys_connector_connection_packageless', ]); } }); diff --git a/packages/metadata-protocol/src/migrations/runtime-index-preflight.ts b/packages/metadata-protocol/src/migrations/runtime-index-preflight.ts index 0fe80eb7681..44a6a9d972d 100644 --- a/packages/metadata-protocol/src/migrations/runtime-index-preflight.ts +++ b/packages/metadata-protocol/src/migrations/runtime-index-preflight.ts @@ -17,6 +17,7 @@ * | `ensureNotificationPreferenceIdentityIndex` | `sys_notification_preference` | one global default per key | * | `ensureActivationLedgerPackagelessIndex` | `sys_metadata_activation` | one package-less row per (type, name) — ADDED, not tightened | * | `ensureUserPermissionSetPackagelessIndex` | `sys_user_permission_set` | one package-less grant per (user, set, organization) — ADDED, not tightened | + * | `ensureConnectorConnectionPackagelessIndex` | `sys_connector_connection` | one package-less connection per (organization, instance) — ADDED, not tightened (#31699) | * * A third, `ensureViewDefinitionActiveIndex` (`sys_view_definition`), retired * with its table under ADR-0131 D13: no writer or reader of that table's rows @@ -120,6 +121,14 @@ import { buildUserPermissionSetPackagelessDuplicateProbeSql, buildUserPermissionSetPresenceSql, } from './user-permission-set-packageless-index.js'; +import { + CONNECTOR_CONNECTION_PACKAGELESS_INDEX_COLUMNS, + CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME, + CONNECTOR_CONNECTION_PACKAGELESS_ROW_SCOPE, + CONNECTOR_CONNECTION_TABLE, + buildConnectorConnectionPackagelessDuplicateProbeSql, + buildConnectorConnectionPresenceSql, +} from './connector-connection-packageless-index.js'; /** The column every one of the duplicate-listing queries counts into. */ const DUPLICATE_ROWS_COLUMN = 'duplicate_rows'; @@ -196,8 +205,9 @@ function isMysqlClient(client?: string): boolean { } /** - * Every index these migrations build — SIX, from five migrations (the grant's - * at schema sync, the rest at `kernel:ready`), because + * Every index these migrations build — SEVEN, from six migrations (the + * grant's and the connector connection's at schema sync, the rest at + * `kernel:ready`), because * `ensureMetadataOverlayIndexes` builds one index per overlay state and either * can be blocked independently. * @@ -276,6 +286,17 @@ export function runtimeIndexProbes(opts: { client?: string } = {}): RuntimeIndex presenceSql: buildUserPermissionSetPresenceSql(), duplicateSql: buildUserPermissionSetPackagelessDuplicateProbeSql(), }, + { + // [ADR-0150 D8 row R11, #31699] The grant's case on the connection + // table: its own name, added beside the declared key. + migration: 'ensureConnectorConnectionPackagelessIndex', + table: CONNECTOR_CONNECTION_TABLE, + index: CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME, + keyParts: [...CONNECTOR_CONNECTION_PACKAGELESS_INDEX_COLUMNS], + rowScope: CONNECTOR_CONNECTION_PACKAGELESS_ROW_SCOPE, + presenceSql: buildConnectorConnectionPresenceSql(), + duplicateSql: buildConnectorConnectionPackagelessDuplicateProbeSql(), + }, ]; } diff --git a/packages/metadata-protocol/src/plugin.ts b/packages/metadata-protocol/src/plugin.ts index aec216e062b..4d8c704b705 100644 --- a/packages/metadata-protocol/src/plugin.ts +++ b/packages/metadata-protocol/src/plugin.ts @@ -47,6 +47,7 @@ import { resolveActivationLedgerIndexSeam, } from './migrations/activation-ledger-packageless-index.js'; import { createUserPermissionSetGuardAtSchemaSync } from './migrations/user-permission-set-packageless-index.js'; +import { createConnectorConnectionGuardAtSchemaSync } from './migrations/connector-connection-packageless-index.js'; import { createRecordedBySentinelPlan } from './migrations/recorded-by-sentinel.js'; import { ObjectStackProtocolImplementation } from './protocol.js'; import type { MetadataAuthoringChannel } from './protocol.js'; @@ -288,8 +289,15 @@ export function assembleMetadataProtocol( // table lock. A refusal is reported once per boot // (`createUserPermissionSetGuardAtSchemaSync`). const ensureGrantGuard = createUserPermissionSetGuardAtSchemaSync(ql, ctx.logger); + // [ADR-0150 D8 row R11, #31699] The same guard on the connector + // connection table, built the same way and for the same reason: + // the old `(organization_id, connector_name)` key stood from the + // table's first DDL, so its package-less half must too + // (`createConnectorConnectionGuardAtSchemaSync`). + const ensureConnectionGuard = createConnectorConnectionGuardAtSchemaSync(ql, ctx.logger); (ctx as any)?.hook?.('objectql:schema-synced', async () => { await ensureGrantGuard(); + await ensureConnectionGuard(); }); // The `kernel:ready` platform-table repairs this assembly arms: #8629 diff --git a/packages/services/service-automation/src/connector-connection-guard-at-schema-sync.test.ts b/packages/services/service-automation/src/connector-connection-guard-at-schema-sync.test.ts new file mode 100644 index 00000000000..73b56f6f3a3 --- /dev/null +++ b/packages/services/service-automation/src/connector-connection-guard-at-schema-sync.test.ts @@ -0,0 +1,199 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0150 D4 and D8 row R11, #31699] `sys_connector_connection`'s + * package-less guard, `uniq_sys_connector_connection_packageless`, stands from + * the table's first DDL, through a booted kernel, with the object's own key. + * + * The connection's key is `(organization_id, connector_package, + * connector_name)` (the maintainer's ruling on #31699: unique by package and + * name), and `connector_package` is NULL-distinct. Every connection of an + * instance the environment authored or a plugin registers in code names no + * package, so for exactly those the declared key alone constrains nothing. The + * guard keeps them to one per `(organization_id, connector_name)`. + * + * Real `ObjectKernel`, real `ObjectQLPlugin` (its built-in protocol assembly, + * which arms metadata-protocol's migrations) over a real in-memory SQLite + * driver, and the shipped {@link SysConnectorConnection}: read from the object, + * not restated, so the pin measures the key this package declares. A fixture + * plugin ordered after `ObjectQLPlugin` writes connections from its own + * `start()`, before `kernel:ready`, through the driver's own connection, so no + * hook decides the answer: the physical indexes do. + * + * The grant guard's pins (`plugin-security`'s + * `user-permission-set-guard-at-schema-sync.test.ts`) measure the gate-off + * kernels and the re-ensure for the shared machinery; this file pins the + * connection table's own wiring (the subscription in metadata-protocol's + * assembly) and its key. + * + * Ablation (recorded in the PR): with `ensureConnectionGuard()` removed from + * the `objectql:schema-synced` handler in `metadata-protocol`'s `plugin.ts`, + * the boot pins go red at the second package-less connection. + */ + +import { afterEach, describe, expect, it } from 'vitest'; +import { ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core'; +import { ObjectQLPlugin, OBJECTQL_SCHEMA_SYNCED_HOOK, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver, buildIndexName } from '@objectstack/driver-sql'; +import { + CONNECTOR_CONNECTION_OLD_KEY_INDEX_NAME, + CONNECTOR_CONNECTION_PACKAGELESS_INDEX_COLUMNS, + CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME, +} from '@objectstack/metadata-protocol'; +import { SysConnectorConnection } from './sys-connector-connection.object.js'; + +const CONNECTIONS = 'sys_connector_connection'; + +function sqliteDriverPlugin(): Plugin { + return { + name: 'test.driver.sqlite', + type: 'standard', + version: '1.0.0', + async init(ctx: PluginContext) { + ctx.registerService( + 'driver.default', + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), + ); + }, + }; +} + +function connectionObjectPlugin(): Plugin { + return { + name: 'test.connection-object', + type: 'standard', + version: '1.0.0', + dependencies: ['com.objectstack.engine.objectql'], + async init(ctx: PluginContext) { + ctx.getService<{ register(m: unknown): unknown }>('manifest').register({ + id: 'test.connection-object', + namespace: 'sys', + version: '1.0.0', + type: 'plugin', + name: 'Connection object', + objects: [SysConnectorConnection], + }); + }, + }; +} + +type Outcome = 'ok' | 'refused'; + +/** + * The connections the early writer lands, in order, all of instance name + * `billing` in one organization: two naming no package, two packages' own, + * then a second of the first package's. + */ +const WRITES: ReadonlyArray<{ id: string; connector_package: string | null }> = [ + { id: 'c1', connector_package: null }, + { id: 'c2', connector_package: null }, + { id: 'c3', connector_package: 'com.acme.crm' }, + { id: 'c4', connector_package: 'com.acme.hr' }, + { id: 'c5', connector_package: 'com.acme.crm' }, +]; + +function earlyConnectionWriter(seen: { outcomes: Outcome[]; afterReady?: boolean; ctx?: PluginContext }): Plugin { + let ready = false; + return { + name: 'test.early-connection-writer', + type: 'standard', + version: '1.0.0', + dependencies: ['com.objectstack.engine.objectql', 'test.connection-object'], + async init(ctx: PluginContext) { + seen.ctx = ctx; + ctx.hook('kernel:ready', async () => { + ready = true; + }); + }, + async start(ctx: PluginContext) { + seen.afterReady = ready; + const ql = ctx.getService('objectql'); + const knex = (ql as any).getDriver(CONNECTIONS).knex; + for (const w of WRITES) { + try { + await knex(CONNECTIONS).insert({ + id: w.id, + organization_id: 'org_1', + connector_name: 'billing', + connector_package: w.connector_package, + grant: 'authorization_code', + status: 'connected', + revision: 1, + }); + seen.outcomes.push('ok'); + } catch { + seen.outcomes.push('refused'); + } + } + }, + }; +} + +let kernel: ObjectKernel | undefined; +afterEach(async () => { + try { + await kernel?.shutdown(); + } catch { + /* a refused boot leaves the kernel stopped */ + } + kernel = undefined; +}); + +async function boot(bootPhaseHooks: boolean) { + const seen: { outcomes: Outcome[]; afterReady?: boolean; ctx?: PluginContext } = { outcomes: [] }; + kernel = new ObjectKernel({ logger: { level: 'silent' }, bootPhaseHooks }); + await kernel.use(sqliteDriverPlugin()); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(connectionObjectPlugin()); + await kernel.use(earlyConnectionWriter(seen)); + await kernel.bootstrap(); + const ql = kernel.getService('objectql'); + const knex = (ql as any).getDriver(CONNECTIONS).knex; + const indexNames = async (): Promise => + ((await knex.raw("SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = ?", [CONNECTIONS])) as Array<{ + name: string; + }>).map((i) => i.name); + return { seen, indexNames: await indexNames(), readIndexNames: indexNames, ql, knex }; +} + +describe('[#31699] the package-less connection guard stands from schema sync, before any later start() writes', () => { + it('a fresh database: a second connection naming no package is refused, two packages’ connections of one name are admitted, a second of one package’s is refused', async () => { + const { seen, indexNames } = await boot(true); + expect(seen.afterReady).toBe(false); + expect(seen.outcomes).toEqual(['ok', 'refused', 'ok', 'ok', 'refused']); + expect(indexNames).toContain(CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME); + // A fresh database never carries the old two-column key where the guard has a form. + expect(indexNames).not.toContain(CONNECTOR_CONNECTION_OLD_KEY_INDEX_NAME); + }); + + it('a bootPhaseHooks: false host (no kernel:ready) refuses it too', async () => { + const { seen, indexNames } = await boot(false); + expect(seen.afterReady).toBe(false); + expect(seen.outcomes).toEqual(['ok', 'refused', 'ok', 'ok', 'refused']); + expect(indexNames).toContain(CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME); + }); + + it('a later pass builds it again after the table lost it', async () => { + const { seen, readIndexNames, ql, knex } = await boot(true); + await knex.raw(`DROP INDEX ${CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME}`); + expect(await readIndexNames()).not.toContain(CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME); + await seen.ctx!.trigger(OBJECTQL_SCHEMA_SYNCED_HOOK, ql); + expect(await readIndexNames()).toContain(CONNECTOR_CONNECTION_PACKAGELESS_INDEX_NAME); + }); +}); + +describe('[#31699] the names metadata-protocol spells as literals, pinned against their owners', () => { + it('the old key it keeps on a dialect with no guard form is the name driver-sql generates for the key this object declared before', () => { + expect(CONNECTOR_CONNECTION_OLD_KEY_INDEX_NAME).toBe( + buildIndexName(CONNECTIONS, [...CONNECTOR_CONNECTION_PACKAGELESS_INDEX_COLUMNS], true), + ); + }); + + it('the guard key is the object key minus the package column, in the object key’s order', () => { + const unique = (SysConnectorConnection.indexes ?? []).filter((i: any) => i.unique); + expect(unique.map((i: any) => i.fields)).toEqual([['organization_id', 'connector_package', 'connector_name']]); + expect([...CONNECTOR_CONNECTION_PACKAGELESS_INDEX_COLUMNS]).toEqual( + unique[0]!.fields.filter((f: string) => f !== 'connector_package'), + ); + }); +}); diff --git a/packages/services/service-automation/src/connector-connections.test.ts b/packages/services/service-automation/src/connector-connections.test.ts index e15818d3eb3..3ed8eeaf3bd 100644 --- a/packages/services/service-automation/src/connector-connections.test.ts +++ b/packages/services/service-automation/src/connector-connections.test.ts @@ -205,3 +205,54 @@ describe('ADR-0143 D5 — a connection store that cannot be read refuses 503, ne expect(String((err as Error).message)).not.toContain('row 42'); }); }); + +describe('[#31699] a first connect that raced the boot backfill takes its row back, as the old key refused it', () => { + /** + * The key is `(organization_id, connector_package, connector_name)`. Between + * this connect's read ("no row") and its insert, another connect inserted a + * row and a booting replica's backfill stamped it with its one holder. The + * old `(organization_id, connector_name)` key refused this insert; the wider + * key admits it. Ablation (recorded in the PR): with the post-insert count + * removed from `connect`, the second row stands and this pin goes red. + */ + it('the second row is deleted and the connect is refused, nothing kept; the stamped row stands', async () => { + const ql = await dataEngine(); + const racing: ConnectorCredentialEngine = { + find: (o, q) => ql.find(o, q as never), + async insert(o, d, opts) { + await ql.insert( + o, + { organization_id: 'org_a', connector_name: 'crm', connector_package: 'com.acme.crm', grant: 'authorization_code', status: 'connected', revision: 1 }, + { context: SYSTEM } as never, + ); + return ql.insert(o, d, opts as never); + }, + update: (o, d, opts) => { + assertEngineUpdateDispatch(d as never, opts as never); + return ql.update(o, d, opts as never); + }, + delete: (o, opts) => { + assertEngineDeleteDispatch(opts as never); + return ql.delete(o, opts as never); + }, + resolveSecretField: (o, id, f) => (ql as any).resolveSecretField(o, id, f), + }; + const store = new ConnectorConnectionStore(() => racing); + await expect( + store.connect({ organizationId: 'org_a', connectorName: 'crm', userId: 'usr_admin', refreshToken: 'dummy-rt-1' }), + ).rejects.toThrow(/changed while this connect was completing/); + const rows = (await ql.find(CONNECTOR_CONNECTION_OBJECT, { + where: { organization_id: 'org_a', connector_name: 'crm' }, + context: SYSTEM, + } as never)) as Array>; + expect(rows.map((r) => r.connector_package)).toEqual(['com.acme.crm']); + }); + + it('CONTROL: a first connect with no race keeps its one row', async () => { + const ql = await dataEngine(); + const { store, record } = await connected(ql); + expect((await store.read('org_a', 'crm'))!.id).toBe(record.id); + const rows = (await ql.find(CONNECTOR_CONNECTION_OBJECT, { where: { organization_id: 'org_a' }, context: SYSTEM } as never)) as unknown[]; + expect(rows).toHaveLength(1); + }); +}); diff --git a/packages/services/service-automation/src/connector-connections.ts b/packages/services/service-automation/src/connector-connections.ts index 9eaf8e5a643..15b79d793c2 100644 --- a/packages/services/service-automation/src/connector-connections.ts +++ b/packages/services/service-automation/src/connector-connections.ts @@ -205,6 +205,16 @@ export class ConnectorConnectionStore { return affectedRows(result) > 0; } + /** How many rows one instance has in one organization: one at most, but for a connect that raced the backfill. */ + private async rowCount(engine: ConnectorCredentialEngine, organizationId: string, connectorName: string): Promise { + const found = await engine.find(CONNECTOR_CONNECTION_OBJECT, { + where: { organization_id: organizationId, connector_name: connectorName }, + fields: ['id'], + context: SYSTEM_CONTEXT, + }); + return rowsOf(found).length; + } + /** Every organization's row for one instance. */ async listFor(connectorName: string): Promise { const engine = this.resolveEngine(); @@ -296,15 +306,18 @@ export class ConnectorConnectionStore { connected_by: args.userId ?? null, }; let moved = false; + let insertedId: string | undefined; try { if (existing) { moved = !(await this.updateAtRevision(engine, existing.id, existing.revision, row, context)); } else { - await engine.insert( + const created = await engine.insert( CONNECTOR_CONNECTION_OBJECT, { organization_id: args.organizationId, connector_name: args.connectorName, ...row }, { context }, ); + const id = (created as { id?: unknown } | null | undefined)?.id; + insertedId = typeof id === 'string' || typeof id === 'number' ? String(id) : undefined; } } catch (err) { if (isSecretProtectionFailure(err)) { @@ -318,6 +331,40 @@ export class ConnectorConnectionStore { `Connector instance '${args.connectorName}' was not connected: the connection store refused the write. Nothing was kept.`, ); } + // [#31699] The key is `(organization_id, connector_package, + // connector_name)`, so a row the boot backfill stamped with its package + // between this connect's read and its insert no longer refuses the + // insert, as the old `(organization_id, connector_name)` key did. Two + // rows of one instance in one organization would leave `read` answering + // either and `revoke` deleting one. So the insert that made the second + // row takes itself back and is refused, as the old key refused it. + // (3a-ii counts by package once the store carries it.) A foreign + // message is never quoted, as above. + if (!existing && !moved) { + const twice = new ConnectorCredentialUnavailableError( + `Connector instance '${args.connectorName}' was connected twice in this organization: another connect ` + + 'landed while this one was completing. Revoke the connection until it reads as not connected, then connect again.', + ); + let rows: number; + try { + rows = await this.rowCount(engine, args.organizationId, args.connectorName); + } catch { + throw new ConnectorCredentialUnavailableError( + `Connector instance '${args.connectorName}' was connected, but the connection store did not answer the ` + + 'read that checks it is the only connection of this instance here. Read the connection before using it.', + ); + } + if (rows > 1) { + // An engine that does not answer the created row's id: the row cannot be told apart, so say so. + if (insertedId === undefined) throw twice; + try { + await engine.delete(CONNECTOR_CONNECTION_OBJECT, { where: { id: insertedId }, context: SYSTEM_CONTEXT }); + } catch { + throw twice; + } + moved = true; + } + } if (moved) { throw new ConnectorCredentialUnavailableError( `Connector instance '${args.connectorName}' was not connected: its connection changed while this connect was ` diff --git a/packages/services/service-automation/src/stored-reference-package-backfill.ts b/packages/services/service-automation/src/stored-reference-package-backfill.ts index 0e51bd6c41f..8ef3db5ea84 100644 --- a/packages/services/service-automation/src/stored-reference-package-backfill.ts +++ b/packages/services/service-automation/src/stored-reference-package-backfill.ts @@ -46,8 +46,9 @@ * packages hold reads the row's package (a row with none answers only while * one package holds the name). A null left by this backfill still reads by * name. The connection store (R11) still reads by name, until the connector - * child moves it. S4's upgrade report reads the columns too. No unique key - * changes. + * child moves it. S4's upgrade report reads the columns too. R11's column is a + * part of its table's unique key (#31699), so a bind there can meet a unique + * violation (below); no other reference's key carries its column. * * ## Re-runnable * @@ -55,10 +56,21 @@ * column, so a second run binds nothing and reports the same ambiguous and * unheld names. A row that names a package is never read as a candidate, so a * run can only add a package, never move one. + * + * [#31699] A bind the database refuses as a unique violation — the row would be + * a second row of one key, a connection beside another of the same organization + * and instance that already names the holder (R11's key is `(organization_id, + * connector_package, connector_name)`) — is reported by id (`duplicated`, at + * `warn`) and the row is left naming no package; the walk goes on, so one such + * row never stops every later row from being bound, nor every later boot. The + * plugin-security grant backfill's rule (#32164). Any other failed write still + * ends the run. A dry run asks the key's own question of each row it would bind + * (`identityColumns`), and reports a row the write would refuse as + * `duplicated`, not `bound`. */ import { describePackageScopedHolder, type PackageScopedResolution } from '@objectstack/objectql'; -import { keysetWalk } from '@objectstack/types'; +import { isUniqueViolationError, keysetWalk } from '@objectstack/types'; /** The declared type a stored reference names. */ export type StoredReferenceType = 'flow' | 'connector'; @@ -77,6 +89,13 @@ export interface StoredReference { readonly packageColumn: string; /** The rows asked, beyond "the package column is null" (none of the three narrows it). */ readonly where?: Record; + /** + * [#31699] The columns beside the name and the package that make up the + * table's unique key, when it carries the package (R11: the organization). + * A dry run asks that key of each row it would bind; absent, a bind cannot + * collide with another row. + */ + readonly identityColumns?: readonly string[]; } /** The three stored references this service owns (ADR-0150 D8 rows R8, R9, R11). */ @@ -89,7 +108,14 @@ export const STORED_AUTOMATION_REFERENCES: readonly StoredReference[] = Object.f packageColumn: 'flow_package', }, { row: 'R9', type: 'flow', object: 'sys_flow_credential', nameColumn: 'flow_name', packageColumn: 'flow_package' }, - { row: 'R11', type: 'connector', object: 'sys_connector_connection', nameColumn: 'connector_name', packageColumn: 'connector_package' }, + { + row: 'R11', + type: 'connector', + object: 'sys_connector_connection', + nameColumn: 'connector_name', + packageColumn: 'connector_package', + identityColumns: ['organization_id'], + }, ]); /** Infrastructure rows, written and read the way the service's other boot passes do. */ @@ -142,6 +168,13 @@ export interface StoredReferenceBackfillReport { readonly unheld: readonly ReferencedName[]; /** Names the environment's own item, or the platform's, answers: left null, its spelling. */ readonly unpackaged: ReadonlyArray; + /** + * [#31699] Rows the bind would make a second row of one key (another row of + * the same key already names the holder): the write was refused as a + * unique violation, the row is left naming no package, and the walk goes + * on. Each is named by id, so an operator can review the pair. + */ + readonly duplicated: ReadonlyArray<{ readonly id: string; readonly name: string; readonly packageId: string }>; } /** The engine slice the backfill reads and writes through. */ @@ -178,13 +211,20 @@ export async function backfillStoredReferencePackages( const ambiguous = new Map(); const unheld = new Map(); const unpackaged = new Map(); + const duplicated: Array<{ id: string; name: string; packageId: string }> = []; const answers = new Map(); const { object, nameColumn, packageColumn, type } = reference; + const identityColumns = reference.identityColumns ?? []; const unbound = { [packageColumn]: null }; + const dryBound = new Set(); const walk = keysetWalk( async (query) => { - const page = await engine.find(object, { ...query, fields: ['id', nameColumn, packageColumn], context: SYSTEM_CTX }); + const page = await engine.find(object, { + ...query, + fields: ['id', nameColumn, packageColumn, ...identityColumns], + context: SYSTEM_CTX, + }); return Array.isArray(page) ? (page as Row[]) : []; }, { where: reference.where ? { $and: [unbound, reference.where] } : unbound, pageSize: PAGE_SIZE }, @@ -204,10 +244,31 @@ export async function backfillStoredReferencePackages( } switch (holder.kind) { case 'package': { - if (!options?.dryRun) { - await engine.update(object, { id, [packageColumn]: holder.packageId }, { context: SYSTEM_CTX }); - } const packageId = holder.packageId; + if (options?.dryRun) { + // A dry run writes nothing, so it also counts the keys it has + // already bound in this pass: two unbound rows of one key bind + // once, and the second is a second row, as the real run finds. + const key = keyOf(identityColumns, row, name, packageId); + if ((key !== undefined && dryBound.has(key)) || (await wouldBeSecondRow(engine, reference, row, name, packageId))) { + duplicated.push({ id: String(id), name, packageId }); + break; + } + if (key !== undefined) dryBound.add(key); + } else { + try { + await engine.update(object, { id, [packageColumn]: packageId }, { context: SYSTEM_CTX }); + } catch (e: unknown) { + // [#31699] One row whose bind is a unique violation is reported + // and left as it stands; the walk goes on (`duplicated`). Only + // where the key carries the package, and only once a read + // confirms the row that already names the holder: anything + // else still ends this reference's pass. + if (!isUniqueViolationError(e) || !(await wouldBeSecondRow(engine, reference, row, name, packageId))) throw e; + duplicated.push({ id: String(id), name, packageId }); + break; + } + } tally(bound, name, () => ({ name, rows: 0, packageId })); break; } @@ -234,9 +295,53 @@ export async function backfillStoredReferencePackages( ambiguous: [...ambiguous.values()], unheld: [...unheld.values()], unpackaged: [...unpackaged.values()], + duplicated, }; } +/** + * [#31699] The unique key `row` would take once bound to `packageId`, or + * `undefined` when the reference's key does not carry the package or a key + * part is NULL (a NULL key part collides with nothing). + */ +function keyOf(identityColumns: readonly string[], row: Row, name: string, packageId: string): string | undefined { + if (identityColumns.length === 0) return undefined; + const parts: unknown[] = []; + for (const column of identityColumns) { + const value = row[column]; + if (value === null || value === undefined) return undefined; + parts.push(value); + } + return JSON.stringify([...parts, name, packageId]); +} + +/** + * [#31699] Would binding `row` to `packageId` make it a second row of the + * table's unique key? Asked by a dry run, and by a real run to confirm a + * unique violation before reporting it, only of a reference whose + * key carries the package (`identityColumns`): one read of the row that already + * names the holder under the same key. + */ +async function wouldBeSecondRow( + engine: StoredReferenceBackfillEngine, + reference: StoredReference, + row: Row, + name: string, + packageId: string, +): Promise { + const identityColumns = reference.identityColumns ?? []; + if (identityColumns.length === 0) return false; + const where: Record = { [reference.nameColumn]: name, [reference.packageColumn]: packageId }; + for (const column of identityColumns) { + const value = row[column]; + // A NULL key part collides with nothing under a UNIQUE index. + if (value === null || value === undefined) return false; + where[column] = value; + } + const found = await engine.find(reference.object, { where, fields: ['id'], limit: 1, context: SYSTEM_CTX }); + return Array.isArray(found) && found.length > 0; +} + /** The logger slice a run writes to. */ export interface StoredReferenceBackfillLogger { info(message: string, meta?: Record): void; @@ -306,4 +411,13 @@ export function logStoredReferenceBackfill(report: StoredReferenceBackfillReport { unheld: report.unheld }, ); } + if (report.duplicated.length > 0) { + logger.warn( + `[automation] ${at}: binding these rows would make each a second row of one key — another row of the same key ` + + 'already names the holder — so each is left naming no package. Review the pair and delete the row that ' + + 'should not stand — ' + + report.duplicated.map((d) => `'${d.name}' row ${d.id} → ${d.packageId}`).join(', ') + '.', + { duplicated: report.duplicated }, + ); + } } diff --git a/packages/services/service-automation/src/stored-reference-package-column.test.ts b/packages/services/service-automation/src/stored-reference-package-column.test.ts index 9c1ef527fe6..308f46f93ff 100644 --- a/packages/services/service-automation/src/stored-reference-package-column.test.ts +++ b/packages/services/service-automation/src/stored-reference-package-column.test.ts @@ -310,6 +310,90 @@ describe('R11 — a connector connection gains the package that holds its connec expect(report.ambiguous).toEqual([{ name: 'mailer', rows: 1, candidates: [`package "${A}"`, `package "${B}"`] }]); expect(report.unpackaged).toEqual([{ name: 'my_api', rows: 1, holder: 'environment' }]); expect(report.unheld).toEqual([{ name: 'gone', rows: 1 }]); + expect(report.duplicated).toEqual([]); + }); + + /** + * [#31699] R11's column is a part of its table's unique key + * (`(organization_id, connector_package, connector_name)`). A row naming no + * package beside a row of the same organization and instance that already + * names the holder cannot be bound: the write is a unique violation. It is + * reported by id and left naming no package, and the walk goes on, so the + * rows after it are still bound and the next boot is not stuck on it. + * + * ABLATED (the walk without its per-row catch, measured): the run throws + * `DuplicateRecordError` at k1, so the boot pass logs "did not finish", + * makes no R11 report, and every later boot stops at the same row. + */ + it('a bind that would be a second row of one key is reported by id and left naming no package; the walk goes on', async () => { + const engine = await boot(); + const connection = (id: string, name: string, pkg: string | null = null) => ({ + id, organization_id: ORG, connector_name: name, connector_package: pkg, + grant: 'authorization_code', status: 'connected', revision: 1, + }); + // k0 already names A; k1 is the stray row of the same key; k9 sorts after it. + for (const row of [connection('k0', 'billing', A), connection('k1', 'billing'), connection('k9', 'billing', null)]) { + if (row.id === 'k9') row.organization_id = 'org_b'; + await engine.insert(CONNECTIONS.object, row, { context: { isSystem: true, tenantId: row.organization_id } }); + } + + const dry = await backfillStoredReferencePackages(engine, CONNECTIONS, holderOf, { dryRun: true }); + expect(dry.duplicated).toEqual([{ id: 'k1', name: 'billing', packageId: A }]); + expect(dry.bound).toEqual([{ name: 'billing', rows: 1, packageId: A }]); + + const report = await backfillStoredReferencePackages(engine, CONNECTIONS, holderOf); + expect(report.duplicated).toEqual([{ id: 'k1', name: 'billing', packageId: A }]); + expect(report.bound).toEqual([{ name: 'billing', rows: 1, packageId: A }]); + expect(await column(engine, CONNECTIONS.object, 'connector_package')).toEqual({ k0: A, k1: null, k9: A }); + + // The boot pass says so at warn, and finishes R11. + const logger = silentLogger(); + const reports = await backfillStoredReferencePackagesAtBoot(engine, (object) => object === CONNECTIONS.object, holderOf, logger); + expect(reports.map((r) => [r.row, r.duplicated.length])).toEqual([['R11', 1]]); + expect(logger.warn).toHaveBeenCalledWith( + expect.stringContaining(`'billing' row k1 → ${A}`), + { duplicated: [{ id: 'k1', name: 'billing', packageId: A }] }, + ); + expect(logger.warn).not.toHaveBeenCalledWith(expect.stringContaining('did not finish'), expect.anything()); + }); + + it('two unbound rows of one key: the dry run binds one and lists the other, as the real run does', async () => { + const engine = await boot(); + for (const id of ['k1', 'k2']) { + await engine.insert(CONNECTIONS.object, { + id, organization_id: ORG, connector_name: 'billing', grant: 'authorization_code', status: 'connected', revision: 1, + }, { context: SYS_ORG }); + } + const dry = await backfillStoredReferencePackages(engine, CONNECTIONS, holderOf, { dryRun: true }); + const real = await backfillStoredReferencePackages(engine, CONNECTIONS, holderOf); + expect(real.duplicated).toEqual([{ id: 'k2', name: 'billing', packageId: A }]); + expect(real.bound).toEqual([{ name: 'billing', rows: 1, packageId: A }]); + expect({ duplicated: dry.duplicated, bound: dry.bound }).toEqual({ duplicated: real.duplicated, bound: real.bound }); + }); + + it('a unique violation no row of the holder confirms is not read as a second row: it ends the run', async () => { + const engine = await boot(); + await engine.insert(CONNECTIONS.object, { + id: 'k1', organization_id: ORG, connector_name: 'billing', grant: 'authorization_code', status: 'connected', revision: 1, + }, { context: SYS_ORG }); + vi.spyOn(engine, 'update').mockRejectedValueOnce(Object.assign(new Error('UNIQUE constraint failed: other_key'), { code: 'SQLITE_CONSTRAINT_UNIQUE' })); + await expect(backfillStoredReferencePackages(engine, CONNECTIONS, holderOf)).rejects.toThrow('other_key'); + }); + + it('a unique violation on a reference whose key does not carry the package (R8) ends the run', async () => { + const engine = await boot(); + await engine.insert(RUNS.object, run('r1', ONE_HOLDER, 'paused'), { context: SYS_ORG }); + vi.spyOn(engine, 'update').mockRejectedValueOnce(Object.assign(new Error('UNIQUE constraint failed: runs'), { code: 'SQLITE_CONSTRAINT_UNIQUE' })); + await expect(backfillStoredReferencePackages(engine, RUNS, holderOf)).rejects.toThrow('UNIQUE constraint failed: runs'); + }); + + it('CONTROL — any other failed write still ends the run', async () => { + const engine = await boot(); + await engine.insert(CONNECTIONS.object, { + id: 'k1', organization_id: ORG, connector_name: 'billing', grant: 'authorization_code', status: 'connected', revision: 1, + }, { context: SYS_ORG }); + vi.spyOn(engine, 'update').mockRejectedValueOnce(new Error('disk full')); + await expect(backfillStoredReferencePackages(engine, CONNECTIONS, holderOf)).rejects.toThrow('disk full'); }); }); @@ -631,7 +715,7 @@ describe('R10 — the missed-run check reads the window\'s bare key too (the tra }); }); -// ── Keys that do not move: byte-identical pins (seat rulings Q2, R14) ──────── +// ── Keys that do not move: byte-identical pins (seat rulings Q2, R14; R11 moved by #31699) ── describe('no key moves: each table keeps its indexes byte for byte (ADR-0150 D8, seat ruling Q2)', () => { it('sys_automation_run', () => { @@ -651,9 +735,14 @@ describe('no key moves: each table keeps its indexes byte for byte (ADR-0150 D8, ])); }); - it('sys_connector_connection (R11: one connection per instance name in an organization)', () => { + // [#31699] The one key that moves, by the maintainer's ruling on that card + // ("unique by package and name", 2026-11-14): an instance is (package, + // name), so one organization may connect both packages' instances of one + // name. Spelled 'global' with the organization listed, the spelling the + // drivers' widening arms retire the old key under. + it('sys_connector_connection (R11: one connection per instance — package and name — in an organization)', () => { expect(JSON.stringify(SysConnectorConnection.indexes)).toBe(JSON.stringify([ - { fields: ['connector_name'], unique: 'organization' }, + { fields: ['organization_id', 'connector_package', 'connector_name'], unique: 'global' }, ])); }); diff --git a/packages/services/service-automation/src/sys-connector-connection.object.ts b/packages/services/service-automation/src/sys-connector-connection.object.ts index f8b06ab7b8a..f9d9c991574 100644 --- a/packages/services/service-automation/src/sys-connector-connection.object.ts +++ b/packages/services/service-automation/src/sys-connector-connection.object.ts @@ -31,7 +31,17 @@ import { ObjectSchema, Field } from '@objectstack/spec/data'; * One row per `(organization, connector instance)` (Q1 = A: a connection is * shared by its organization, and every run of that organization dispatches * with it). The organization column is explicit so the row is bound to the - * organization that connected it, not to whatever context reads it. + * organization that connected it, not to whatever context reads it. A + * connector instance is identified by `(package, name)` (ADR-0150 D4), so the + * declared unique key is (`organization_id`, `connector_package`, + * `connector_name`) (#31699, ruled "unique by package and name"): one + * organization may connect two packages' instances of one name. A connection + * naming no package (an instance the environment authored or a plugin + * registers in code) is held to one per organization and name by the runtime + * partial index `uniq_sys_connector_connection_packageless`, which the + * declared surface cannot spell (metadata-protocol's + * `connector-connection-packageless-index.ts`; driver-mongodb's runtime-owned + * uniques). * * ⛔ Not a sign-in account (D6). Nothing here is a better-auth `account` row, * and no sign-in path reads it: an integration grant never lets anyone sign in, @@ -83,8 +93,8 @@ export const SysConnectorConnection = ObjectSchema.create({ // boot from the instance's one package holder // (`stored-reference-package-backfill.ts`); empty for an instance the // environment authored or a plugin registers in code, and for a name no - // single package holds. Nothing reads it yet, no writer stamps it, and the - // unique key is unchanged. Width: the package-id class. + // single package holds. A key part of the unique key below (#31699). + // Width: the package-id class. connector_package: Field.text({ label: 'Connector Package', required: false, @@ -178,8 +188,19 @@ export const SysConnectorConnection = ObjectSchema.create({ indexes: [ // One connection per instance in an organization — the connect door's - // upsert key (ADR-0143 Q1 = A). - { fields: ['connector_name'], unique: 'organization' }, + // upsert key (ADR-0143 Q1 = A). [ADR-0150 D4 and D8 row R11, #31699] An + // instance is (package, name), so the key carries the package column, and + // one organization may connect both packages' instances of one name. + // `unique: 'global'` materializes exactly the listed columns, the + // organization column among them, and it is the spelling the drivers' + // widening arms retire the old `(organization_id, connector_name)` key + // under, create-before-drop, once the package-less guard stands beside it + // (`uniq_sys_connector_connection_packageless`, metadata-protocol's + // `connector-connection-packageless-index.ts`): `connector_package` is + // NULL-distinct, so that guard holds connections naming no package to one + // per organization and instance. Spelled `'organization'`, the old key + // would read as an orphan whose drop is destructive (measured). + { fields: ['organization_id', 'connector_package', 'connector_name'], unique: 'global' }, ], enable: { diff --git a/packages/types/src/driver-error-classification.callers.test.ts b/packages/types/src/driver-error-classification.callers.test.ts index 5faa91f07e4..5366386c1f4 100644 --- a/packages/types/src/driver-error-classification.callers.test.ts +++ b/packages/types/src/driver-error-classification.callers.test.ts @@ -426,6 +426,10 @@ const OPERATOR_TEXT_CALLERS: Readonly