Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(sync): #6712 PR 4b lane C origin-native cursor rows on the pass

garrytanaaf38638d419
diff --git a/test/persistence-sync-origin-native.test.ts b/test/persistence-sync-origin-native.test.ts
index 2dbe417e00..a0b8de2f80 100644
--- a/test/persistence-sync-origin-native.test.ts
+++ b/test/persistence-sync-origin-native.test.ts
@@ -6,10 +6,14 @@
* on a page no sync import recorded, asks for the brain host and writes nothing; deleting a filename no page claims is not
* a candidate (no request, the live or tombstoned page unchanged; a tombstone whose file is still present is held
* file_drift deleted/tombstone_edited); a committed or working-tree deletion of a page no sync import recorded is held
- * file_drift deleted/file_gone and the page stays live. The cursor-only tests (frozen manifests, resumed and legacy
- * cursors, hand-built cursor intents) still pin the cursor engine.
+ * file_drift deleted/file_gone and the page stays live. A native root spelling keeps the registered owner and resumes the
+ * one pass row; a pass's deletion publication revalidates a recreated file, activation, the configured root and the
+ * origin after preparation, under the request id it was admitted with. An older binary's unfinished cursor (what its
+ * frozen manifest and admitted deletion leave behind) is retired by the pass: a frozen deletion of a present file is never
+ * admitted, an admitted one is cancelled under its original id with its intent unchanged, an origin-less page is never
+ * deleted by slug, and a legacy deletion request with no manifest still fails closed at preparation.
*/
-import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { afterAll, afterEach, beforeAll, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';
@@ -23,13 +27,14 @@ import { importFromContent } from '../src/core/import-file.ts';
import { serializePageToMarkdown } from '../src/core/markdown.ts';
import { resolveSlugForPath } from '../src/core/sync.ts';
import { claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { managedSyncAuthority } from '../src/core/persistence/sync-authority.ts';
+import { passRequestId } from '../src/core/persistence/sync-pass-batch.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
import { performManagedSync } from '../src/core/persistence/sync-run.ts';
import { prepareManagedSyncMutation, type SyncIntent } from '../src/core/persistence/sync-prepare.ts';
import { assertDistinctSyncOrigins, syncOriginPath } from '../src/core/persistence/sync-origin.ts';
import { assertConfiguredSyncRoot, resolveManagedSyncContext } from '../src/core/persistence/sync-discovery.ts';
-import { admitWrite, claimNextWrite, getWriteRequest } from '../src/core/persistence/journal.ts';
-import { localHostId } from '../src/core/persistence/identity.ts';
-import { publishMutation } from '../src/core/persistence/coordinator.ts';
+import { admitWrite, getWriteRequest } from '../src/core/persistence/journal.ts';
import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
import { computeSyncDelta } from '../src/core/sync-delta.ts';
@@ -38,7 +43,6 @@ import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { prepareRemoteJob, withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';
import { readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
-import { interruptAfterSyncDiscovery } from './helpers/persistence-sync-interruption.ts';
import { makeGitFixture } from './helpers/git-fixture.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -56,6 +60,7 @@ afterAll(async () => {
for (const store of stores) { await disposePersistenceConsumer(store.engine); await store.close(); }
rmSync(home, { recursive: true, force: true });
});
+afterEach(() => installFaultHook(undefined));
const check = (name: string, run: (engine: BrainEngine) => Promise<void>) => test(name, () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
for (const { engine } of stores) await run(engine);
}), 120_000);
@@ -77,27 +82,41 @@ async function fixture(engine: BrainEngine, sourcePath = 'notes/example.md', slu
return { id, root, head, slug, snapshot, opts: { ...options, sourceId: id, repoPath: root } };
}
+/**
+ * #6712 PR 4b: what an older binary's unfinished cursor left for this source: a cursor row and its frozen manifest naming the
+ * deletion of notes/example.md, and (when `admitted`) that deletion admitted as the cursor's pending request with a legacy
+ * intent (no `working`, no `passId`). A non-company source no longer writes a cursor, so the rows are written as it wrote them.
+ */
async function legacyDeletion(engine: BrainEngine, f: Awaited<ReturnType<typeof fixture>>, admitted: boolean) {
- expect((await interruptAfterSyncDiscovery(engine, f.opts)).status).toBe('partial');
- const [stored] = await engine.executeRaw<{ fingerprint: string; completed_keys: any[] }>(
- "SELECT fingerprint,completed_keys FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id]);
- const cursor = stored.completed_keys[0];
+ const context = await resolveManagedSyncContext(engine, f.opts);
+ const authority = await managedSyncAuthority(engine, f.id, context.incarnation, context.root);
+ const binding = { ...context.binding, owner_epoch: String(context.binding.owner_epoch), topology_generation: String(context.binding.topology_generation) };
+ const key = `legacy-${randomUUID()}`, runId = randomUUID();
+ const target = execFileSync('git', ['-C', f.root, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
const entry = { path: 'notes/example.md', sourcePath: f.snapshot.page.source_path!, action: 'delete', working: false,
slug: f.slug, pageId: f.snapshot.page.id, revision: f.snapshot.revision };
+ const cursor: Record<string, any> = { binding, root: context.root, gitRoot: context.gitRoot, sourceId: f.id, incarnation: context.incarnation, from: null, target,
+ slugMode: 'git-root', discoveredAt: new Date().toISOString(), runId, index: 0, total: 1, authority,
+ processingOptions: { noEmbed: true, noExtract: true, noSchemaPack: true }, counts: { added: 0, modified: 0, deleted: 0, chunks: 0 },
+ syncOptions: { full: true, workingTree: false, srcSubpath: null, exclude: [], includeHidden: [], strategy: null } };
const intent: SyncIntent = { kind: 'managed_sync_delete', expected_revision: f.snapshot.revision,
sourcePath: entry.sourcePath, path: entry.path, rawHash: sha256(content), content: null,
- ownerEpoch: String(cursor.binding.owner_epoch), syncAuthority: cursor.authority, cursorKey: stored.fingerprint,
- runId: cursor.runId, index: 0, total: 1, from: cursor.from, target: cursor.target, slugMode: cursor.slugMode };
+ ownerEpoch: binding.owner_epoch, syncAuthority: authority, cursorKey: key,
+ runId, index: 0, total: 1, from: null, target, slugMode: 'git-root' };
const requestId = randomUUID();
- const next = { ...cursor, total: 1, ...(admitted ? { pending: { requestId, slug: f.slug, pageId: f.snapshot.page.id, intent } } : {}) };
- await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=$2::text::jsonb WHERE op='managed-sync-manifest' AND fingerprint=$1", [cursor.runId, JSON.stringify([entry])]);
- await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=$2::text::jsonb WHERE op='managed-sync' AND fingerprint=$1", [stored.fingerprint, JSON.stringify([next])]);
+ if (admitted) cursor.pending = { requestId, slug: f.slug, pageId: f.snapshot.page.id, intent };
+ await engine.executeRaw('INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,$3::text::jsonb,now())', ['managed-sync', key, JSON.stringify([cursor])]);
+ await engine.executeRaw('INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,$3::text::jsonb,now())', ['managed-sync-manifest', runId, JSON.stringify([entry])]);
if (admitted) await admitWrite(engine, { requestId, operation: 'submit_job', sourceId: f.id,
- sourceIncarnation: cursor.incarnation, slug: f.slug, pageId: f.snapshot.page.id, worktreeId: cursor.binding.worktree_id,
- topologyGeneration: cursor.binding.topology_generation, principal: cursor.authority.writer.principal,
- authority: cursor.authority.writer, callerIntent: intent, intent });
- return { requestId, intent, cursor, entry };
+ sourceIncarnation: context.incarnation, slug: f.slug, pageId: f.snapshot.page.id, worktreeId: binding.worktree_id,
+ topologyGeneration: binding.topology_generation, principal: authority.writer.principal,
+ authority: authority.writer, callerIntent: intent, intent });
+ return { requestId, intent, cursor: cursor as { runId: string; authority: typeof authority }, entry, key };
}
+const legacyRows = (engine: BrainEngine, legacy: Awaited<ReturnType<typeof legacyDeletion>>) => engine.executeRaw<{ op: string }>(
+ "SELECT op FROM op_checkpoints WHERE (op='managed-sync' AND fingerprint=$1) OR (op='managed-sync-manifest' AND fingerprint=$2)", [legacy.key, legacy.cursor.runId]);
+const deleteRequests = (engine: BrainEngine, id: string) => engine.executeRaw<{ request_id: string; state: string; error_code: string | null }>(
+ "SELECT request_id::text AS request_id, state, error_code FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_delete' ORDER BY sequence", [id]);
test('origin comparison is Windows-specific and never case-folds POSIX identity', () => {
expect(syncOriginPath('notes\\example.md', 'win32')).toBe('notes/example.md');
@@ -124,9 +143,13 @@ test('configured sync roots still refuse unrelated directories and replaced regi
expect(() => assertConfiguredSyncRoot(root, other)).toThrow('configured source directory');
});
-check('native root spellings retain the registered owner and resume the same sync cursor', async engine => {
+// #6712 PR 4b: the pass keeps one row per source incarnation (no cursor to resume). A pass interrupted part way and resumed
+// under the native spelling of the root keeps that one row, admits every request under the registered owner, and leaves
+// the binding as it was: no second worktree or owner.
+check('native root spellings retain the registered owner and resume the same pass row', async engine => {
for (const legacy of [false, true]) {
- const f = await fixture(engine);
+ const f = await fixture(engine, 'notes/example.md', 'notes/example', { 'notes/example.md': content,
+ 'notes/second.md': 'A second synthetic observation.\n', 'notes/third.md': 'A third synthetic observation.\n' });
if (legacy) {
const binding = (await getWorktreeBinding(engine, f.id))!;
await engine.transaction(async tx => {
@@ -145,22 +168,27 @@ check('native root spellings retain the registered owner and resume the same syn
expect(realpathSync(f.root)).not.toBe(binding.local_path);
}
expect(await resolveManagedSyncContext(engine, { ...f.opts, repoPath: nativeRoot })).toEqual(context);
- expect((await interruptAfterSyncDiscovery(engine, f.opts)).status).toBe('partial');
- const before = await engine.executeRaw<{ fingerprint: string; completed_keys: Array<Record<string, unknown>> }>(
- "SELECT fingerprint,completed_keys FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id]);
- expect(before).toHaveLength(1);
+ const passRows = () => engine.executeRaw<{ fingerprint: string; value: { source_id: string; incarnation: string; telemetry: { pass_id: string; outcome: string } } }>(
+ "SELECT fingerprint, completed_keys->0 AS value FROM op_checkpoints WHERE op='managed-sync-pass' AND completed_keys->0->>'source_id'=$1", [f.id]);
+ const partial = await performManagedSync(engine, f.opts, { maxPages: 1, maxMs: 1000 });
+ expect(partial).toMatchObject({ status: 'partial', reason: 'writer_yield', pass: { outcome: 'resumable' } });
+ const before = await passRows();
+ expect(before.map(row => row.fingerprint)).toEqual([`${f.id}:${context.incarnation}`]);
expect(await performManagedSync(engine, { ...f.opts, repoPath: nativeRoot, dryRun: true })).toMatchObject({ status: 'dry_run' });
- expect(await engine.executeRaw(
- "SELECT fingerprint,completed_keys FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id])).toEqual(before);
- expect(await performManagedSync(engine, f.opts)).toMatchObject({ status: 'first_sync', added: 0, deleted: 0 });
- const after = await engine.executeRaw<{ fingerprint: string; completed_keys: Array<Record<string, unknown>> }>(
- "SELECT fingerprint,completed_keys FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id]);
- expect(after).toHaveLength(1);
- expect(after[0].fingerprint).toBe(before[0].fingerprint);
- for (const key of ['root', 'gitRoot', 'binding', 'authority', 'runId']) {
- expect(after[0].completed_keys[0][key]).toEqual(before[0].completed_keys[0][key]);
- }
+ expect(await passRows()).toEqual(before);
+ const resumed = await performManagedSync(engine, { ...f.opts, repoPath: nativeRoot });
+ expect(resumed).toMatchObject({ status: 'first_sync', deleted: 0, pass: { outcome: 'synced' } });
+ expect(resumed.pass!.pass_id).not.toBe(partial.pass!.pass_id);
+ const after = await passRows();
+ expect(after.map(row => [row.fingerprint, row.value.source_id, row.value.incarnation, row.value.telemetry.pass_id, row.value.telemetry.outcome]))
+ .toEqual([[before[0]!.fingerprint, f.id, context.incarnation, resumed.pass!.pass_id, 'synced']]);
+ const requests = await engine.executeRaw<{ worktree_id: string; owner_epoch: string; kind: string; path: string | null; state: string }>(
+ `SELECT worktree_id::text AS worktree_id, intent->>'ownerEpoch' AS owner_epoch, intent->>'kind' AS kind, intent->>'path' AS path, state
+ FROM persistence_requests WHERE source_id=$1 ORDER BY sequence`, [f.id]);
+ expect(requests.every(row => row.worktree_id === binding.worktree_id && row.owner_epoch === String(binding.owner_epoch) && row.state === 'committed')).toBe(true);
+ expect(requests.filter(row => row.kind === 'managed_sync_import').map(row => row.path).sort()).toEqual(['notes/second.md', 'notes/third.md']);
expect(await getWorktreeBinding(engine, f.id)).toEqual(binding);
+ expect(await engine.executeRaw('SELECT worktree_id FROM persistence_source_bindings WHERE source_id=$1', [f.id])).toHaveLength(1);
expect((await engine.getPage(f.slug, { sourceId: f.id }))?.id).toBe(f.snapshot.page.id);
expect(readFileSync(join(f.root, 'notes/example.md'), 'utf8')).toBe(content);
}
@@ -333,44 +361,6 @@ check('deleting an unowned filename is not a pass candidate and preserves the li
}
});
-check('unowned deletion rechecks absent ownership and file bytes at publication', async engine => {
- for (const change of ['origin', 'file']) {
- const f = await fixture(engine, 'notes/recorded.md', 'notes/example', {
- 'notes/recorded.md': content, 'notes/example.md': content,
- });
- await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () =>
- tx.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [f.id, f.head]), TEST_WRITE_ATTRIBUTION));
- unlinkSync(join(f.root, 'notes/example.md'));
- execFileSync('git', ['-C', f.root, 'add', '-A']);
- execFileSync('git', ['-C', f.root, 'commit', '-qm', 'Remove the unowned duplicate']);
- expect((await interruptAfterSyncDiscovery(engine, { ...f.opts, full: false })).status).toBe('partial');
- const [stored] = await engine.executeRaw<{ fingerprint: string; completed_keys: any[] }>(
- "SELECT fingerprint,completed_keys FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id]);
- const cursor = stored.completed_keys[0], requestId = randomUUID();
- const intent: SyncIntent = { kind: 'managed_sync_delete', expected_revision: f.snapshot.revision,
- sourcePath: 'notes/example.md', path: 'notes/example.md', rawHash: null, content: null, unownedDeletion: true, working: false,
- ownerEpoch: String(cursor.binding.owner_epoch), syncAuthority: cursor.authority, cursorKey: stored.fingerprint,
- runId: cursor.runId, index: 0, total: 1, from: cursor.from, target: cursor.target, slugMode: cursor.slugMode };
- cursor.pending = { requestId, slug: f.slug, pageId: f.snapshot.page.id, intent };
- await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=$2::text::jsonb WHERE op='managed-sync' AND fingerprint=$1",
- [stored.fingerprint, JSON.stringify([cursor])]);
- const accepted = await admitWrite(engine, { requestId, operation: 'submit_job', sourceId: f.id, sourceIncarnation: cursor.incarnation,
- slug: f.slug, pageId: f.snapshot.page.id, worktreeId: cursor.binding.worktree_id, topologyGeneration: cursor.binding.topology_generation,
- principal: cursor.authority.writer.principal, authority: cursor.authority.writer, callerIntent: intent, intent });
- const row = (await claimNextWrite(engine, localHostId()))!;
- expect(row.id).toBe(accepted.id);
- const prepared = await prepareManagedSyncMutation(engine, row, { engine: engine.kind });
- expect(prepared.noop).toBe(true);
- if (change === 'origin') await engine.executeRaw('UPDATE pages SET source_path=$2 WHERE id=$1', [f.snapshot.page.id, 'notes/example.md']);
- else writeFileSync(join(f.root, 'notes/example.md'), content);
- const published = await publishMutation(engine, row, prepared);
- expect(published.state).not.toBe('committed');
- expect(published.error_code).toBe(change === 'origin' ? 'page_identity_changed' : 'source_changed');
- expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))?.revision).toBe(f.snapshot.revision);
- expect((await engine.executeRaw('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(f.head);
- }
-});
-
check('a committed Git deletion of a page no sync import recorded is held file_drift (deleted, file_gone): the page stays live and only the checkpoint commits', async engine => {
const f = await fixture(engine);
await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.executeRaw('UPDATE sources SET last_commit=$2 WHERE id=$1', [f.id, f.head]), TEST_WRITE_ATTRIBUTION));
@@ -401,31 +391,34 @@ check('a committed Git deletion of a page no sync import recorded is held file_d
expect(await engine.getVersions(f.slug, { sourceId: f.id })).toEqual(history);
});
-check('old manifest reuse refuses a present-file deletion before admitting any request', async engine => {
+// #6712 PR 4b: the pass reads no manifest. It retires an older binary's unfinished cursor, so the deletion that cursor froze
+// for a file still in the tree is never admitted: no deletion request, the page as it was, and the source checkpoints HEAD.
+check("an older binary's unfinished cursor freezing a present file's deletion is retired by the pass, which admits no deletion and keeps the page", async engine => {
const f = await fixture(engine, process.platform === 'win32' ? 'notes\\example.md' : 'notes/example.md');
const legacy = await legacyDeletion(engine, f, false);
- await expect(performManagedSync(engine, f.opts)).rejects.toMatchObject({ code: 'page_identity_changed' });
- expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual([]);
- expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))?.revision).toBe(f.snapshot.revision);
- const [manifest] = await engine.executeRaw<{ completed_keys: unknown[] }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [legacy.cursor.runId]);
- expect(manifest.completed_keys).toEqual([legacy.entry]);
- expect((await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBeNull();
- expect((await performManagedSync(engine, { ...f.opts, retryFailed: true })).status).toBe('first_sync');
- expect((await engine.getPage(f.slug, { sourceId: f.id }))?.id).toBe(f.snapshot.page.id);
+ expect(await performManagedSync(engine, f.opts)).toMatchObject({ status: 'first_sync', deleted: 0, pass: { outcome: 'synced' } });
+ expect(await deleteRequests(engine, f.id)).toEqual([]);
+ expect(await engine.readPageSnapshot(f.slug, { sourceId: f.id })).toEqual(f.snapshot);
+ expect(await legacyRows(engine, legacy)).toEqual([]);
+ expect((await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(f.head);
+ expect(readFileSync(join(f.root, 'notes/example.md'), 'utf8')).toBe(content);
});
-check('already-admitted legacy deletion fails under its original ID and the next sync rediscovers', async engine => {
+// #6712 PR 4b: the pass retires the older cursor and cancels its admitted deletion under that request's original id, with the
+// accepted intent unchanged; the pass mints no deletion of its own for the present file, and the next sync stays clean.
+check('an already-admitted legacy deletion is cancelled under its original ID with its intent unchanged; the pass keeps the page and the next sync stays clean', async engine => {
const f = await fixture(engine, process.platform === 'win32' ? 'notes\\example.md' : 'notes/example.md');
const legacy = await legacyDeletion(engine, f, true);
- const first = await performManagedSync(engine, f.opts);
- expect(first).toMatchObject({ status: 'blocked_by_failures', managedWrite: { write_request: { request_id: legacy.requestId } } });
+ expect(await performManagedSync(engine, f.opts)).toMatchObject({ status: 'first_sync', deleted: 0, pass: { outcome: 'synced' } });
const row = (await getWriteRequest(engine, legacy.cursor.authority.writer.principal, legacy.requestId))!;
- expect(row.state).not.toBe('committed');
- expect(row.error_code).toBe('page_identity_changed');
+ expect({ state: row.state, error_code: row.error_code }).toEqual({ state: 'cancelled', error_code: 'cancelled' });
expect(row.intent).toEqual(legacy.intent);
- // #6712 PR 3 (L7): the next plain sync retries the recorded failure by rediscovering, as `--retry-failed` (now its alias) did.
- expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');
- expect((await getWriteRequest(engine, legacy.cursor.authority.writer.principal, legacy.requestId))?.state).toBe(row.state);
+ expect(await deleteRequests(engine, f.id)).toEqual([{ request_id: legacy.requestId, state: 'cancelled', error_code: 'cancelled' }]);
+ expect(await legacyRows(engine, legacy)).toEqual([]);
+ expect(await engine.readPageSnapshot(f.slug, { sourceId: f.id })).toEqual(f.snapshot);
+ expect(['synced', 'up_to_date']).toContain((await performManagedSync(engine, f.opts)).status);
+ expect(await getWriteRequest(engine, legacy.cursor.authority.writer.principal, legacy.requestId)).toEqual(row);
+ expect(await deleteRequests(engine, f.id)).toHaveLength(1);
expect((await engine.getPage(f.slug, { sourceId: f.id }))?.id).toBe(f.snapshot.page.id);
expect(readFileSync(join(f.root, 'notes/example.md'), 'utf8')).toBe(content);
});
@@ -461,8 +454,13 @@ check('native case aliases refuse rather than merge distinct origins', async eng
expect(readFileSync(join(f.root, 'notes/example.md'), 'utf8')).toBe(content);
});
+// #6712 PR 4b: a legacy deletion request an older binary admitted can still reach preparation; with no manifest entry
+// behind it, it fails closed even when the file is gone, and its accepted intent is not rewritten.
check('unknown old deletion manifests fail closed without rewriting accepted request identity', async engine => {
const f = await fixture(engine);
+ unlinkSync(join(f.root, 'notes/example.md'));
+ execFileSync('git', ['-C', f.root, 'add', '-A']);
+ execFileSync('git', ['-C', f.root, 'commit', '-qm', 'Remove the synthetic source file']);
const legacy = await legacyDeletion(engine, f, true);
await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [legacy.cursor.runId]);
const row = (await getWriteRequest(engine, legacy.cursor.authority.writer.principal, legacy.requestId))!;
@@ -472,50 +470,72 @@ check('unknown old deletion manifests fail closed without rewriting accepted req
await engine.executeRaw("UPDATE persistence_requests SET state='cancelled' WHERE id=$1::uuid", [row.id]);
});
-check('an admitted deletion cannot infer a missing page origin from its slug', async engine => {
+// #6712 PR 4b: the pass reads pages by their recorded origin. A synced page whose origin was cleared, and whose file is
+// gone, is no deletion candidate and no hold: it stays live, and an older binary's admitted deletion of it is cancelled with
+// its intent unchanged.
+check('a pass never infers a missing page origin from its slug: the origin-less page stays live and an admitted legacy deletion of it is cancelled unchanged', async engine => {
const f = await fixture(engine);
+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');
unlinkSync(join(f.root, 'notes/example.md'));
execFileSync('git', ['-C', f.root, 'add', '-A']);
execFileSync('git', ['-C', f.root, 'commit', '-qm', 'Remove the synthetic source file']);
await engine.executeRaw('UPDATE pages SET source_path=NULL WHERE id=$1', [f.snapshot.page.id]);
+ const before = (await engine.readPageSnapshot(f.slug, { sourceId: f.id }))!;
const legacy = await legacyDeletion(engine, f, true);
- expect(await performManagedSync(engine, f.opts)).toMatchObject({ status: 'blocked_by_failures',
- managedWrite: { write_error: 'page_identity_changed', write_request: { request_id: legacy.requestId } } });
- expect((await engine.getPage(f.slug, { sourceId: f.id }))?.id).toBe(f.snapshot.page.id);
+ const result = await performManagedSync(engine, { ...f.opts, full: false });
+ expect(result).toMatchObject({ status: 'synced', deleted: 0 });
+ expect(result.held ?? []).toEqual([]);
+ expect(await engine.readPageSnapshot(f.slug, { sourceId: f.id })).toEqual(before);
+ expect(before.page.deleted_at ?? null).toBeNull();
+ expect(await deleteRequests(engine, f.id)).toEqual([{ request_id: legacy.requestId, state: 'cancelled', error_code: 'cancelled' }]);
expect((await getWriteRequest(engine, legacy.cursor.authority.writer.principal, legacy.requestId))?.intent).toEqual(legacy.intent);
});
-check('publication revalidates a recreated working-tree deletion and activation after preparation', async engine => {
- for (const change of ['file', 'activation', 'configured-root', 'origin']) {
+// #6712 PR 4b: a pass's working-tree deletion is re-validated at publication. A change made after the consumer prepared it
+// (the file recreated, the brain deactivated, the configured root moved, the page's origin cleared) refuses it under the
+// request id the pass admitted it with, its intent unchanged; the page keeps its revision and last_commit does not move.
+check("a pass's working-tree deletion publication revalidates a recreated file, activation, the configured root and the origin after preparation", async engine => {
+ for (const change of ['file', 'activation', 'configured-root', 'origin'] as const) {
const f = await fixture(engine);
+ const opts = { ...f.opts, workingTree: true };
+ expect(await performManagedSync(engine, opts)).toMatchObject({ status: 'synced', reason: 'selection_scoped' });
+ const before = (await engine.readPageSnapshot(f.slug, { sourceId: f.id }))!;
unlinkSync(join(f.root, 'notes/example.md'));
- const legacy = await legacyDeletion(engine, f, false);
- const intent = { ...legacy.intent, working: true, rawHash: null };
- const requestId = randomUUID();
- const [cursor] = await engine.executeRaw<{ completed_keys: any[] }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1", [intent.cursorKey]);
- cursor.completed_keys[0].pending = { requestId, slug: f.slug, pageId: f.snapshot.page.id, intent };
- await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=$2::text::jsonb WHERE op='managed-sync' AND fingerprint=$1", [intent.cursorKey, JSON.stringify(cursor.completed_keys)]);
- const admission = { requestId, operation: 'submit_job', sourceId: f.id, sourceIncarnation: legacy.cursor.incarnation,
- slug: f.slug, pageId: f.snapshot.page.id, worktreeId: legacy.cursor.binding.worktree_id, topologyGeneration: legacy.cursor.binding.topology_generation,
- principal: legacy.cursor.authority.writer.principal, authority: legacy.cursor.authority.writer, callerIntent: intent, intent };
- const accepted = await admitWrite(engine, admission);
- const row = (await claimNextWrite(engine, localHostId()))!;
- expect(row.id).toBe(accepted.id);
- const prepared = await prepareManagedSyncMutation(engine, row, { engine: engine.kind });
- if (change === 'file') writeFileSync(join(f.root, 'notes/example.md'), content);
- else if (change === 'activation') await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
- else if (change === 'origin') await engine.executeRaw('UPDATE pages SET source_path=NULL WHERE id=$1', [f.snapshot.page.id]);
- else await engine.transaction(async tx => {
- await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");
- await tx.executeRaw('UPDATE sources SET local_path=$2 WHERE id=$1', [f.id, home]);
+ let prepared: { request_id: string; intent: SyncIntent } | null = null;
+ installFaultHook(async point => {
+ if (point !== 'consumer:prepared' || prepared) return;
+ const [running] = await engine.executeRaw<{ request_id: string; intent: SyncIntent }>(
+ "SELECT request_id::text AS request_id, intent FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_delete' AND state='running'", [f.id]);
+ if (!running) return;
+ prepared = running;
+ if (change === 'file') writeFileSync(join(f.root, 'notes/example.md'), content);
+ else if (change === 'activation') await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ else if (change === 'origin') await engine.executeRaw('UPDATE pages SET source_path=NULL WHERE id=$1', [f.snapshot.page.id]);
+ else await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");
+ await tx.executeRaw('UPDATE sources SET local_path=$2 WHERE id=$1', [f.id, home]);
+ });
});
- const published = await publishMutation(engine, row, prepared);
- expect(published.state).not.toBe('committed');
- expect(published.error_code).toBe(change === 'activation' ? 'writer_coordinator_required' : change === 'origin' ? 'page_identity_changed' : 'source_changed');
- expect((await engine.readPageSnapshot(f.slug, { sourceId: f.id }))?.revision).toBe(f.snapshot.revision);
- expect((await admitWrite(engine, admission)).id).toBe(accepted.id);
- expect((await getWriteRequest(engine, admission.principal, requestId))?.intent).toEqual(intent);
+ let result;
+ try { result = await performManagedSync(engine, opts); }
+ finally { installFaultHook(undefined); await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }
+ expect(prepared).not.toBeNull();
+ const { request_id: requestId, intent } = prepared!;
+ expect(requestId).toBe(passRequestId(intent.passId!, 'notes/example.md', null));
+ const code = change === 'activation' ? 'writer_coordinator_required' : change === 'origin' ? 'page_identity_changed' : 'source_changed';
+ const [published] = await engine.executeRaw<{ state: string; error_code: string | null; intent: SyncIntent }>(
+ 'SELECT state, error_code, intent FROM persistence_requests WHERE source_id=$1 AND request_id=$2::uuid', [f.id, requestId]);
+ expect(published!.state).not.toBe('committed');
+ expect(published!.error_code).toBe(code);
+ expect(published!.intent).toEqual(intent);
+ expect((await deleteRequests(engine, f.id)).map(row => row.request_id)).toEqual([requestId]);
+ const page = await engine.readPageSnapshot(f.slug, { sourceId: f.id, includeDeleted: true });
+ expect(page?.revision).toBe(before.revision);
+ expect(page?.page.deleted_at ?? null).toBeNull();
expect((await engine.executeRaw('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBeNull();
+ // A recreated file is the level moving: the pass passes the refused deletion over and the next round settles the file.
+ if (change === 'file') expect(result).toMatchObject({ status: 'synced', reason: 'selection_scoped', deleted: 0 });
+ else expect(result).toMatchObject({ status: 'blocked_by_failures', deleted: 0, pass: { outcome: 'blocked' } });
}
});