Uh oh!
There was an error while loading. Please reload this page.
fix(driver-mongodb): refuse an unrecognised aggregate function instead of answering it as a silent SUM - #13076
Conversation
…d of answering it as a silent SUM
The `default` arm of `buildAccumulator` answered ANY function name this
driver does not lower with `{ $sum: fieldRef ?? 0 }` — a sum of the column
under the caller's alias, with no error, no envelope and no log. Refuse it
instead, with the two-class ADR-0112 envelope both SQL faces already answer
with: INVALID_QUERY/400 for a name the Query Protocol does not declare,
NOT_IMPLEMENTED/501 for a declared name this backend does not lower.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LZbWd2jNV1FErXTPSS4Dry…ions Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LZbWd2jNV1FErXTPSS4Dry
…gg/string_agg divergence Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LZbWd2jNV1FErXTPSS4Dry
📓 Docs Drift CheckThis PR changes 1 package(s): 5 hand-written doc(s) NAME something this change touched and may need an implementation-accuracy re-verification:
⛔ 2 release-owned page(s) also name something this change touched. These are read-only:
What this run could not see
Coarse fallback — 6 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 b7bf8cd2cf44e1ad6d50a7c28783c9b951ad5617 && git checkout b7bf8cd2cf44e1ad6d50a7c28783c9b951ad5617
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin e6fd1caf7b2454cdd332cef488308efc1196d83e 19f89da392db793f954003eed3c8d737a917754f && git checkout -B drift-repro e6fd1caf7b2454cdd332cef488308efc1196d83e && git merge --no-ff 19f89da392db793f954003eed3c8d737a917754f
node scripts/docs-audit/affected-docs.mjs --json e6fd1caf7b2454cdd332cef488308efc1196d83e
|
os-zhuang
commented
Aug 29, 2026
⛔ Clause-② gate: this PR must not be flipped ready, enqueued, or auto-merged until Posting the gate here because the label could not be written to this PR from the dispatching seat — Why the gate fires: the dev self-assessed Clause-② as yes against the actual diff, and that reads right — previously-resolving inputs now throw, so the accept/reject face moves. Why the dispatching seat cannot clear it: machine-read, not self-declared — Below tier ⇒ ⛔ not eligible to review or clear. A ⇒ For a reviewer at tier: the implementation review is on #12818 and finds nothing outstanding — the contract increment to judge is the two-class #5907 refusal ( Generated by Claude Code |
os-zhuang
commented
Aug 29, 2026
|
Uh oh!
There was an error while loading. Please reload this page.
's landed refusal Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LZbWd2jNV1FErXTPSS4Dry
…changed Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LZbWd2jNV1FErXTPSS4Dry
Fixes#12818
buildAccumulator'sswitchonagg.functionended withdefault: return { $sum: fieldRef ?? 0 }, so any name this driver does not lower — a typo, a miscased spelling, a function added to the contract but not to this file, an unnarrowedmethodfromStrategyContext.executeAggregate— was answered as a sum of that column, under the alias the caller asked for. No error, no envelope, no log.Measured on
origin/main@cd1348802, without a server:{ function: 'median', field: 'score', alias: 'm' }built{ $group: { _id: null, m: { $sum: '$score' } } }and answeredm: 210overAGGREGATION_ROWS. The field-less spelling was quieter still —{ $sum: 0 }, i.e.0, which reads as "no matching rows".The decision, and why (a) beats (b)
The card offered two remedies. This PR takes (a) — refuse at the lowering site — and does not take (b).
(b) — narrow
AggregationInput.functionto the declared union — does not close the hole it names. Three measurements, not three opinions:MongoDBDriver.aggregatereads its aggregations as(query as any).aggregations || (query as any).aggregate || []. A narrowed field onAggregationInputtherefore meets no value at this driver's own call site — the cast erases it, which is exactly howgroupByreached this file as"[object Object]"under a declared union ([finding][drivers] driver-mongodb cannot take a structuredGroupByNodeat all — the object stringifies into a"[object Object]"$group._id #6850).mongodb-aggregation.tsis an exported module of a published package. A JavaScript caller, or one on the far side of anyany, hands the builder whatever string it likes andtscis not present at that moment at all.array_aggandstring_aggleftAggregationFunctionat [spec] AggregationFunction 声明 8 个,SQL 族只实现 5 个 —— count_distinct / array_agg / string_agg 按 ADR-0049 enforce-or-remove 定去留 #6188, so narrowing the field makes their twocasearms a type error — (b) silently drags in a second accept-face change (see the divergence section below) as a side effect of a type annotation.A door that cannot be reached by the values it governs looks shut and is not. So
functionstaysstringdeliberately, with the reasoning in its docblock, and the enforcement is a runtime refusal. Note the two are not rivals in principle — (b) is a fine thing for the upstream declaration to become (#12776 owns that half and is untouched here); what (b) cannot be is this driver's enforcement.And the refusal is what the rest of this file already does. One seam over, a
groupByentry carrying a granularity this driver cannot bucket is REFUSED rather than grouped by the raw instant, and a per-aggregationfilterit cannot lower is REFUSED rather than accumulated unfiltered (#10576). Aggregation function and groupBy entry are the two halves of one lowering, and until this PR they disagreed about what to do with a shape the driver does not model.Refined against the card: it is the TWO-CLASS refusal, not one 501
The dispatch framed (a) as "NOT_IMPLEMENTED-shaped". Taking that literally would be wrong for the card's own repro.
medianis not a capability gap in this backend — the Query Protocol has no such function, so no backend can run it, and answering 501 tells a dashboard author that our backend is missing something when in fact their query is. That is the line #5907 spent a whole issue drawing on the SQL faces, and this PR reproduces it rather than re-litigating it:median,COUNT_DISTINCT)INVALID_QUERYNOT_IMPLEMENTEDClass 2 is empty today — every member of
AggregationFunctionlowers here — and is pinned as a positive assertion rather than left to be rediscovered, so the day the spec grows a function this driver misses, the suite goes red. Its producer is kept deliberately for the same reasondriver-sqlkeeps its unreachable twin: it is not an unenforced declaration, it is the classifier that decides which of two truths the first function of a later spec bump is told.First sentences are byte-identical to
driver-sql's anddriver-turso's (#5240 — one condition, one wording), so a caller cannot tell which backend answered from the words it used. Judged case-sensitively, which is what the enum is.Clause ② self-assessment, against the actual diff
It fires, and
needs:contract-reviewis correct. The diff changes the driver's accept/reject face: inputs that previously resolved to a pipeline now throw. Stated precisely, so the review has the real boundary rather than a label:agg.functionvalue outside the eight namesbuildAccumulatorlowers. Every one of them was previously answered as a SUM of the named column (or0with nofield).packages/specis untouched; the declared vocabulary is read (AggregationFunction.options), never restated, so this driver cannot drift from it.AggregationInput.functionkeeps its declared type (string), on purpose.Environment limit — declared, not worked around
This fleet cannot run a real
mongod: no daemon on the box, no image path, andmongodb-memory-server's ~123 MB download is refused by the egress proxy (#5517 — the real-server suites in this package have been opt-in ever since; this run reported 5 files / 143 tests skipped on exactly that gate).mongodb-pipeline-evaluator.testkit.tscomputes from them — a strict in-process reader modelled from the MongoDB manual, which refuses every shape it does not model rather than tolerating it.buildAggregationPipelinebefore a stage reaches a server, so it is one of the few claims here a live server could not tell us more about. The positive controls are the half that carries the bound.Verification
Union re-run at the final head
19f89da39, after the last commit.pnpm --filter @objectstack/driver-mongodb test— 21 files passed, 5 skipped; 484 tests passed, 143 skipped (the skips are the real-mongod suites above).pnpm --filter @objectstack/driver-mongodb typecheck— clean.mongodb-unrecognised-aggregate-function.test.ts— 21 passed.node scripts/pm/dispatch-gates.mjs --repo objectstack-ai/objectstack(not from a recalled list): 25 gates run locally, all exit 0 — includingcheck:driver-conformance,check:cross-package-test-inputs,check:test-source-alias,check:engine-double-contract,check:where-matcher,check:query-options-erasure,check:nul-bytes, and the changeset family.check:type-check-debt(the ratchet) — refused to run on an unbuilt worktree, so the closure was built exactly aslint.ymldoes; it then reported "31 ledger entries re-measured, 1570 raw tsc errors total, none above its recorded number."The pin is in the REFUSING direction, and it has a positive control
A recognised function must still work, so "it refused" can never be read as "aggregation broke". In the same suite:
count(*)=6,count(stage)=4,sum(score)=210,avg=35,min=10,max=60, and groupedregionanswerswest 4/100, east 2/110. The refusal cases and the controls sit oneitapart over the same fixture.Every case asserts
codeandstatus, never merely "it threw" — and the reason is the inverse of the trapdriver-sql's twin records. There, the un-fixed driver already threw anonymously, sotoThrow()was permanently green. Here the un-fixed builder does not throw at all, so a baretoThrow()catches today's defect and goes blind the moment somebody swaps the ADR-0112 envelope for a bareError.Ablation — direction predicted before it was run
Predicted: restore
default: return { $sum: fieldRef ?? 0 };and change nothing else, and every refusal case fails through the helper's "expected the builder to refuse, but it returned a pipeline" branch, not on an absentcode— the opposite direction fromdriver-sql's ablation of the same class — while the controls stay green.Measured: 11 failed / 10 passed of 21. Every one of the 11 failed exactly as predicted (
Error: expected the builder to refuse "median", but it returned a pipeline, and the multi-entry case onexpected undefined to be defined); not one failed on a missingcode. The 10 green are the controls, the class-2 emptiness pins and the divergence pins.Mutation and restore, both proven on disk rather than by an exit code:
536941d3= worktree hash before mutating (a tree at HEAD, verified, not assumed);1 → 0, silent-SUM arm0 → 1; blob hash moved536941d3 → 89036572. Had either count or the hash not moved, the run aborts as "this ablation did not run";git checkout HEAD -- ABSOLUTE_PATH(absolute, and namingHEADso the index cannot serve back the mutation), under anEXIT INT TERMtrap;536941d3equals the HEAD blob,git diff HEADempty,git status --porcelainempty, anchors back at1 / 0. Byte-identical, not merely "same insertion count".No
distleg, stated rather than assumed: the suite imports./mongodb-aggregation.jsrelatively, so vitest transforms this source file directly and nothing resolves through the package's built output. The dependency closure was built beforehand for the@objectstack/specvalue import.Readings that are NOT measurements, said plainly
tsconfig.jsonexcludes**/*.test.ts(pre-existing, and the@objectstack/driver-mongodbTEST_DEBT note already records it), sopnpm typechecksays nothing about the new test file. Measured with--listFiles: the source file appears once, the test file zero times. Rather than claim green over unread source, I built the tests-included program by hand: the new file is in it (positive control: an existing sibling test is too), it contributes 0 errors, and the package still totals exactly the 10 its ledger records.pnpm lintis CI's run and was not taken here. The declared narrowing: this repo runs oneeslint.config.mjswhich never enables type-aware linting for any file (noparserOptions.project, no typed rules — the config says so in its own comment, with a planted-error measurement behind it), so this diff cannot move any untouched file's verdict;--format jsonover the two changed files reports 2 files, 0 errors, 0 warnings.scripts/check-test-completeness.mjsneeds a turbo test log argument and could not be driven locally — NOT MEASURED, not a red gate.return { $sum: fieldRef ?? 0 };now occurs 0 times in the file, withfieldRefstill occurring 11 times and the legitimate{ $sum: 1 }lowering still occurring once — so the zero is the arm's removal, not a mis-typed pattern.Changeset — graded
patch, argued.changeset/khaki-donuts-refuse.mdgrades this patch, deliberately rather than by default:sumstill sums.filterrefusal — a native face that began answeringNOT_IMPLEMENTED/501 where it had silently aggregated the wrong rows — shipped as a Patch Change in@objectstack/driver-mongodb@17.2.0.majorwould misdescribe it. Nothing an author can write is removed or renamed, no spec key is retired, and there is no FROM → TO migration to carry: a caller reaching the olddefaultarm was reading a SUM in place of the function it asked for, and now gets that function named back at it.Boundaries respected
StrategyContext.executeAggregatedeclaresaggregations[].methodasstringwhile the engine contract declares the six-valueAggregationFunction#12776 (StrategyContext.executeAggregatedeclaringmethodasstring) is why an unrecognised name can reach this driver and is deliberately out of scope — that card is not addressed by this PR and stays open. Even once it narrows, a driver that lowers fewer functions than its contract declares should say so rather than substitute one.sum/avgboolean-aggregand repair for driver-mongodb lowersavg/sumover a boolean column tonull/0— the same cell as #11065, one driver over #11151 in this sameswitch; this PR is thedefaultarm, one arm over, and stands alone.packages/drivers/driver-mongodb/src/**and.changeset/only — nodocs/adr/**, no.claude/**, noskills/**, noAGENTS.md, noCLAUDE.md, and nothing undercontent/docs/releases/.Out-of-scope finding, filed rather than ridden in
#13075 —
driver-mongodbstill lowersarray_aggandstring_agg, retired fromAggregationFunctionat #6188 and refused as undeclared names (400) by both SQL faces today. That divergence pre-dates this change; removing the two arms would be a second accept-face narrowing with its own changeset, and it would falsify an existingstring_aggexpectation that must be INVERTED in place rather than re-baselined. This PR keeps both arms working, byte-identically, and pins them as current behaviour in the new suite so their absence from the refusal roster reads as a measured property rather than an oversight. The refusal messages deliberately offer only the intersection of "lowered here" and "declared", because a remedy naming a retired spelling is a remedy the protocol door rejects.Generated by Claude Code