Skip to content

Commit b811f6a

Browse files
fix(objectql): the stored-expression fill judges a row another write moved mid-walk again, instead of counting it as computed (#32917)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9DBuXWhwvpm35T1HHqBk53DP)_ domain:server#8 · os-elon-musk · session_016WV4cygFz7u9NcRqm24ucS Fixes #32732 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:存储计算字段的补算(保存、发布时自动跑,以及 `os migrate stored-expressions --apply`)遇到「补算期间被别的写入改过」的行时,不再默认对方已按新表达式算好;改为重读这一行、按现在生效的定义重新判定:已是正确值就不动,仍欠值就以它的新时间戳条件写入,再被改一次就记入失败并让回执报「未补完」。 - 为什么改:改动这一行的若是尚未生效新定义的另一台节点,或绕过引擎的写入,它根本没按新表达式算;之前这行被跳过并计为「对方已算」,回执可能仍说无需处理,数据却是空值或旧值。 - 风险与回滚:只动补算内部,回执与报告形状不变;被并发改过的行最多多读一次、多写一次,不会循环。回滚即撤销本 PR,回到「被改过就跳过」。 - 先看:`packages/objectql/src/stored-expression-backfill.ts` 的 `fillRowUnlessMovedSince`(重判与二次条件写入)与 `judgeRow`(遍历与重判共用的同一判定);测试文件里五个 `[#32732]` 用例。 - 两分钟验证:`pnpm --filter @objectstack/objectql exec vitest run src/stored-expression-backfill.test.ts -t "32732"`,预期 5 个用例通过:绕过引擎改过的行补成 10、旧定义节点写的 10 被改写成 80、被改两次的行报未补完。 - 需要你做的:无,席位落地。 ## What changes The fill of stored computed fields (`backfillStoredExpressions`: `os migrate stored-expressions --apply`, and the save / publish doors' `fillChanged()`) writes each row only while it still holds the `updated_at` the walk read (PR #32690). When that precondition matched no row, it read the row again and, on another stamp, answered `moved` and counted the row under `concurrentRows`, trusting that the write which moved it had computed the field under the live definition. That holds for an engine write on a node already serving the change. It does not hold for a peer node that has not applied the change yet, or for a write that did not go through the engine: the row kept NULL or the old expression's value, was counted as computed, and the door could still answer `stored-expression-filled`. `packages/objectql/src/stored-expression-backfill.ts` only: - **One predicate for a row, `judgeRow`.** The walk's per-row judgement (hole, stale, faulting field holding a value, a fault on a stored field outside the scope) is lifted out of the loop unchanged, so the walk and the re-check of a moved row judge a row the same way. The walk's counting is unchanged. - **A moved row is judged again (`fillRowUnlessMovedSince`).** On `moved`, the row as re-read is computed again under the definition live now (`computeStoredExpressionsOver`, the walk's own `computePage`) and judged by `judgeRow`: - owes nothing (the moving write stored the value): left alone, counted under `concurrentRows` as before; this is the CONTROL case; - owes a value: its new patch is written under the row's NEW stamp, with the same precondition (`writeUnlessMovedSince`, the conditional write kept under its name). It counts under `written`; a field of the first patch the moving write had already stored counts under `concurrentRows`; - moved again before that write lands, or holding a value a field which does not evaluate there would erase: listed under `failures` with the reason, so `storedExpressionBackfillComplete` is false, the command exits 1 and the door answers `stored-expression-fill-incomplete`. One retry, never a loop. - deleted: counted under `concurrentRows`, as before (nothing left to fill). - **The same-stamp fallback is no longer silent.** A driver whose conditional write never matches the `updated_at` it reads back still gets the unconditional write (unchanged), and the run now warns once per object that the guard is off on that driver. - Docblocks of the module header, `concurrentRows` on both report types and the text report's concurrent line say what the count now means ("read again, hold what the expression computes"). The report shape is unchanged (no member added or removed); `concurrentRows` now counts only rows that, read again, hold the live value. **Changeset (F2).** `.changeset/32732-stored-expression-fill-moved-row.md` (`@objectstack/objectql`: patch) carries the sentence the #32690 changeset lacked: `concurrentRows` is a required member of the exported `StoredExpressionBackfillReport` and `StoredExpressionBackfillFieldOutcome` (and so of the command's `--json` report) since the fill's writes became conditional on the stamp the walk read. ## Tests Five new cases in `packages/objectql/src/stored-expression-backfill.test.ts`, on the real engine and protocol over the in-file door driver whose `updateMany` evaluates the precondition: - a row moved mid-walk by a raw driver write (stamp moved, nothing computed) ends filled with 10 under its new stamp; the notice says `3 rows of 3 written` and nothing about another write; - a row moved mid-walk by a node still serving the OLD expression (stores 10) is rewritten with the new one (80) under its new stamp; - a moved row that moves again before the re-judged write lands keeps its value and stamp, and the save answers `stored-expression-fill-incomplete` with `2 rows written, 1 row not`; - the same through `backfillStoredExpressions` directly: `failures` names the row and why, `storedExpressionBackfillComplete` is false; - a driver whose conditional write never matches: every row written, one warning. CONTROL: the existing #32527 case (an engine write moves the row and computes the field itself) now also asserts the fill wrote nothing over it (one update of that row: the edit's own). The raw writes replace the stored row object instead of mutating it, so a page row the walk already holds keeps the stamp it read; a mutation in place would have handed the fill the new stamp and left the moved path unexercised. ## Acceptance notes Card nits (item 3), each taken or dropped with the reason: - Taken: a row deleted mid-walk is no longer described as "written by another write" in this file (docblocks and the text report say "changed or deleted"); the same-stamp fallback now warns once per object. - Dropped, outside the claimed file surface (the claim: `stored-expression-backfill.ts` and its tests, one changeset): the notice's "1 row ... were not written over" agreement and its "written by another write" wording for a deleted row (`packages/metadata-protocol/src/protocol-stored-expression-fill.ts`); the engine's one-time no-`updateMany` warning (`engine-insert.ts`); the stale comments in `concurrent-update-error.ts` and the `WRITE_PRECONDITION_OPTION` docblock (`engine-top-level.ts`); the `cli.mdx` row. Each is prose only. Also note: a twice-moved row rides the door notice's existing "N rows refused the write" clause (same file), which is loose wording for "moved again"; the failure entry itself names the reason. - `beforeUpdate` hooks run on a write the precondition then refuses (review nit, not in the card's list): unchanged, as for the claim gate. ## Verification Head `67101a94` (after one `git merge origin/main`). - Ablation (the forbidden behaviour put back: every `CONCURRENT_UPDATE` outcome answered `moved` without the re-judgement), via `node scripts/ablation-replace.mjs`, anchor `if (first.kind === 'gone') return { kind: 'moved', fields: Object.keys(patch) };` replaced by `if (first.kind !== 'written') return ...; // ABLATION: trust the moving write` (anchor x1 to x0, marker x1, `grep -c` 1 on disk). The test imports `src/`, so no dist rebuild is involved. <details><summary>ablated run: 4 failed | 45 passed</summary> ``` × [#32732] a row moved mid-walk by a write that did not go through the engine is filled under its new stamp AssertionError: expected undefined to be 10 // Object.is equality × [#32732] a row moved mid-walk by a node still serving the old expression is rewritten with the new one AssertionError: expected 10 to be 80 // Object.is equality × [#32732] a moved row that moves again before the re-judged write lands is reported as left, never as computed Expected: "2099-02-01T00:00:00.000Z" Received: "2099-01-01T00:00:00.000Z" × [#32732] the command reports a twice-moved row as a failure naming why, and the run as incomplete AssertionError: expected { …(16) } to match object { nullRows: 3, writtenRows: 2, …(1) } Tests 4 failed | 45 passed (49) ``` Restored: blob after restore == HEAD blob `d236e2ab9762`, `git diff HEAD` empty. The CONTROL stayed green under the ablation. </details> - `pnpm --filter @objectstack/objectql test`: Test Files 590 passed (590), Tests 12615 passed (12615), lock VERDICT command-exit 0, on `67101a94`. Before the final naming commit the whole package run found one red, `federated-injected-column-readers.test.ts` (the reader ledger keys the conditional write by function name); the conditional write keeps the name `writeUnlessMovedSince` so its ledger row still holds. - `pnpm --filter @objectstack/objectql typecheck`: exit 0 (`tsc --noEmit` and `check:test-typecheck` OK). - `node scripts/pm/dispatch-gates.mjs --commands` (66 families, derived from the merge base) plus `pnpm lint`, run sequentially after a whole-tree `turbo run build`; `--ran` reconciliation: <details><summary>--ran</summary> ``` node scripts/check-adr-0087-registration.mjs --base origin/main :: exit 0 node scripts/check-adr-0087-registration.mjs --self-test :: exit 0 node scripts/check-changeset-no-major.mjs --base origin/main :: exit 0 node scripts/check-closing-keyword-parity.mjs :: exit 0 node scripts/check-closing-keyword-parity.mjs --self-test :: exit 0 node scripts/check-comment-mask-adoption.mjs :: exit 0 node scripts/check-comment-mask-adoption.mjs --self-test :: exit 0 node scripts/check-comment-mask-corpus.mjs :: exit 0 node scripts/check-dts-emitted.mjs --self-test :: exit 0 node scripts/check-empty-changeset.mjs --base origin/main :: exit 0 node scripts/check-empty-changeset.mjs --self-test :: exit 0 node scripts/check-engine-split-ratio.mjs --self-test :: exit 0 node scripts/check-issue-citations.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs --self-test :: exit 0 node scripts/ci/assert-turbo-remote-cache.mjs --self-test :: exit 0 node scripts/ci/plan-test-core-shards.mjs --self-test :: exit 0 node scripts/ci/prune-turbo-cache.mjs --self-test :: exit 0 node scripts/ci/snapshot-next.mjs --self-test :: exit 0 node scripts/docs-audit/check-affected-docs.mjs :: exit 0 node scripts/docs-audit/check-drift-comment.mjs :: exit 0 node scripts/pm/release-rehearsal-clone.mjs --self-test :: exit 0 node scripts/release-pending-publish.mjs --self-test :: exit 0 pnpm --filter @objectstack/spec run check:duration-unit-keys :: exit 0 pnpm --filter @objectstack/spec run check:error-code-provenance :: exit 0 pnpm check:changeset-gate-self-tests :: exit 0 pnpm check:ci-filter-parity :: exit 0 pnpm check:cli-command-ids :: exit 0 pnpm check:closed-ceremony-text :: exit 0 pnpm check:cross-package-test-inputs :: exit 0 pnpm check:dispatcher-error-vocabulary :: exit 0 pnpm check:doc-authoring :: exit 0 pnpm check:driver-memory-census :: exit 0 pnpm check:dts-closure :: exit 0 pnpm check:dual-build-cjs-loads :: exit 0 pnpm check:durability-log-level :: exit 0 pnpm check:engine-double-contract :: exit 0 pnpm check:error-status-conformance :: exit 0 pnpm check:gitlink-declared :: exit 0 pnpm check:issue-citations :: exit 0 pnpm check:keyed-text-bounds :: exit 0 pnpm check:lean-entry-closure :: exit 0 pnpm check:logger-receiver-detach :: exit 0 pnpm check:nul-bytes :: exit 0 pnpm check:object-def-param-keys :: exit 0 pnpm check:objectql-double-limit :: exit 0 pnpm check:optional-error-sink :: exit 0 pnpm check:org-identifier :: exit 0 pnpm check:page-declaration-shape :: exit 0 pnpm check:platform-object-tenancy-census :: exit 0 pnpm check:published-files :: exit 0 pnpm check:query-options-erasure :: exit 0 pnpm check:refd-timer-probe :: exit 0 pnpm check:registry-log-declared :: exit 0 pnpm check:rest-log-spy-declared :: exit 0 pnpm check:slot-lookup :: exit 0 pnpm check:sourcemap-no-sources-content :: exit 0 pnpm check:system-context-census :: exit 0 pnpm check:test-source-alias :: exit 0 pnpm check:tier-file-adoption :: exit 0 pnpm check:type-check-coverage :: exit 0 pnpm check:type-check-debt :: exit 0 pnpm check:undeclared-dep-imports :: exit 0 pnpm check:vouch-for-reference-callers :: exit 0 pnpm check:watch-hint-literal :: exit 0 pnpm check:where-matcher :: exit 0 pnpm lint :: exit 0 dispatch-gates --ran: 66 derived famil(ies) accounted for — 66 run, 0 NOT-MEASURED; pnpm lint outside the derivation, exit 0 ``` </details> - Every family CI runs is read from this PR's check-runs; not re-run locally. --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4cygFz7u9NcRqm24ucS)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent ae9c134 commit b811f6a

3 files changed

Lines changed: 329 additions & 46 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql): the stored-expression fill judges a row another write moved mid-walk again, under the definition live now, instead of counting it as computed
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The fill that `os migrate stored-expressions --apply` runs, and that a save or publish runs when a stored computed field computes something new, writes each row only while it still holds the `updated_at` the walk read. A row another write changed in between was skipped and counted as computed by that write. That holds for an engine write on a node already serving the new definition, and not for a peer node that has not applied the change yet or a write that did not go through the engine: such a row kept a NULL or the old expression's value, and the answer could still say nothing was left. Now the fill reads the moved row again and judges it by the walk's own predicate under the live definition. A row that holds the value is left alone and counted under `concurrentRows`; a row that does not is written under its new stamp, with the same precondition; a row that moves again before that write lands, or that holds a value a field which does not evaluate there would erase, is listed under `failures`, so the save or publish answers `stored-expression-fill-incomplete` and the command exits 1. A driver whose conditional write never matches the stamp it reads back still falls back to an unconditional write, and the run now warns once per object that the guard is off there.
11+
12+
`concurrentRows` is a required member of the exported `StoredExpressionBackfillReport` and `StoredExpressionBackfillFieldOutcome` types (and so of the command's `--json` report) since the fill's writes became conditional on the stamp the walk read; it counts only rows that, read again, hold what the expression computes now, and a row deleted mid-walk is counted there too.

‎packages/objectql/src/stored-expression-backfill.test.ts‎

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -562,6 +562,13 @@ describe('[#32527] the save and publish doors fill a stored computed field the c
562562
const total = async (rig: Awaited<ReturnType<typeof makeRig>>) =>
563563
(await stored(rig)).reduce<number>((n, v) => n + (typeof v === 'number' ? v : 0), 0);
564564
const notices = (res: any, rule: string) => (res.advisories ?? []).filter((a: any) => a.rule === rule);
565+
/**
566+
* [#32732] A write that bypasses the engine: it replaces the stored row (never mutates the object a page read
567+
* handed out) and computes nothing.
568+
*/
569+
const rawWrite = (rig: Awaited<ReturnType<typeof makeRig>>, id: string, data: Record<string, unknown>) => {
570+
rig.storeFor(OBJ).set(id, { ...rig.storeFor(OBJ).get(id)!, ...data });
571+
};
565572

566573
it('the card: a formula turned into a stored number with the same expression — the save fills the rows, the total reads 6', async () => {
567574
const rig = await populated();
@@ -680,6 +687,123 @@ describe('[#32527] the save and publish doors fill a stored computed field the c
680687
const [notice] = notices(res, 'stored-expression-filled');
681688
expect(notice.message).toContain('2 rows of 3 written');
682689
expect(notice.message).toContain('1 row written by another write while the fill ran');
690+
// [#32732] CONTROL: read again, the moved row holds what the live expression computes, so the fill writes nothing over it.
691+
expect(rig.updates.filter((u) => u.id === second)).toHaveLength(1);
692+
});
693+
694+
// [#32732] The write that moves a row mid-walk is not trusted to have computed the field under the live definition.
695+
it('[#32732] a row moved mid-walk by a write that did not go through the engine is filled under its new stamp', async () => {
696+
const rig = await populated();
697+
const [, second] = Array.from(rig.storeFor(OBJ).keys());
698+
const EDITED = '2099-01-01T00:00:00.000Z';
699+
// A raw driver write: it moves the row and its stamp, and computes nothing.
700+
rig.afterFirstPage(async () => {
701+
rawWrite(rig, second!, { end_day: 13, updated_at: EDITED });
702+
});
703+
704+
const res = await rig.save(STORED);
705+
706+
const moved = rig.storeFor(OBJ).get(second!)!;
707+
expect(moved.updated_at).toBe(EDITED);
708+
expect(moved.days).toBe(10);
709+
expect(await stored(rig)).toEqual([1, 10, 3]);
710+
const [notice] = notices(res, 'stored-expression-filled');
711+
expect(notice.message).toContain('3 rows of 3 written');
712+
expect(notice.message).not.toContain('another write');
713+
expect(notices(res, 'stored-expression-fill-incomplete')).toEqual([]);
714+
});
715+
716+
it('[#32732] a row moved mid-walk by a node still serving the old expression is rewritten with the new one', async () => {
717+
const rig = await populated();
718+
await rig.save(STORED);
719+
const [, second] = Array.from(rig.storeFor(OBJ).keys());
720+
const EDITED = '2099-01-01T00:00:00.000Z';
721+
// A peer that has not applied the change yet: its write stores the OLD expression's value (13 - 3).
722+
rig.afterFirstPage(async () => {
723+
rawWrite(rig, second!, { end_day: 13, days: 10, updated_at: EDITED });
724+
});
725+
726+
const res = await rig.save({ type: 'number', expression: cel('(record.end_day - record.start_day) * 8') });
727+
728+
const moved = rig.storeFor(OBJ).get(second!)!;
729+
expect(moved.updated_at).toBe(EDITED);
730+
expect(moved.days).toBe(80);
731+
expect(await stored(rig)).toEqual([8, 80, 24]);
732+
const [notice] = notices(res, 'stored-expression-filled');
733+
expect(notice.message).toContain('3 rows of 3 written');
734+
expect(notice.message).not.toContain('another write');
735+
});
736+
737+
it('[#32732] a moved row that moves again before the re-judged write lands is reported as left, never as computed', async () => {
738+
const rig = await populated();
739+
const [, second] = Array.from(rig.storeFor(OBJ).keys());
740+
const EDITED = '2099-01-01T00:00:00.000Z';
741+
const AGAIN = '2099-02-01T00:00:00.000Z';
742+
rig.afterFirstPage(async () => {
743+
rawWrite(rig, second!, { end_day: 13, updated_at: EDITED });
744+
});
745+
// A second raw write lands just before the fill's write under the new stamp.
746+
const updateMany = rig.driver.updateMany;
747+
rig.driver.updateMany = async function (object: string, ast: any, data: Record<string, unknown>) {
748+
if (object === OBJ && ast?.where?.id === second && ast?.where?.updated_at === EDITED) {
749+
rawWrite(rig, second!, { end_day: 14, updated_at: AGAIN });
750+
}
751+
return updateMany.call(this, object, ast, data);
752+
};
753+
754+
const res = await rig.save(STORED);
755+
756+
const moved = rig.storeFor(OBJ).get(second!)!;
757+
expect(moved.updated_at).toBe(AGAIN);
758+
expect(moved.days ?? null).toBeNull();
759+
expect(notices(res, 'stored-expression-filled')).toEqual([]);
760+
const [warning] = notices(res, 'stored-expression-fill-incomplete');
761+
expect(warning).toMatchObject({ severity: 'warning', path: `objects.${OBJ}.fields.days` });
762+
expect(warning.message).toContain('2 rows written, 1 row not');
763+
});
764+
765+
it('[#32732] the command reports a twice-moved row as a failure naming why, and the run as incomplete', async () => {
766+
const rig = await populated();
767+
await rig.save(STORED);
768+
const [, second] = Array.from(rig.storeFor(OBJ).keys());
769+
for (const row of rig.storeFor(OBJ).values()) row.days = null;
770+
const EDITED = '2099-01-01T00:00:00.000Z';
771+
rig.afterFirstPage(async () => {
772+
rawWrite(rig, second!, { end_day: 13, updated_at: EDITED });
773+
});
774+
const updateMany = rig.driver.updateMany;
775+
rig.driver.updateMany = async function (object: string, ast: any, data: Record<string, unknown>) {
776+
if (object === OBJ && ast?.where?.id === second && ast?.where?.updated_at === EDITED) {
777+
rawWrite(rig, second!, { updated_at: '2099-02-01T00:00:00.000Z' });
778+
}
779+
return updateMany.call(this, object, ast, data);
780+
};
781+
782+
const report = await backfillStoredExpressions(rig.engine as any, quietLogger, { objects: [OBJ], apply: true });
783+
784+
expect(report).toMatchObject({ nullRows: 3, writtenRows: 2, concurrentRows: 0 });
785+
expect(report.fields[0]).toMatchObject({ field: 'days', nullRows: 3, written: 2, concurrentRows: 0 });
786+
expect(report.failures).toEqual([expect.objectContaining({ object: OBJ, recordId: second })]);
787+
expect(report.failures[0].error).toContain('changed the row twice while the fill ran');
788+
expect(storedExpressionBackfillComplete(report)).toBe(false);
789+
});
790+
791+
it('[#32732] a driver whose conditional write never matches its own read stamp is written unconditionally, and said once', async () => {
792+
const rig = await populated();
793+
await rig.save(STORED);
794+
for (const row of rig.storeFor(OBJ).values()) row.days = null;
795+
rig.driver.updateMany = async () => 0;
796+
const warns: string[] = [];
797+
798+
const report = await backfillStoredExpressions(
799+
rig.engine as any,
800+
{ info: () => {}, warn: (msg: string) => { warns.push(msg); } },
801+
{ objects: [OBJ], apply: true },
802+
);
803+
804+
expect(report).toMatchObject({ writtenRows: 3, concurrentRows: 0, failures: [] });
805+
expect(await stored(rig)).toEqual([1, 2, 3]);
806+
expect(warns.filter((w) => w.includes('conditional write did not match'))).toHaveLength(1);
683807
});
684808

685809
it('a refused storage sync is not followed by a fill: no row is written, and each field is reported unfilled', async () => {

0 commit comments

Comments
 (0)