Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

fix(work-view): save request groups in batches so reviews over 512 records stop failing (#6753)

AJ Greene7f3e8a24ee0
diff --git a/src/services/work-view/shared-ledger-adapter.mjs b/src/services/work-view/shared-ledger-adapter.mjs
index 0ff42bba5..bf009e934 100644
--- a/src/services/work-view/shared-ledger-adapter.mjs
+++ b/src/services/work-view/shared-ledger-adapter.mjs
@@ -6,7 +6,7 @@ import { activitySignature, buildAgentView, readAgentRecords } from './agent-vie
import { reduceWorkState } from './work-state-reduce.mjs';
import { buildSharedProjectionUpdates, applySharedProjection, decorateSharedView, isSharedProjectionValue } from './shared-projection.mjs';
import { createSharedRecordReader, publishSharedRecords } from './shared-record-store.mjs';
-import { sharedRecordKey, sharedValueHash, sharedWorkListSql } from './shared-records.mjs';
+import { SHARED_WORK_MAX_UPDATES, sharedRecordKey, sharedValueHash, sharedWorkListSql } from './shared-records.mjs';
import { canonicalJson } from '../sync/CanonicalContent.js';
import { redactJsonStrings } from '../../utils/redaction.js';
import { isTransientSqliteBusy } from '../worker/db-init-retry.js';
@@ -58,6 +58,66 @@ function rawWrite(path, value) {
function removeFile(path) { try { unlinkSync(path); } catch (error) { if (error.code !== 'ENOENT') throw error; } }
+/**
+ * Split one save's changes into publish batches of at most `size` so that no prefix of whole batches claims a
+ * conversation for two groups. A replica applies a batch once its commit row arrives, and a sync page (500 ops) can end
+ * between two batches of one save, so it can hold the first batches until its next pull. A group change that takes a
+ * conversation therefore goes after the change that gives it up (a deleted or shrunk group), and changes that take from
+ * each other (a swap) form one unit that is not split across batches (strongly connected components, Tarjan). Only a
+ * unit larger than `size` is split.
+ */
+function membershipSafeBatches(changes, shared, size) {
+ if (changes.length <= size) return [changes];
+ const membersOf = record => record && !record.deleted && Array.isArray(record.value?.members) ? record.value.members : [];
+ const giver = new Map();
+ const taken = changes.map(change => {
+ if (change.kind !== 'group') return [];
+ const before = new Set(membersOf(shared.records.get(sharedRecordKey('group', change.key))));
+ const after = new Set(change.deleted ? [] : change.value?.members ?? []);
+ return { before, after };
+ }).map((claims, index) => {
+ if (!claims.before) return [];
+ for (const member of claims.before) if (!claims.after.has(member)) giver.set(member, index);
+ return [...claims.after].filter(member => !claims.before.has(member));
+ });
+ // Each change's prerequisites: the changes that give up a conversation it takes.
+ const edges = taken.map(members => [...new Set(members.filter(member => giver.has(member)).map(member => giver.get(member)))]);
+ // Tarjan emits a component after every component it reaches, so prerequisites come first.
+ const order = changes.map(() => -1), low = [], onStack = [], stack = [], units = [];
+ let counter = 0;
+ const visit = node => { order[node] = low[node] = counter++; stack.push(node); onStack[node] = true; };
+ for (let root = 0; root < changes.length; root++) {
+ if (order[root] !== -1) continue;
+ visit(root);
+ const work = [[root, 0]];
+ while (work.length) {
+ const frame = work.at(-1), node = frame[0];
+ if (frame[1] < edges[node].length) {
+ const target = edges[node][frame[1]++];
+ if (order[target] === -1) { visit(target); work.push([target, 0]); }
+ else if (onStack[target]) low[node] = Math.min(low[node], order[target]);
+ continue;
+ }
+ work.pop();
+ if (work.length) low[work.at(-1)[0]] = Math.min(low[work.at(-1)[0]], low[node]);
+ if (low[node] !== order[node]) continue;
+ const unit = [];
+ let member;
+ do { member = stack.pop(); onStack[member] = false; unit.push(member); } while (member !== node);
+ units.push(unit.sort((a, b) => a - b));
+ }
+ }
+ const batches = [[]];
+ for (const unit of units) {
+ if (batches.at(-1).length + unit.length > size) batches.push([]);
+ for (const index of unit) {
+ if (batches.at(-1).length === size) batches.push([]);
+ batches.at(-1).push(changes[index]);
+ }
+ }
+ return batches.filter(batch => batch.length);
+}
+
/**
* Local files are compatibility caches. Their observed/base hashes and pending
* writes live in SQLite, so a crash between database commit and rename cannot
@@ -244,9 +304,19 @@ export class SharedLedgerAdapter {
if (!Object.hasOwn(prior.bases, key) && existing
&& sharedValueHash(change.kind, change.key, change.value, change.deleted) === (existing.valueHash ?? existing.hash)) change.expectedHash = existing.hash;
}
- const result = publishSharedRecords(this.db, { deviceId: this.deviceId, project: this.project, updates: changes, validateValue: isSharedProjectionValue, reader: this.sharedReader(), readState: shared });
+ // One publish takes at most SHARED_WORK_MAX_UPDATES records, and request-groups.json alone can hold more
+ // (every group and every ignored conversation is a record). Publish it in batches inside this transaction, so a
+ // refusal in any batch still saves nothing. Only the first batch can pass readState: it must be read with nothing
+ // written since, so each later batch reads again; its records' expectedHash still holds the bases read above.
+ // A replica can apply the first batches before the rest, so they are ordered to never claim a conversation twice.
+ const reader = this.sharedReader();
+ let published = 0;
+ for (const [index, batch] of membershipSafeBatches(changes, shared, SHARED_WORK_MAX_UPDATES).entries()) {
+ published += publishSharedRecords(this.db, { deviceId: this.deviceId, project: this.project,
+ updates: batch, validateValue: isSharedProjectionValue, reader, ...(index === 0 ? { readState: shared } : {}) }).changed;
+ }
this.remember(name, value, updates, this.shared(), true, value === null);
- if (result.changed) changed = { rules: changes.some(change => change.kind === 'story') };
+ if (published) changed = { rules: changes.some(change => change.kind === 'story') };
}).immediate(); }
catch (error) {
if (!isTransientSqliteBusy(error)) throw error;
@@ -390,8 +460,8 @@ export class SharedLedgerAdapter {
throw new Error('Shared My Work has a conflicting decision; retained the previous complete state');
}
const safe = updates;
- for (let offset = 0; offset < safe.length; offset += 512) {
- changed += publishSharedRecords(this.db, { deviceId: this.deviceId, project: this.project, updates: safe.slice(offset, offset + 512), validateValue: isSharedProjectionValue, reader: this.sharedReader() }).changed;
+ for (let offset = 0; offset < safe.length; offset += SHARED_WORK_MAX_UPDATES) {
+ changed += publishSharedRecords(this.db, { deviceId: this.deviceId, project: this.project, updates: safe.slice(offset, offset + SHARED_WORK_MAX_UPDATES), validateValue: isSharedProjectionValue, reader: this.sharedReader() }).changed;
}
if (changed) this.notify({ rules: safe.some(update => update.kind === 'story') });
if (changed) this.lastSignature = null;
diff --git a/tests/worker/work-view/shared-ledger-adapter.test.ts b/tests/worker/work-view/shared-ledger-adapter.test.ts
index ac7feabeb..f6371034f 100644
--- a/tests/worker/work-view/shared-ledger-adapter.test.ts
+++ b/tests/worker/work-view/shared-ledger-adapter.test.ts
@@ -39,8 +39,8 @@ function groups(...ids: string[]) {
}
const state = (f: ReturnType<typeof fixture>) => readSharedRecords(f.store.db, { deviceId: f.deviceId, validateValue: isSharedProjectionValue });
const count = (f: ReturnType<typeof fixture>) => (f.store.db.query('SELECT COUNT(*) AS count FROM work_state_entries').get() as { count: number }).count;
-function replicate(from: ReturnType<typeof fixture>, to: ReturnType<typeof fixture>) {
- const rows = from.store.db.query('SELECT * FROM work_state_entries WHERE origin_device_id IS NULL ORDER BY id').all() as any[];
+function replicate(from: ReturnType<typeof fixture>, to: ReturnType<typeof fixture>, throughId = Number.MAX_SAFE_INTEGER) {
+ const rows = from.store.db.query('SELECT * FROM work_state_entries WHERE origin_device_id IS NULL AND id <= ? ORDER BY id').all(throughId) as any[];
const apply = new SyncApply(to.store.db, { deviceId: to.deviceId });
const cursor = Number(apply.getCursor());
const wires = rows.map((row, i) => ({ seq: String(cursor + i + 1), ...buildContentOperation({ kind: 'work_state', originDeviceId: from.deviceId,
@@ -484,3 +484,87 @@ test('a replica that owns no activity does not rebuild the agent view on every p
expect(viewBuilds).toBe(1);
expect([...state(f).records.values()].find(record => record.kind === 'provenance')?.value).toMatchObject({ session: { content_session_id: 'pulled-session' } });
});
+
+// One publish takes at most 512 records, and request-groups.json writes one per group and per ignored conversation.
+const ids = (n: number) => Array.from({ length: n }, (_, i) => `c${String(i).padStart(4, '0')}`);
+function bigLedger(groupCount: number, ignoredCount = 0) {
+ const ledger = groups(...ids(groupCount));
+ ledger.ignored = Object.fromEntries(Array.from({ length: ignoredCount }, (_, i) =>
+ [key(`ignored-${i}`), 'Not a human goal']));
+ return ledger;
+}
+
+for (const [groupCount, ignoredCount] of [[512, 0], [513, 0], [600, 337]]) {
+ test(`request-groups.json with ${groupCount} groups and ${ignoredCount} ignored saves every record`, () => {
+ const f = fixture();
+ const ledger = bigLedger(groupCount, ignoredCount);
+ expect(f.adapter.updatesForFile('request-groups.json', ledger).length).toBe(groupCount + ignoredCount);
+ f.adapter.saveFile('request-groups.json', ledger);
+ const records = [...state(f).records.values()];
+ expect(records.filter(record => record.kind === 'group' && !record.deleted).length).toBe(groupCount);
+ expect(records.filter(record => record.kind === 'ignored' && !record.deleted).length).toBe(ignoredCount);
+ expect(Object.keys(readLedger(f.directory).groups.groups).length).toBe(groupCount);
+ // Saving the same file again changes nothing.
+ const before = count(f);
+ f.adapter.saveFile('request-groups.json', readLedger(f.directory).groups);
+ expect(count(f)).toBe(before);
+ });
+}
+
+test('a refusal in a later batch of a large request-groups.json saves nothing', () => {
+ const f = fixture();
+ const ledger = bigLedger(600);
+ const updates = f.adapter.updatesForFile('request-groups.json', ledger);
+ const last = updates.at(-1)!.key;
+ // The last record lands in the second batch; refuse it there.
+ f.store.db.run(`CREATE TEMP TRIGGER refuse_last BEFORE INSERT ON work_state_entries
+ WHEN instr(NEW.fields, '${last}') > 0 BEGIN SELECT RAISE(ABORT, 'refused in a later batch'); END`);
+ const before = count(f);
+ expect(() => f.adapter.saveFile('request-groups.json', ledger)).toThrow('refused in a later batch');
+ expect(count(f)).toBe(before);
+ expect(state(f).records.size).toBe(0);
+ expect(existsSync(join(f.directory, 'request-groups.json'))).toBe(false);
+});
+
+// A replica applies each batch once its commit row arrives, and a sync page (500 ops) can end between two batches of one
+// save. Every prefix of whole batches must be a state without a membership conflict.
+test('a replica that pulled only the first batches of a large regrouping sees no membership conflict', () => {
+ const f = fixture();
+ const ledger = bigLedger(600);
+ for (const id of ids(600)) ledger.conversations[key(`x${id}`)] = groupIdFor(key(id));
+ f.adapter.saveFile('request-groups.json', ledger);
+ const order = f.adapter.updatesForFile('request-groups.json', ledger).map(update => update.key);
+ const anchorOf = (group: string) => ledger.groups[group].anchor;
+ const extraOf = (group: string) => key(`x${JSON.parse(anchorOf(group))[2]}`);
+ const next = structuredClone(ledger);
+ // A deleted group's conversations join a group in the first batch.
+ const removed = order.at(-1)!;
+ for (const member of [anchorOf(removed), extraOf(removed)]) next.conversations[member] = order[0];
+ delete next.groups[removed];
+ // Two groups in different batches swap a conversation.
+ next.conversations[extraOf(order[1])] = order[597];
+ next.conversations[extraOf(order[597])] = order[1];
+ // A chain: one group gives a conversation to a group in the first batch and takes one from another.
+ next.conversations[extraOf(order[596])] = order[2];
+ next.conversations[extraOf(order[3])] = order[596];
+ // An unrelated change in the last batch, so the save stays more than one batch.
+ next.groups[order[595]].title = 'Renamed';
+ const lastRow = (f.store.db.query('SELECT MAX(id) AS id FROM work_state_entries').get() as { id: number }).id;
+ f.adapter.saveFile('request-groups.json', next);
+ const commits = (f.store.db.query(`SELECT id FROM work_state_entries WHERE id > ? AND list_name = '__my_work_v1:commit' ORDER BY id`)
+ .all(lastRow) as Array<{ id: number }>).map(row => row.id);
+ expect(commits.length).toBeGreaterThan(1);
+ for (const through of commits) {
+ const replica = fixture('device-b');
+ replicate(f, replica, through);
+ expect([...replica.adapter.conflictedKeys(state(replica))]).toEqual([]);
+ }
+ const replica = fixture('device-b');
+ replicate(f, replica);
+ const groupsOf = new Map([...state(replica).records.values()].filter(record => record.kind === 'group' && !record.deleted)
+ .map(record => [record.key, (record.value as { members: string[] }).members]));
+ expect(groupsOf.has(removed)).toBe(false);
+ expect(groupsOf.get(order[0])).toContain(anchorOf(removed));
+ expect(groupsOf.get(order[1])).toContain(extraOf(order[597]));
+ expect(groupsOf.get(order[2])).toContain(extraOf(order[596]));
+});