Repository navigation
fix(core): an import upsert finds its match through the organization unique index instead of scanning the table per row - #31846
Conversation
The update/upsert match lookup queried the key fields alone. Under the single posture the engine adds no tenant scope to a read, so the lookup could not use the (organization_id, key) unique index and scanned the table once per row. It now carries the target's tenant column set to the context's organization, read off the target's declaration once per import; with no organization, no declaration, a federated target or no tenant column the lookup stays the key alone. The tenancy-scope predicate (resolveTenantFieldName, DEFAULT_TENANT_FIELD) and isFederatedObject move down to @objectstack/core so the runner asks the engine's own rule; objectql re-exports the same bindings. Claude-Session: https://claude.ai/code/session_01ADHkmQPtCxVmh3N9qvbqxE Co-authored-by: Claude <noreply@anthropic.com>
…ancy census The engine's tenancy-scope predicate now lives in @objectstack/core: the objectql suite pins that its re-exports are the same bindings, the injected-column readers census drops the two definition rows that moved out of its scan, and the platform-object tenancy census loads the predicate (and reads its header) from the new file. Adds the patch changeset for @objectstack/core and @objectstack/objectql. Claude-Session: https://claude.ai/code/session_01ADHkmQPtCxVmh3N9qvbqxE Co-authored-by: Claude <noreply@anthropic.com>
… real driver The import door case updated a row the stub had stored without the tenant column every real driver stamps from DriverOptions.tenantId; the import runner's match lookup now reads by that column, so the stub carries it. Audit columns stay the hook's alone. Claude-Session: https://claude.ai/code/session_01ADHkmQPtCxVmh3N9qvbqxE Co-authored-by: Claude <noreply@anthropic.com>
📓 Docs Drift CheckThis PR changes 2 package(s): 7 hand-written doc(s) NAME something this change touched and may need an implementation-accuracy re-verification:
⛔ 4 release-owned page(s) also name something this change touched. These are read-only:
What this run could not see
Coarse fallback — 48 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): Which tree this was computed onThis run read A worktree cut from an older # while this PR is open — GitHub drops the merge commit once it closes
git fetch origin 356da5fabe6f8e9a971117aca2876b7c5cd317b1 && git checkout 356da5fabe6f8e9a971117aca2876b7c5cd317b1
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 785d432bb0fb3e13f4679f2ee0f94f276cac7561 003b09d533231ce10d2fc131c79ec679c28ef395 && git checkout -B drift-repro 785d432bb0fb3e13f4679f2ee0f94f276cac7561 && git merge --no-ff 003b09d533231ce10d2fc131c79ec679c28ef395
node scripts/docs-audit/affected-docs.mjs --json 785d432bb0fb3e13f4679f2ee0f94f276cac7561
|
@objectstack/core now exports resolveTenantFieldName, DEFAULT_TENANT_FIELD and isFederatedObject, moved from @objectstack/objectql, which re-exports the same bindings. Claude-Session: https://claude.ai/code/session_01ADHkmQPtCxVmh3N9qvbqxE Co-authored-by: Claude <noreply@anthropic.com>
|
domain:server#2 · os-steve · session_01ADHkmQKZzp4DLtqiCkZZRM Contract reviewServed-tier: Inputs: card #31812 (body, the seat's delta and the shape-A amendment), PR #31846 body and file list, and the net diff of ① Derived judgments
② Semver level
③ Boundary flags
Implemented-by: VERDICT: PASS |
|
domain:server#2 · os-steve · session_01ADHkmQKZzp4DLtqiCkZZRM 维护者速读
席位核对 — ACCEPT · domain:server#2 · Head-sha
|
Requested by Steve · project thread
Fixes #31812
Clause-②: yes (widening) — @objectstack/core gains resolveTenantFieldName, DEFAULT_TENANT_FIELD and isFederatedObject (moved from @objectstack/objectql, which re-exports the same bindings)
Metadata-protocol: none
维护者速读
organization_id = ? AND key = ?),能用上 (organization_id, key) 唯一索引。packages/core/src/utils/import-runner.ts的matchScopeOf和findExisting;packages/core/src/security/tenant-field.ts(从 objectql 原样下移的规则)。pnpm --filter @objectstack/rest exec vitest run src/import-upsert-match-organization.test.ts,3 条全过,第一条断言 SQLite 的执行计划是按唯一索引 SEARCH。What changes
runImport's match lookup (findExisting, used by update and upsert, dry run included) now adds the target's tenant column, set to the context'stenantId, beside the key fields. The organization is the one a created row is stamped with (the engine's write target in every posture), so the lookup finds exactly the record an insert of that key would collide with.p.getMetaItem), by the engine's own rule: a federated (external) object has none, thenresolveTenantFieldNamedecides (tenancy.enabled: false→ none; a declaredtenancy.tenantFieldthe object has; elseorganization_id).getMetaItem, the declaration read fails, the object is federated, or it has no tenant column. A key set that already names the tenant column keeps the row's own value.resolveTenantFieldName,DEFAULT_TENANT_FIELDandisFederatedObjectmove from@objectstack/objectqldown to@objectstack/core(security/tenant-field.ts), following ADR-0138 D4's move ofresolveSystemWriteOrganization. objectql'stenancy/system-write-organization.tsandfederated-object.tsre-export the same bindings; no behaviour change there. The platform-object tenancy census now loads the predicate, and reads its header, from the new file.Why
Step 0, measured on
origin/main6be71abcthrough the realrunImport→ protocolfindData→SqlDriver(better-sqlite3):singleposture (the default when multi-org is off): the lookup reached SQLite asselect * from T where external_id = ? order by id asc limit ?, planSCAN. The engine's read scope (engine-driver-options.tsdriverReadScope→computeTenantLayer0Verdict) isnoneundersingleby design (ADR-0131 D11).isolatedposture: the same call reached SQLite asorganization_id = ? and external_id = ?, planSEARCH … USING INDEX uniq_T_organization_id_external_id. The index is the plain-column form, so the cause is (a): no organization predicate reaches the driver undersingle.Shape, by seat ruling:
organization_id = ? AND KEYonly. AnOR organization_id IS NULLleg was measured and rejected (readings below): on SQLite it forfeits the index on every table created since ADR-0131 D1 (tenant column NOT NULL).Tests
packages/core/src/utils/import-runner-match-organization.test.ts(new, 18 cases): thewhereis tenant column + key for a job context and a session context, upsert and update, dry run, ordered key sets, a declaredtenancy.tenantField; the declaration is read once per import. CONTROL (the lookup is the key alone and the stored row still matches): no tenant column,tenancy.enabled: false, an external object, a declared tenantField the object lacks, no / blank / absent organization, nogetMetaItem, a failing declaration read, and a key set that names the tenant column. RED on main: 8 failed, 10 passed.packages/rest/src/import-upsert-match-organization.test.ts(new, 3 cases, realSqlDriver,singleposture): the lookup SQL iswhere organization_id = ? and external_id = ?with bindings[org, key], and itsEXPLAIN QUERY PLANisSEARCH … USING INDEX uniq_…_organization_id_external_id. CONTROL: a key with no index (code) still matches and updates; an object with no tenant column (systemFields: false) matches on the key alone. RED on main: 2 failed, 1 passed.packages/objectql/src/system-write-organization.test.ts: objectql's module and barrel exports of the three moved names are the@objectstack/corebindings.Forced test edits:
packages/objectql/src/audit-stamp-skip-automations.test.ts: its stub driver stored rows without the tenant column, which every real driver stamps fromDriverOptions.tenantId(injectTenantOnInsert). Case (c) imports a row and then updates it bycode; with the lookup now scoped byorganization_id, the stub's row (no column) no longer matched (NO_MATCH). The stub now stampsorganization_idfromoptions.tenantIdon create; audit columns stay the hook's alone.packages/objectql/src/federated-injected-column-readers.test.ts: twoREADERSrows named the definitions that moved out of objectql (the module-level row oftenancy/system-write-organization.tsand itsresolveTenantFieldNamerow), so the census reported them stale. Rows removed; the header says the definitions live in core.Acceptance notes
6328195425): "NULL is not a state, and nothing reads a NULL tenant value as an owner". measure(adr-0131 D1): a database 18.0.0 created is certified by its birth marker yet keeps every tenant column nullable, and the ceremony certifies tables it left nullable — D1 is not yet a fact the certificate proves #24919 measured 0 NULL-organization rows in every store it read.groupposture. The match is now the record in the active organization, the one a create from that context writes. It no longer reaches a same-key row in another member organization (updating that row would be a cross-organization write).organization.jobExecutionContext(undefined)gives{ isSystem: true }with notenantId, so that pull keeps the key-only lookup. sync-in P0 measurement (epic #31763): run the existing pull path end to end (rest connector + mapping.connectorSource + job.pull) and record which of G1–G9 hold #31778 G9's measured setup is that path; it is job pull: a job with no declared organization runs its pull with no tenantId, so the import match lookup cannot carry the organization the writes are stamped with #31823.organization_idunreadable for the importing user would now refuse the lookup at the predicate guard (assertReadableQueryFields), since the lookup filters on it. Read only, not measured; no shipped permission set does this.findDataalso runs acount(*)over the samewherefor every lookup (it now benefits from the same index probe); plugin-security and plugin-sharing each keep their ownisFederatedObjectcopy (federated-phantom-anchors.ts).Verification
Head:
003b09d5(the changeset declaration line only, on top ofe9f6ba17, which mergedorigin/mainat0a4d8b18). Each reading below names the commit it was taken on; on003b09d5the changeset gatescheck-changeset-no-major(with this body as the event payload),check-adr-0087-registration(and--self-test),check-empty-changeset,check-declaration-mirrorsandcheck:changeset-gate-self-testsexit 0.Timing: rows/s at 10,000 and 50,000 rows, before and after
Real
ObjectQL+SqlDriver(better-sqlite3:memory:),singleposture, context{ isSystem: true, tenantId }. The table is pre-seeded to N rows; then one upsert of 1,000 rows (500 update existing keys spread over the table, 500 create new keys). Shared-box readings under the verify lock.6be71abc)a5aeb1a1)Before, throughput falls with table size (each lookup scans). After, it is flat.
Query plans: SQLite and Postgres
SQLite (better-sqlite3), unique index
(organization_id, external_id), 20,000 rows:organization_id = ? and external_id = ?(this PR)(organization_id = ? or organization_id is null) and external_id = ?organization_id is null and external_id = ?external_id = ?(main)Postgres 16, 100,000 rows, ANALYZE:
organization_id = 'org_a' and external_id = 'E7'(this PR):Index Scan using u_nn … Index Cond: ((organization_id = 'org_a') AND (external_id = 'E7')).external_id = 'E7'(main):Seq Scan … Filter: (external_id = 'E7').Ablation
On
a5aeb1a1. Mutation (committed fix first,scripts/ablation-replace.mjs): the line that adds the tenant column to the lookup'swherereplaced by a marker statement (ABLATED_31812).pnpm --filter @objectstack/core build;ablation-dist-preflight.mjs @objectstack/core ABLATED_31812→ marker indist/index.jsanddist/index.cjs.Restore: blob == HEAD,
git diff HEADempty; rebuilt;--absentpreflight: dist reading passed (marker in 0 of 14 built files); its tree reading exited 3 only because two untracked probe files were still inpackages/rest/src(removed right after, never committed). rest test after restore: 3 passed.Suites and gates
Package suites, before the merge (head
88c2e6a2, then the stub fixfdd5c8d8), all green:@objectstack/coretest: Test Files 140 passed, Tests 3212 passed.@objectstack/objectqltest: Tests 11817 passed (the first run had 1 failure, the audit stub case named under Forced test edits; green after it).@objectstack/resttest: Test Files 397 passed, Tests 7636 passed, 332 skipped.runImportconsumers:service-automationconnector-pull 27 passed;plugin-authadmin-import-users / account-invitation-marker / durability-swallow-repair 120 passed;service-messagingnotification-template integration 38 passed.@objectstack/core,@objectstack/objectql,@objectstack/rest: exit 0.After merging
origin/main(heade9f6ba17), rebuilt (turbo run build --filter=./packages/** --filter=./examples/**, 82 tasks successful), then:import-runner-match-organization.test.ts18 passed; restimport-upsert-match-organization.test.ts3 passed; objectqlsystem-write-organization,federated-object,federated-injected-column-readers,audit-stamp-skip-automations53 passed; the three typechecks exit 0.eslint --no-inline-config packages/core packages/objectql packages/rest: exit 0.node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack: 88 derived families, each run one9f6ba17, all exit 0.check-plugin-teardown-shape.mjs --self-testfirst exited 3 (its fixture commit was not in the shallow clone); aftergit fetch --depth=1 origin 621a4876…it exited 0.--ranreconciliation: 88 derived, 88 run, 0 NOT-MEASURED, 0 UNRUN.check-platform-object-tenancy-census.mjs --self-testpassed and the gate reads 99 platform-namespace objects, 51 in reach, 48 outside, matching the tree.Dogfood battery: not run locally (no
!in the title, no(narrowing)arm); CI's queue run carries it.Human Minimum
packages/specholds no runtime logic.pnpm lintpasses.main, one pull request.packages/spectouched: not touched.content/docs/references/,packages/*/CHANGELOG.mdorcontent/docs/releases/.🤖 Generated with Claude Code
https://claude.ai/code/session_01ADHkmQPtCxVmh3N9qvbqxE
Generated by Claude Code