Skip to content

Commit d210e4c

Browse files
authored
fix(todos): preserve storage compatibility on ordinary updates (#8902)
Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent 42483ac commit d210e4c

2 files changed

Lines changed: 79 additions & 10 deletions

File tree

‎loopx/control_plane/coordination/coordination_projection.ts‎

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,16 @@ function historicalTodoContracts(
122122
return contracts;
123123
}
124124

125+
function usesFieldsOutsideTodoContract(
126+
records: readonly JsonObject[],
127+
contract: HistoricalTodoContract,
128+
): boolean {
129+
for (const field of contract.absentFields) {
130+
if (records.some((record) => field in record)) return true;
131+
}
132+
return false;
133+
}
134+
125135
function sortedIds(values: Iterable<string>): string[] {
126136
return [...values].sort(authorityUnicodeCompare);
127137
}
@@ -181,13 +191,13 @@ export function validateCoordinationTodoReadModel(
181191
value: JsonObject,
182192
expectedGoalId: string,
183193
): JsonObject {
184-
return validateIndexedTodoReadModel(value, indexCoordinationProjectionTodos(value, expectedGoalId));
194+
return validateIndexedTodoReadModel(value, indexCoordinationProjectionTodos(value, expectedGoalId)).readModel;
185195
}
186196

187197
function validateIndexedTodoReadModel(
188198
value: JsonObject,
189199
index: CoordinationTodoProjectionIndex,
190-
): JsonObject {
200+
): { readModel: JsonObject; historicalContract: HistoricalTodoContract | undefined } {
191201
const records = index.todo_ids.map((todoId) => index.todos.get(todoId)!);
192202
// Identity indexing already validates/copies every record and rejects duplicate
193203
// IDs. The insertion order of those same records proves order; serializing
@@ -222,14 +232,13 @@ function validateIndexedTodoReadModel(
222232
if (!currentContract && historicalContract === undefined) {
223233
throw new AuthorityStoreProtocolError("coordination Todo read-model field contract mismatch");
224234
}
225-
if (historicalContract !== undefined &&
226-
records.some((record) => [...historicalContract.absentFields].some((field) => field in record))) {
235+
if (historicalContract !== undefined && usesFieldsOutsideTodoContract(records, historicalContract)) {
227236
throw new AuthorityStoreProtocolError("coordination Todo record exceeds its historical field contract");
228237
}
229238
for (const [recordIndex, record] of records.entries()) {
230239
canonicalTodoRecord(record, `coordination Todo read record ${recordIndex}`);
231240
}
232-
return readModel;
241+
return { readModel, historicalContract };
233242
}
234243

235244
function requireCompleteTodoReplacement(
@@ -361,7 +370,7 @@ export class CoordinationProjectionRead {
361370
}
362371

363372
validateTodoReadModel(): JsonObject {
364-
return validateIndexedTodoReadModel(this.head, this.todoIndex);
373+
return validateIndexedTodoReadModel(this.head, this.todoIndex).readModel;
365374
}
366375
}
367376

@@ -380,8 +389,8 @@ export function reduceCoordinationProjection(
380389
throw new AuthorityStoreProtocolError("coordination projection mutation batch is empty");
381390
}
382391
const current = indexCoordinationProjection(value, expectedGoalId);
383-
const readModel = value.todo_read_model === undefined
384-
? undefined : validateCoordinationTodoReadModel(value, expectedGoalId);
392+
const previous = value.todo_read_model === undefined
393+
? undefined : validateIndexedTodoReadModel(value, current);
385394
const todos = new Map(current.todos);
386395
const leases = new Map(current.leases);
387396
const mutatedRecords = new Set<string>();
@@ -415,13 +424,20 @@ export function reduceCoordinationProjection(
415424
}
416425
}
417426
const nextTodos = sortedIds(todos.keys()).map((todoId) => todos.get(todoId)!);
427+
const readModel = previous && coordinationTodoReadModel(nextTodos, previous.readModel.schema_version);
428+
const historicalContract = previous?.historicalContract;
429+
// Ordinary writes should keep a released declaration readable by its
430+
// original consumer. A write that uses newer fields needs the current one.
431+
if (readModel && historicalContract && !usesFieldsOutsideTodoContract(nextTodos, historicalContract)) {
432+
readModel.contract_fields = [...historicalContract.fields];
433+
}
418434
const reduced = canonicalAuthorityObject({
419435
...value,
420436
todos: nextTodos,
421437
leases: sortedIds(leases.keys()).map((todoId) => leases.get(todoId)!),
422438
...(readModel === undefined
423439
? {}
424-
: { todo_read_model: coordinationTodoReadModel(nextTodos, readModel.schema_version) }),
440+
: { todo_read_model: readModel }),
425441
}, "coordination projection");
426442
if (value.todo_read_model !== undefined) {
427443
validateCoordinationTodoReadModel(reduced, expectedGoalId);

‎tests/control_plane_ts/coordination_projection.test.ts‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -417,7 +417,9 @@ for (const native of [false, true]) {
417417
const commit = prepareCoordinationProjectionCommit({goal_id: head.goal_id,
418418
operation_id: "next-mutation", expected_provider_revision: initial.provider_revision,
419419
projection: reopened.head, mutations: [{kind: "todo_upsert", todo: changed}]});
420-
assert.deepEqual(commit.next_projection.todo_read_model, coordinationTodoReadModel([changed], schema));
420+
assert.deepEqual(commit.next_projection.todo_read_model, {
421+
...head.todo_read_model, records_sha256: canonicalAuthoritySha256([changed]),
422+
}, "an ordinary edit must keep the exact persisted field declaration");
421423
assert.equal((await store.commitAuthority(commit)).status, "applied");
422424
const updated = await listLocalCoordinationTodos(request, {createStore});
423425
assert.equal(updated.status, "loaded");
@@ -489,6 +491,10 @@ for (const native of [false, true]) {
489491
// fixture and its registered additions, independently of today's field list.
490492
const preReceiptFields = [...previousReleaseFields];
491493
preReceiptFields.splice(preReceiptFields.indexOf("completion_turn_key") + 1, 0, "completion_result");
494+
const releasedBeforeScopedMonitors = [...preReceiptFields];
495+
releasedBeforeScopedMonitors.splice(
496+
releasedBeforeScopedMonitors.indexOf("completion_recovery") + 1, 0, "completion_receipt_id",
497+
);
492498
for (const native of [false, true]) {
493499
test(`pre-receipt ${native ? "domain" : "canonical"} head remains readable and upgrades on commit`, () => {
494500
const fields = preReceiptFields.filter(field =>
@@ -516,6 +522,53 @@ for (const native of [false, true]) {
516522
});
517523
}
518524

525+
for (const native of [false, true]) {
526+
test(`released ${native ? "domain" : "canonical"} manifest changes only when the mutation uses a newer field`, () => {
527+
const fields = releasedBeforeScopedMonitors.filter(field =>
528+
!native || !historicalFields.projection_metadata_fields.includes(field));
529+
const schema = native ? TODO_DOMAIN_READ_RECORD_SCHEMA : TODO_CANONICAL_READ_RECORD_SCHEMA;
530+
const monitor: JsonObject = {
531+
schema_version: native ? TODO_DOMAIN_ITEM_SCHEMA : "todo_item_v0",
532+
todo_id: "todo_monitor", role: "agent", status: "open", done: false,
533+
text: "Observe the assigned run", archive_state: "active",
534+
task_class: "continuous_monitor",
535+
...(native ? {} : {source_section: "Agent Todo"}),
536+
};
537+
const head = {
538+
goal_id: "monitor-goal", todos: [monitor], leases: [],
539+
todo_read_model: {
540+
schema_version: schema, contract_fields: fields, todo_count: 1,
541+
records_sha256: canonicalAuthoritySha256([monitor]),
542+
},
543+
};
544+
const noteEdit = {...monitor, note: "Keep the existing watch"};
545+
const edited = reduceCoordinationProjection(head, head.goal_id, [{kind: "todo_upsert", todo: noteEdit}]);
546+
assert.deepEqual(edited.todo_read_model, {
547+
...head.todo_read_model, records_sha256: canonicalAuthoritySha256([noteEdit]),
548+
});
549+
550+
const observation = {
551+
...noteEdit, material_change_scope: "case-a/run-1",
552+
// The Monitor persists a scope digest, generation, and result digest.
553+
material_change_scope_generations: "95866d27011023fae340614c:1:cb27aee87af9e0125c0766d8",
554+
};
555+
const observed = reduceCoordinationProjection(edited, head.goal_id, [{kind: "todo_upsert", todo: observation}]);
556+
const model = validateCoordinationTodoReadModel(observed, head.goal_id);
557+
assert.deepEqual(observed.todos, [observation]);
558+
assert.deepEqual(model.contract_fields, [
559+
...fields.slice(0, fields.indexOf("material_change_generation") + 1),
560+
"material_change_scope", "material_change_scope_generations",
561+
...fields.slice(fields.indexOf("material_change_generation") + 1),
562+
]);
563+
const cleared = reduceCoordinationProjection(observed, head.goal_id, [{
564+
kind: "todo_upsert", todo: noteEdit,
565+
clear_fields: ["material_change_scope", "material_change_scope_generations"],
566+
}]);
567+
assert.deepEqual(validateCoordinationTodoReadModel(cleared, head.goal_id).contract_fields, model.contract_fields,
568+
"once committed, a newer field declaration does not downgrade implicitly");
569+
});
570+
}
571+
519572
for (const native of [false, true]) {
520573
test(`read-model order uses unique Unicode identities without weakening ${native ? "domain" : "canonical"} content validation`, () => {
521574
// U+E000 precedes U+10000 in persisted Unicode code-point order, but not

0 commit comments

Comments
 (0)