Repository navigation
fix(driver-mongodb): two records with a null unique field are both admitted, as on driver-sql and driver-memory - #29339
Conversation
…er-sql and driver-memory
The field-level and declared unique indexes were built
{ unique: true, sparse: true }; a sparse index still indexes an explicit
null, so two records with a cleared unique field collided. They are now
partial over every non-null BSON type, with a plain read index over the
same keys, and a legacy sparse unique index is rebuilt at schema sync.
Claude-Session: https://claude.ai/code/session_01ADHkmRc2jLWPKqPfVHStXw
Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ADHkmRc2jLWPKqPfVHStXw Co-authored-by: Claude <noreply@anthropic.com>
📓 Docs Drift Check11 anchor(s) derived from 1 changed package(s); no hand-written page names any of them, so this run has nothing to list — not a clean bill of health. This check sees only pages that NAME a derived anchor: one that documents this change in prose, or enumerates it in an authoring dialect, names none and stays invisible to it on every run. What this run could not see
Coarse fallback — 7 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 4016a895adfcbd052f2866c70eeb470cd744403d && git checkout 4016a895adfcbd052f2866c70eeb470cd744403d
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 2f7977cd2f25d878f31942dae6e229af9ff316d3 e38ab2275eac32187c122276ad6652f69840a199 && git checkout -B drift-repro 2f7977cd2f25d878f31942dae6e229af9ff316d3 && git merge --no-ff e38ab2275eac32187c122276ad6652f69840a199
node scripts/docs-audit/affected-docs.mjs --json 2f7977cd2f25d878f31942dae6e229af9ff316d3 |
|
domain:server#1 · os-steve · session_01ADHkmQjPiXgNoSaEpqeGvY Contract-review-claim: session_01ADHkmQjPiXgNoSaEpqeGvY · head e38ab22 · 2026-11-02T12:24Z |
|
domain:server#1 · os-steve · session_01ADHkmQjPiXgNoSaEpqeGvY Contract reviewServed-tier: Inputs: card #29278 body and all six comments (triage 6575398009, claims 6575831164 / 6575878708, hold 6576235761 and its correction 6576319221, os-dev-report 6577003677); PR #29339 body, file list (3 files: ① Derived judgmentsGates (check-runs on the head): 48 check-runs, all completed: 35
② Semver levelThe changeset ③ Boundary flagsDev deviations (os-dev-report 6577003677):
Card history: hold 6576235761 was withdrawn by 6576319221 (the #5499 freeze was lifted for Follow-ups for the seat, all non-blocking: OQ1's spec card; one assertion that Implemented-by: VERDICT: PASS |
|
domain:server#1 · os-steve · session_01ADHkmQjPiXgNoSaEpqeGvY 席位核对 · ACCEPT ·
|
| item | reading |
|---|---|
| Shape | Draft, base main, Fixes #29278. 3 files: driver-mongodb/src/mongodb-schema.ts, one new test file, and a changeset (@objectstack/driver-mongodb: patch, Clause-②: yes (widening), Metadata-protocol: none). No packages/spec/**. Not governed (check-governed-merges governed: false). |
| Rule | Field-level and declared unique indexes are partial over every non-null BSON type, with no sparse, so two null or missing values are both admitted, as on driver-sql and driver-memory. A non-null duplicate, '' included, is still refused with E11000. Each unique index gets a plain read index idx_FIELDS. A legacy sparse index of exactly the old shape is rebuilt at the next sync. |
| Evidence | Measured on a real mongod 8.3.7: base has 8 red, head is 15/15, the driver-mongodb suite passes 911/911, and 3 ablations went red and then green again. CI on this head: 48 runs, 35 green, 13 skipped, none red. check-expected-skips OK (13, all in main's roster). The real-mongod tests run in no CI lane (#5517 standing). The 7 DDL pins are the CI copy. |
| Open questions | OQ2 is A: keep the read index. OQ3 is A: keep the drop-then-create rebuild. OQ1, the shared NULL-distinct unique conformance case-set in packages/spec/src/data, is outside this claim; the seat routes it to the spec lane separately. It does not block. |
| Should-fix, not filed | ① A first-sync assertion that idx_code exists beside the legacy sparse index is unpinned; the next sync self-heals. ② An idx_a_b name collision between a field literally named a_b and a declared plain index over [a, b] is contrived. ③ Deprecated BSON types (undefined, symbol, …) are no longer constrained, but the driver cannot write them. None of these has a user-visible cost that passes the filing gate. The next PR that touches mongodb-schema.ts should add pin ①. |
| Landing | 「按照 pm-dispatch 规则复核过的都授权」 (Leehom, 2026-10-25T11:35Z): ready and auto-merge through the relay. |
Requested by Steve · project thread
Fixes #29278
Clause-②: yes (widening)
Metadata-protocol: none
维护者速读
null当成一个值:两条唯一字段为空(null或缺失)的记录都能保存,和 SQL、内存驱动一致;真正的重复值(含'')照旧报E11000。sparse,只跳过“没有这个字段”的文档,显式null仍进索引,所以第二条清空唯一字段的记录被拒。已用真实 mongod 8.3.7 在主干上复现。packages/drivers/driver-mongodb/src/mongodb-schema.ts的nullDistinctUniqueOps与rebuildLegacySparseUnique;src/mongodb-unique-null-distinct.test.ts。pnpm --filter @objectstack/driver-mongodb exec vitest run src/mongodb-unique-null-distinct.test.ts,默认 7 个 DDL 测试绿、8 个真实 mongod 测试跳过;加OS_TEST_MONGODB_MEMORY_SERVER_ENABLED=1且能拿到 mongod 时 15 个全绿(主干上 8 红)。What changes
syncCollectionSchemabuilt a field-leveluniqueand a declaredindexes[]entry carryinguniqueas{ unique: true, sparse: true }. Both are now{ unique: true, partialFilterExpression: { FIELD: { $type: [every non-null BSON type] } } }, one entry per key part, with nosparse(MongoDB refusessparsebeside a partial filter). A document with anullor missing value in any key part is not constrained; every other value is constrained exactly as before.$ne/$notinside a partial filter ({ $exists: true, $ne: null }→CannotCreateIndex, code 67, measured).find({ code: 'X' })→COLLSCANon the partial index,EXPRESS_IXSCANon the old sparse one; a single$type: 'string'filter is not used either). So each unique index also getsidx_FIELDS, a plain index over the same keys (the name a declared plain index over those columns already gets, so they converge). A plain index already present under another name (a lookup'sidx_FIELD_lookup) answersIndexOptionsConflict(85), which the loop already skips. An author-named unique index that already takes theidx_FIELDSname gets no read index.indexes[]unique entries are in this fix, not left on the old shape. A single-column declaration and a field-leveluniqueconverge on one index name (idx_FIELD_unique, pinned inmongodb-schema-declared-indexes.test.ts); leaving the declared route sparse would ask for one name with two option sets. Multi-column: anullin ANY key part exempts the row, the rulememory-unique-constraint.tsstates for driver-sql and driver-memory.IndexKeySpecsConflict(86) on 8.3.7, andcollModcannot changesparse/partialFilterExpression. On that conflict the loop reads the collection's indexes; when the same-name index is exactly the legacy shape this driver built (unique: true,sparse: true, same keys in the same order, no partial filter) it is dropped and created again under its own name. Measured on a real server: a collection seeded with the legacy index, anullrow and an'X'row refuses a secondnull(E11000) before the sync; aftersyncSchemathe index carries the partial filter and nosparse, a secondnullis admitted, a second'X'is still refused, and a second sync is a no-op.E11000, which is thrown (the sync fails loudly, the field is not left unconstrained). The read index is created first, so lookups stay indexed. A concurrent sync's drop of an already-dropped index (IndexNotFound, 27) is ignored.packages/spec, any error code. A non-null duplicate is refused with the server's ownE11000 duplicate key error(code 11000), as before.Tests
No existing test was edited. One new file,
packages/drivers/driver-mongodb/src/mongodb-unique-null-distinct.test.ts, two suites:Db(7 tests, runs on every lane): the field-level index options (partial filter, nosparse); the read index created before the unique one; the declared two-column filter over both parts; the author-named collision; the legacy rebuild sequencecreateIndex → dropIndex → createIndex; and two controls where a same-name index the driver did not build (extracollation; other keys) is not dropped and the86still throws.OS_TEST_MONGODB_MEMORY_SERVER_ENABLED=1, driver-mongodb 测试:两个套件并发下载 MongoDB 二进制,mongodb-memory-server 的 rename 竞态让全绿测试 exit 1(队列 flaky) #5517): twonullcreates admitted; two updates clearing tonulladmitted; two missing admitted; a non-null duplicate refused11000with message startingE11000 duplicate key error; two''refused; declared(region, tag):(eu, null)twice admitted,(eu, t)twice refused; a lookup by the unique field is not aCOLLSCAN; the legacy-index migration.Red on main, green on head (real mongod 8.3.7)
mongodb-schema.tsrestored to276ca307in the tree only, the new file run, then restored to HEAD (git diff HEADempty, status clean). The suites importsrc/directly (nodist/in the path).276ca307Tests 8 failed, 7 passed (15).admits two records whose unique field is null:expected 11000 to be 'ok'; the migration test:expected true to be undefined(sparsestill set). The 7 that pass on base are the ones that must: missing ×2 admitted, non-null and''duplicates refused, the lookup index, the author-named case, the two leave-alone controls.84fb196dTests 15 passed (15), no suite skippedPremise probe on base, raw client against the same server (
{ f: 1 }index): sparse unique: twonull→ secondE11000; two missing → bothok; two'', two'x',1and1.0, two equal dates, twotrue→ secondE11000. The partial index answers the same row for every case except twonull(bothok).Ablations of the negative pins
Each mutation was made with
scripts/ablation-replace.mjs(anchor 1 → 0, blob changed, then restored with blob equal to HEAD andgit diff HEADempty). No build leg: the suite readssrc/.unique: falsestill refuses a non-null duplicate:expected undefined to be 11000,''refused,(eu, t)refused, the migration's'X'refusalserves a lookup … not a collection scan:expected '{"isCached":false,"stage":"COLLSCAN",…' not to contain 'COLLSCAN'Acceptance notes
The same case on all three drivers, measured (head
84fb196d, builtdist, each driver's ownsyncSchema+create, fieldcodeunique: 'global', declared(region, tag)unique):codenull ×2codemissing ×2code''×2code'X'×2(eu, null)×2(eu, t)×2On base, mongo answered
ok, refusedfor bothnullrows.No shared conformance case-set was added. The case-sets live in
packages/spec/src/data/*-conformance.ts, which this lane does not edit. The table above is the cross-driver reading; a shareduniquecase-set is an open question for the spec seat.check:driver-conformance: 66 covered, 0 DEBT, 0 exempt, on base and head (unchanged, as expected with no new case-set).The real-server suite runs on no CI lane (opt-in since driver-mongodb 测试:两个套件并发下载 MongoDB 二进制,mongodb-memory-server 的 rename 竞态让全绿测试 exit 1(队列 flaky) #5517). The 7 DDL tests are the ones CI runs. This PR's real-server readings were taken with a MongoDB 8.3.7
mongodfrom conda-forge (mongodb-8.3.7-hc064ac0_0.conda, sha256 matching conda-forge's index) supplied tomongodb-memory-serverthroughMONGOMS_SYSTEM_BINARY, becausefastdl.mongodb.orgis refused in the card container.Write cost. Each unique index now has a plain read index beside it, so a write to a unique field updates two indexes instead of one.
''still collides, as on driver-sql and driver-memory:''is a value. PR fix(objectql): a cleared optional unique text field stores null, so the second record cleared is no longer refused 409 UNIQUE_VIOLATION (#29176) #29271 (open) makes the engine store a cleared optional unique text field asnull; with this PR, Mongo admits those too.Verification
Suites, typecheck, lint, gates
pnpm --filter @objectstack/driver-mongodb testwith the real mongod84fb196d84fb196dpnpm --filter @objectstack/driver-mongodb typechecke38ab227check:test-typecheck0 debtpnpm exec eslint --no-inline-config packages/drivers/driver-mongodbe38ab227turbo run build --filter='./packages/**'(gate prerequisite)e38ab227dispatch-gates.mjs --commands(60 families), each rune38ab227--ran: 60 derived, 60 run, 0 NOT-MEASURED, 0 UNRUNOne family first exited 3 (prerequisite, nothing measured):
check-plugin-teardown-shape --self-testneeded its pinned fixture commit fetched; aftergit fetch --depth=1 origin 621a4876…it exited 0.origin/mainmoved 27 commits past the base276ca307while this ran; none touchpackages/driversorpackages/spec/src/data, so the branch was not merged.Not run locally: the full dogfood battery (no
!in the title, no(narrowing)arm).Generated by Claude Code