Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(sync): #6712 PR 4b lane C retire the cursor-only rows of persistence-managed-sync

garrytan2b61317ca8db
diff --git a/test/persistence-managed-sync.test.ts b/test/persistence-managed-sync.test.ts
index 49a269514e..ad813ed9c5 100644
--- a/test/persistence-managed-sync.test.ts
+++ b/test/persistence-managed-sync.test.ts
@@ -15,14 +15,12 @@ import { prepareManagedSyncMutation, type SyncIntent } from '../src/core/persist
import { publishMutation } from '../src/core/persistence/coordinator.ts';
import { sha256 } from '../src/core/persistence/digest.ts';
import { performManagedSync } from '../src/core/persistence/sync-run.ts';
-import { recordManagedSyncFailure } from '../src/core/persistence/sync-failures.ts';
import { discoverManagedSync } from '../src/core/persistence/sync-discovery.ts';
import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
import { disposePersistenceConsumer, registerMutationPreparer } from '../src/core/persistence/service.ts';
-import { UNFINISHED_PAGE_REQUEST_SQL, noopWaiversEnabled } from '../src/core/persistence/sync-waivers.ts';
+import { UNFINISHED_PAGE_REQUEST_SQL } from '../src/core/persistence/sync-waivers.ts';
import { waitFor } from './helpers/wait-for.ts';
-import { installFaultHook } from '../src/core/persistence/fault-points.ts';
import { withEnv } from './helpers/with-env.ts';
import { prepareRemoteJob, withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';
import type { OperationContext } from '../src/core/ops/contract.ts';
@@ -249,50 +247,6 @@ test('attached working-tree changes require opt-in and delete retains exact phys
}
}),120_000);
-test('repeated slices reuse one manifest and hold an intervening page identity change instead of rejecting the run', async () => withEnv({ GBRAIN_HOME: home }, async () => {
- for (const engine of engines) {
- const f = await fixture(engine, {
- 'a.md': 'First source observation for a durable sliced import.\n',
- 'b.md': 'Second source observation for a durable sliced import.\n',
- 'c.md': 'Third source observation for a durable sliced import.\n',
- });
- const executeRaw = engine.executeRaw;
- let manifestReads = 0;
- engine.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[]) {
- if (params?.[0] === f.id && sql.includes('SELECT id,slug,source_path,knowledge_revision,deleted_at FROM pages')) manifestReads++;
- return executeRaw.call(this, sql, params);
- } as BrainEngine['executeRaw'];
- try {
- const options = { sourceId: f.id, noPull: true };
- const slice = { maxPages: 1, maxMs: 1000 };
- expect(await performManagedSync(engine, options, slice)).toMatchObject({ status: 'partial', reason: 'writer_yield', filesImported: 1 });
- const [manifest] = await engine.executeRaw<{ fingerprint: string; completed_keys: unknown }>(
- `SELECT m.fingerprint,m.completed_keys FROM op_checkpoints c JOIN op_checkpoints m
- ON m.op='managed-sync-manifest' AND m.fingerprint=c.completed_keys->0->>'runId'
- WHERE c.op='managed-sync' AND c.completed_keys->0->>'sourceId'=$1`, [f.id]);
- expect(manifest).toBeDefined();
- expect(await performManagedSync(engine, options, slice)).toMatchObject({ status: 'partial', reason: 'writer_yield', filesImported: 2 });
- expect(manifestReads).toBe(1);
- await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.putPage('c', {
- type: 'note', title: 'c', compiled_truth: 'A newer accepted page between sync slices.', timeline: '', frontmatter: {}, content_hash: 'newer',
- }, { sourceId: f.id }), TEST_WRITE_ATTRIBUTION));
- // #6340: the page that moved under the manifest is held (`concurrent_write`), the run finishes, and the database version stays.
- const held = await performManagedSync(engine, options, slice);
- expect(held).toMatchObject({ status: 'partial', reason: 'writer_yield', held_count: 1, held: [{ path: 'c.md', code: 'concurrent_write' }] });
- expect(manifestReads).toBe(1);
- expect(await engine.executeRaw('SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2',
- ['managed-sync-manifest', manifest.fingerprint])).toEqual([{ completed_keys: manifest.completed_keys }]);
- expect((await engine.getPage('c', { sourceId: f.id }))?.compiled_truth).toBe('A newer accepted page between sync slices.');
- expect(await engine.executeRaw('SELECT slug,state FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [f.id]))
- .toEqual([{ slug: 'a', state: 'committed' }, { slug: 'b', state: 'committed' }]);
- 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, options, slice)).toMatchObject({ status: 'first_sync', filesImported: 3, held_count: 1 });
- expect((await engine.getPage('c', { sourceId: f.id }))?.compiled_truth).toBe('A newer accepted page between sync slices.');
- expect(loadSyncFailures().filter(row => row.source_id === f.id)).toHaveLength(0);
- } finally { await disposePersistenceConsumer(engine); engine.executeRaw = executeRaw; }
- }
-}),120_000);
-
test('managed discovery unions persisted hidden-path waivers with explicit patterns', async () => withEnv({GBRAIN_HOME:home},async()=>{
for(const engine of engines){
const previous = await engine.getConfig('sync.include_hidden');
@@ -397,7 +351,7 @@ test.each([false, true])('raw bytes changing after preparation conflict without
}
}),120_000);
-test.each([false, true])('managed terminal receipts survive a missing ledger and corrected retry uses a new ID (CRLF=%s)', async crlf =>
+test('managed terminal receipts survive a missing ledger and corrected retry uses a new ID', async () =>
withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
for (const engine of engines) {
// #6340 holds a pinned-worktree conflict by default; `sync.holds=fail` keeps the blocking receipt this test is about.
@@ -409,38 +363,14 @@ test.each([false, true])('managed terminal receipts survive a missing ledger and
const path = join(f.root, 'notes/example.md');
writeFileSync(path, pinned);
const target = commit(f.root);
- const working = crlf ? pinned.replace(/\n/g, '\r\n') : 'A private uncommitted observation that must not appear in diagnostics.\n';
+ const working = 'A private uncommitted observation that must not appear in diagnostics.\n';
writeFileSync(path, working);
const opts = { sourceId: f.id, noPull: true };
- if (crlf) {
- const { entries, ...discovery } = await discoverManagedSync(engine, opts);
- expect(entries).toHaveLength(1);
- const [previous] = await engine.executeRaw<{ fingerprint: string }>(
- "SELECT fingerprint FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1 AND completed_keys->0->>'done'='true'", [f.id]);
- expect(previous).toBeDefined();
- const authority = await managedSyncAuthority(engine, f.id, discovery.incarnation, discovery.root);
- const runId = randomUUID(), requestId = randomUUID(), entry = entries[0];
- const legacyIntent: SyncIntent = { kind: 'managed_sync_import', expected_revision: entry.revision ?? null,
- processingOptions: { noEmbed: false, noExtract: false, noSchemaPack: false },
- sourcePath: entry.sourcePath, path: entry.path, rawHash: sha256(working), content: pinned,
- ownerEpoch: String(discovery.binding.owner_epoch), syncAuthority: authority, cursorKey: previous.fingerprint,
- runId, index: 0, total: entries.length, from: discovery.from, target: discovery.target, slugMode: discovery.slugMode };
- expect(legacyIntent).not.toHaveProperty('lineEndingOnly');
- const legacyCursor = { ...discovery, authority, runId, index: 0, total: entries.length,
- counts: { added: 0, modified: 0, deleted: 0, chunks: 0 },
- pending: { requestId, slug: entry.slug!, pageId: entry.pageId ?? null, intent: legacyIntent } };
- await engine.transaction(async tx => {
- await tx.executeRaw('INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)',
- ['managed-sync-manifest', runId, JSON.stringify(entries)]);
- await tx.executeRaw("UPDATE op_checkpoints SET completed_keys=$2::text::jsonb WHERE op='managed-sync' AND fingerprint=$1",
- [previous.fingerprint, JSON.stringify([legacyCursor])]);
- });
- }
const blocked = await performManagedSync(engine, opts);
expect(blocked).toMatchObject({ status: 'blocked_by_failures', failedFiles: 1, filesImported: 0,
managedWrite: { source_id: f.id, slug: 'notes/example', path: 'notes/example.md', write_error: 'source_changed',
reason: 'pinned_git_worktree_conflict', ledger_recorded: true, write_request: { state: 'conflict', retry_after_ms: null } } });
- expect(blocked.managedWrite?.line_endings).toBe(crlf ? 'crlf_lf_only' : undefined);
+ expect(blocked.managedWrite?.line_endings).toBe(undefined);
expect(JSON.stringify(blocked)).not.toContain(working.trim());
expect(JSON.stringify(blocked)).not.toContain(f.root);
expect(readFileSync(path, 'utf8')).toBe(working);
@@ -636,63 +566,6 @@ test('managed sync still rejects conflicting explicit slugs on extension-bearing
}
}), 120_000);
-test('retry-failed resets cursor when pending write is committed but failure record exists', async () =>
- withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
- for (const engine of engines) {
- await disposePersistenceConsumer(engine);
- const f = await fixture(engine, {
- 'a.md': 'First observation committed during the original sync run.\n',
- 'b.md': 'Second observation not yet imported.\n',
- });
- const abort = new AbortController();
- const partial = await performManagedSync(engine, {
- sourceId: f.id, noPull: true, noEmbed: true, noExtract: false,
- signal: abort.signal,
- onProgress: p => { if (p.phase === 'managed_sync.page_committed') abort.abort(); },
- });
- expect(partial).toMatchObject({ status: 'partial', filesImported: 1 });
- await disposePersistenceConsumer(engine);
-
- // The progress callback fires AFTER cursor advancement. Reconstruct the
- // crash window between the committed write and that cursor update.
- const [row] = await engine.executeRaw<{ fingerprint: string; completed_keys: [{
- runId: string; incarnation: string; index: number;
- counts: { added: number; modified: number; deleted: number; chunks: number };
- pending?: { requestId: string; slug: string; pageId: number | null; intent: SyncIntent };
- }] }>("SELECT fingerprint,completed_keys FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id]);
- const [committed] = await engine.executeRaw<{ request_id: string; slug: string; intent: SyncIntent; state: string }>(
- "SELECT request_id,slug,intent,state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import'", [f.id]);
- expect(committed?.state).toBe('committed');
- expect(committed?.slug).toBe('a');
- const cursor = row.completed_keys[0];
- cursor.index = 0;
- cursor.counts = { added: 0, modified: 0, deleted: 0, chunks: 0 };
- cursor.pending = { requestId: committed.request_id, slug: committed.slug, pageId: null, intent: committed.intent };
- await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=$2::text::jsonb WHERE op='managed-sync' AND fingerprint=$1",
- [row.fingerprint, JSON.stringify([cursor])]);
- expect((await engine.getPage('a', { sourceId: f.id }))?.compiled_truth).toContain('First observation');
- expect(await engine.getPage('b', { sourceId: f.id })).toBeNull();
-
- // #6712 PR 1: a mismatched invocation no longer refuses (the cursor's processing opt-outs are inherited), so the
- // failure an older release recorded against that run on such a refusal is written as that release wrote it.
- await recordManagedSyncFailure(engine, { source_id: f.id, source_incarnation: cursor.incarnation, path: '', code: 'invalid_params',
- message: 'Unfinished sync uses different processing options.', request_id: null, run_id: cursor.runId, target: null,
- cursor_key: row.fingerprint, phase: 'resume', state: 'failed', observation_id: randomUUID() });
- const failuresBefore = await engine.executeRaw(
- "SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1 AND completed_keys->0->>'run_id'=$2", [row.fingerprint, cursor.runId]);
- expect(failuresBefore).toHaveLength(1);
-
- const retried = await performManagedSync(engine, {
- sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, retryFailed: true,
- });
- expect(['first_sync', 'synced']).toContain(retried.status);
- expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toContain('Second observation');
- expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(f.head);
- expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1", [row.fingerprint])).toHaveLength(0);
- await disposePersistenceConsumer(engine);
- }
- }), 120_000);
-
test('managed sync leaves reserved skillpack paths to the skill publisher instead of blocking (#5852)', async () =>
withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
for (const engine of engines) {
@@ -716,8 +589,7 @@ test('managed sync leaves reserved skillpack paths to the skill publisher instea
}
}), 120_000);
-// #5984 (CEO-A12/A32/A34, ENG-A7, DX-A7/A15): a manifest delete of a page that is
-// already soft-deleted at its frozen revision advances without an admission.
+// #5984 / #6712 PR 4b: a synced source whose files are all removed in one commit, the named pages soft-deleted first.
const WAIVER_OPTS = { noPull: true, noEmbed: true, noExtract: true };
async function deletedFixture(engine: BrainEngine, files: Record<string, string>, softDeleted: string[]) {
const f = await fixture(engine, files);
@@ -727,13 +599,10 @@ async function deletedFixture(engine: BrainEngine, files: Record<string, string>
commit(f.root, 'remove every file');
return f;
}
-const runRequests = (engine: BrainEngine, sourceId: string, runId: string) => engine.executeRaw<{ kind: string; slug: string; state: string }>(
- "SELECT intent->>'kind' AS kind,slug,state FROM persistence_requests WHERE source_id=$1 AND intent->>'runId'=$2 ORDER BY sequence", [sourceId, runId]);
const deleteRequests = (engine: BrainEngine, sourceId: string) => engine.executeRaw<{ slug: string; state: string }>(
"SELECT slug,state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_delete' ORDER BY sequence", [sourceId]);
/**
- * Runs `hook` on the `nth` snapshot read of `slug`. The default (2) is a head entry's screen, which re-reads the
- * page after its freeze; an entry frozen for a waiver run is read once (#5984 G3: its screen reuses the freeze's read).
+ * Runs `hook` on the `nth` snapshot read of `slug`. The default (2) is a delete's screen, which re-reads the page the pass classified.
*/
function onScreen(engine: BrainEngine, slug: string, hook: () => Promise<void>, nth = 2): BrainEngine {
let reads = 0;
@@ -768,63 +637,6 @@ test('soft-deleted pages whose files are gone are not pass candidates; only the
}
}), 120_000);
-test('GBRAIN_SYNC_WAIVE_NOOP=0 admits every no-op entry', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_WAIVE_NOOP: '0' }, async () => {
- expect(noopWaiversEnabled()).toBe(false);
- expect(noopWaiversEnabled({})).toBe(true);
- for (const engine of engines) {
- const f = await deletedFixture(engine, { 'a.md': note('First'), 'b.md': note('Second') }, ['a', 'b']);
- const result = await performManagedSync(engine, { sourceId: f.id, ...WAIVER_OPTS });
- expect(result).toMatchObject({ status: 'synced', deleted: 0, waived: { imports: 0, deletes: 0 } });
- expect((await runRequests(engine, f.id, result.runId!)).map(row => row.kind)).toEqual(['managed_sync_delete', 'managed_sync_delete', 'managed_sync_checkpoint']);
- }
-}), 120_000);
-
-test('a restore between freeze and screen is admitted, not waived', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
- for (const engine of engines) {
- const f = await deletedFixture(engine, { 'a.md': note('Restored concurrently') }, ['a']);
- const proxy = onScreen(engine, 'a', () => engine.transaction(tx => withCoordinatedWrite(tx, [f.id], async () => { await tx.restorePage('a', { sourceId: f.id }); }, TEST_WRITE_ATTRIBUTION)));
- try {
- const result = await performManagedSync(proxy, { sourceId: f.id, ...WAIVER_OPTS });
- expect(result.waived).toEqual({ imports: 0, deletes: 0 });
- expect(await deleteRequests(engine, f.id)).toHaveLength(1);
- expect(await engine.getPage('a', { sourceId: f.id })).not.toBeNull();
- } finally { await disposePersistenceConsumer(proxy); rmSync(syncFailuresPath(), { force: true }); }
- }
-}), 120_000);
-
-test.each(['restore', 'rename', 'database-only'] as const)('an unfinished %s request for the page is never overtaken by a waiver', async kind => withEnv({ GBRAIN_HOME: home }, async () => {
- let hold = Promise.withResolvers<void>();
- registerMutationPreparer('test_waiver_hold', async () => { await hold.promise; return { observedRevision: null, noop: true, apply: async () => ({ status: 'complete' }) }; });
- try {
- for (const engine of engines) {
- hold = Promise.withResolvers<void>();
- const f = await deletedFixture(engine, { 'a.md': note('Pending foreground work') }, ['a']);
- const binding = (await getWorktreeBinding(engine, f.id))!;
- const authority = await managedSyncAuthority(engine, f.id, binding.source_incarnation, f.root);
- const page = (await engine.readPageSnapshot('a', { sourceId: f.id, includeDeleted: true }))!.page;
- const intent = kind === 'rename' ? { renameFrom: { slug: 'a', pageId: page.id } } : { restore: true };
- const foreground = await admitWrite(engine, { operation: 'test_waiver_hold', sourceId: f.id, sourceIncarnation: binding.source_incarnation,
- slug: kind === 'rename' ? 'a-renamed' : 'a', pageId: kind === 'rename' ? null : page.id,
- worktreeId: kind === 'database-only' ? null : binding.worktree_id, topologyGeneration: kind === 'database-only' ? null : binding.topology_generation,
- principal: authority.writer.principal, authority: authority.writer, callerIntent: intent, intent });
- expect(await engine.executeRaw(UNFINISHED_PAGE_REQUEST_SQL, [binding.worktree_id, binding.source_incarnation, f.id, 'a', page.id, String(page.id), 'a.md', 'a.md'])).toHaveLength(1);
- const abort = new AbortController();
- const admitted = waitFor(async () => (await deleteRequests(engine, f.id)).length > 0, { timeoutMs: 30_000 }).then(() => abort.abort());
- const result = await performManagedSync(engine, { sourceId: f.id, ...WAIVER_OPTS, signal: abort.signal });
- await admitted;
- expect(result.waived ?? { imports: 0, deletes: 0 }).toEqual({ imports: 0, deletes: 0 });
- expect(await deleteRequests(engine, f.id)).toHaveLength(1);
- if (kind !== 'database-only') expect(result).toMatchObject({ status: 'partial', reason: 'timeout', writeWait: { status: 'pending' } });
- hold.resolve();
- await waitFor(async () => ['committed', 'conflict', 'failed'].includes((await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE id=$1::uuid', [foreground.id]))[0].state), { timeoutMs: 30_000 });
- let finished = result;
- for (let i = 0; i < 5 && finished.status === 'partial'; i++) finished = await performManagedSync(engine, { sourceId: f.id, ...WAIVER_OPTS });
- expect(finished).toMatchObject({ status: 'synced', waived: { imports: 0, deletes: 0 } });
- await disposePersistenceConsumer(engine);
- }
- } finally { hold.resolve(); }
-}), 120_000);
-
// #6712 PR 4b: a soft-deleted page whose file is gone is no pass candidate (nothing is read or waived), so the revocation
// lands on a live page's delete: its screen re-reads the page, and the revoked grant refuses before any admission.
test('revoked sync authority refuses before any delete is admitted', async () => withEnv({ GBRAIN_HOME: home }, async () => {
@@ -849,111 +661,87 @@ test('revoked sync authority refuses before any delete is admitted', async () =>
}
}), 120_000);
-test('a waiver that loses the cursor to another drain adopts the winner without double counting', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+// #6712 PR 4b: the waiver run (no-op deletes of soft-deleted pages, frozen and screened in one cursor run) is cursor-only; on the
+// pass a soft-deleted page whose file is gone is no candidate (above). What survives is the delete of a live page whose file
+// is gone, and these rows pin its two data guarantees: a database edit landing between the pass's read and its delete is
+// never overwritten, and an unfinished foreground request on the page is never overtaken by the delete.
+test('a database edit of a live page between the pass\'s screen and its delete is held concurrent_write; the page and the edit stay', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
for (const engine of engines) {
- const f = await deletedFixture(engine, { 'a.md': note('First'), 'b.md': note('Second') }, ['a', 'b']);
- let winner: Awaited<ReturnType<typeof performManagedSync>> | undefined;
- const proxy = onScreen(engine, 'a', async () => { winner = await performManagedSync(engine, { sourceId: f.id, ...WAIVER_OPTS }); });
- try {
- const loser = await performManagedSync(proxy, { sourceId: f.id, ...WAIVER_OPTS });
- expect(winner).toMatchObject({ status: 'synced', waived: { imports: 0, deletes: 2 } });
- expect(loser).toMatchObject({ status: 'synced', runId: winner!.runId, waived: { imports: 0, deletes: 2 }, deleted: 0 });
- expect((await runRequests(engine, f.id, winner!.runId!)).map(row => row.kind)).toEqual(['managed_sync_checkpoint']);
- } finally { await disposePersistenceConsumer(proxy); await disposePersistenceConsumer(engine); }
- }
-}), 120_000);
-
-/** Counts top-level transactions: a waived entry costs two (a pending save and its waiver) on the per-entry path. */
-function countTransactions(engine: BrainEngine): { engine: BrainEngine; count: () => number } {
- let count = 0;
- return { count: () => count, engine: new Proxy(engine, { get(target, key) {
- if (key === 'transaction') return (fn: (tx: BrainEngine) => Promise<unknown>) => { count++; return target.transaction(fn); };
- const value = Reflect.get(target, key);
- return typeof value === 'function' ? value.bind(target) : value;
- } }) };
-}
-const manyNotes = (n: number) => Object.fromEntries(Array.from({ length: n }, (_, i) => [`n${String(i).padStart(2, '0')}.md`, note(`Note ${i}`)]));
-const manySlugs = (n: number) => Array.from({ length: n }, (_, i) => `n${String(i).padStart(2, '0')}`);
-
-test('a run of no-op deletes is waived in one transaction, and GBRAIN_SYNC_WAIVE_BATCH=0 waives them one at a time', async () => withEnv({ GBRAIN_HOME: home }, async () => {
- for (const engine of engines) {
- for (const batch of ['1', '0']) await withEnv({ GBRAIN_SYNC_WAIVE_BATCH: batch }, async () => {
- const f = await deletedFixture(engine, manyNotes(10), manySlugs(10));
- const counted = countTransactions(engine);
- const waived: number[] = [];
- try {
- const result = await performManagedSync(counted.engine, { sourceId: f.id, ...WAIVER_OPTS,
- onProgress: event => { if (event.phase === 'managed_sync.page_committed' && event.waived) waived.push(event.bankedFiles!); } });
- expect(result).toMatchObject({ status: 'synced', deleted: 0, waived: { imports: 0, deletes: 10 } });
- expect(waived).toEqual(Array.from({ length: 10 }, (_, i) => i + 1));
- expect((await runRequests(engine, f.id, result.runId!)).map(row => row.kind)).toEqual(['managed_sync_checkpoint']);
- if (batch === '1') expect(counted.count()).toBeLessThan(8);
- else expect(counted.count()).toBeGreaterThanOrEqual(20);
- } finally { await disposePersistenceConsumer(counted.engine); }
- });
- }
-}), 120_000);
-
-test('a page restored in the middle of a waiver run ends the run there: earlier entries are waived, it is admitted and held, and the rest is passed in a new run', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
- for (const engine of engines) {
- const f = await deletedFixture(engine, manyNotes(8), manySlugs(8));
- // n06 is frozen (and screened) after n02 was screened and before the run's waiver transaction.
- const proxy = onScreen(engine, 'n06', () => engine.transaction(tx => withCoordinatedWrite(tx, [f.id], async () => { await tx.restorePage('n02', { sourceId: f.id }); }, TEST_WRITE_ATTRIBUTION)), 1);
+ const f = await deletedFixture(engine, { 'a.md': note('Live until its file is removed') }, []);
+ const edited = 'A concurrent database-only edit that the delete must not overwrite.';
+ const proxy = onScreen(engine, 'a', () => engine.transaction(tx => withCoordinatedWrite(tx, [f.id], async () => { await tx.putPage('a', {
+ type: 'note', title: 'Example', compiled_truth: edited, timeline: '', frontmatter: {}, content_hash: 'concurrent-edit' }, { sourceId: f.id }); }, TEST_WRITE_ATTRIBUTION)));
try {
const result = await performManagedSync(proxy, { sourceId: f.id, ...WAIVER_OPTS });
- // #6340: the restored page's delete conflicts and is held (`concurrent_write`, the page stays); the run no longer stops there.
- expect(result).toMatchObject({ status: 'synced', waived: { imports: 0, deletes: 7 }, held_count: 1, held: [{ path: 'n02.md', code: 'concurrent_write' }] });
- expect((await deleteRequests(engine, f.id)).map(row => row.slug)).toEqual(['n02']);
- expect(await engine.getPage('n02', { sourceId: f.id })).not.toBeNull();
- const [cursor] = await engine.executeRaw<{ index: number; done: boolean }>("SELECT (completed_keys->0->>'index')::int AS index,(completed_keys->0->>'done')::boolean AS done FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id]);
- expect(cursor).toMatchObject({ index: 8, done: true });
+ expect(result).toMatchObject({ deleted: 0, held_count: 1, held: [{ path: 'a.md', code: 'concurrent_write' }] });
+ expect((await engine.getPage('a', { sourceId: f.id }))?.compiled_truth).toBe(edited);
+ expect((await deleteRequests(engine, f.id)).filter(row => row.state === 'committed')).toEqual([]);
} finally { await disposePersistenceConsumer(proxy); rmSync(syncFailuresPath(), { force: true }); }
}
}), 120_000);
-test('an entry frozen for a waiver run is read once: its screen reuses the freeze\'s page read and authority check (#5984 G3)', async () => withEnv({ GBRAIN_HOME: home }, async () => {
- for (const engine of engines) {
- const f = await deletedFixture(engine, manyNotes(8), manySlugs(8));
- const reads = new Map<string, number>();
- const counted = new Proxy(engine, { get(target, key) {
- if (key === 'readPageSnapshot') return (read: string, opts: Parameters<BrainEngine['readPageSnapshot']>[1]) => {
- reads.set(read, (reads.get(read) ?? 0) + 1);
- return target.readPageSnapshot(read, opts);
- };
- const value = Reflect.get(target, key);
- return typeof value === 'function' ? value.bind(target) : value;
- } });
- try {
- const result = await performManagedSync(counted, { sourceId: f.id, ...WAIVER_OPTS });
- expect(result).toMatchObject({ status: 'synced', waived: { imports: 0, deletes: 8 } });
- const slugs = manySlugs(8);
- expect(reads.get(slugs[0]!)).toBe(2);
- expect(slugs.slice(1).map(slug => reads.get(slug))).toEqual(slugs.slice(1).map(() => 1));
- } finally { await disposePersistenceConsumer(counted); }
- }
+test.each(['rename', 'database-only'] as const)('an unfinished %s request for a live page is never overtaken by the pass\'s delete', async kind => withEnv({ GBRAIN_HOME: home }, async () => {
+ let hold = Promise.withResolvers<void>();
+ registerMutationPreparer('test_pass_delete_hold', async () => { await hold.promise; return { observedRevision: null, noop: true, apply: async () => ({ status: 'complete' }) }; });
+ try {
+ for (const engine of engines) {
+ hold = Promise.withResolvers<void>();
+ const f = await deletedFixture(engine, { 'a.md': note('Pending foreground work') }, []);
+ const binding = (await getWorktreeBinding(engine, f.id))!;
+ const authority = await managedSyncAuthority(engine, f.id, binding.source_incarnation, f.root);
+ const page = (await engine.readPageSnapshot('a', { sourceId: f.id }))!.page;
+ const intent = kind === 'rename' ? { renameFrom: { slug: 'a', pageId: page.id } } : { restore: true };
+ const foreground = await admitWrite(engine, { operation: 'test_pass_delete_hold', sourceId: f.id, sourceIncarnation: binding.source_incarnation,
+ slug: kind === 'rename' ? 'a-renamed' : 'a', pageId: kind === 'rename' ? null : page.id,
+ worktreeId: kind === 'database-only' ? null : binding.worktree_id, topologyGeneration: kind === 'database-only' ? null : binding.topology_generation,
+ principal: authority.writer.principal, authority: authority.writer, callerIntent: intent, intent });
+ const foregroundState = async () => (await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE id=$1::uuid', [foreground.id]))[0];
+ const result = await performManagedSync(engine, { sourceId: f.id, ...WAIVER_OPTS });
+ expect(result.deleted).toBe(0);
+ // database-only: the page's open request makes its path in_flight, so no delete is admitted; rename: the delete is
+ // admitted behind the rename's renameFrom (#6862 FIFO) and waits for it.
+ const waiting = (await deleteRequests(engine, f.id)).map(row => ['committed', 'conflict', 'failed'].includes(row.state) ? `${row.slug}:done` : `${row.slug}:waiting`);
+ expect(waiting).toEqual(kind === 'rename' ? ['a:waiting'] : []);
+ expect(['committed', 'conflict', 'failed']).not.toContain((await foregroundState()).state);
+ expect(await engine.getPage('a', { sourceId: f.id })).not.toBeNull();
+ hold.resolve();
+ await waitFor(async () => ['committed', 'conflict', 'failed'].includes((await foregroundState()).state), { timeoutMs: 30_000 });
+ let finished = await performManagedSync(engine, { sourceId: f.id, ...WAIVER_OPTS });
+ for (let i = 0; i < 5 && finished.status === 'partial'; i++) finished = await performManagedSync(engine, { sourceId: f.id, ...WAIVER_OPTS });
+ expect(finished).toMatchObject({ status: 'synced' });
+ const [order] = await engine.executeRaw<{ after: boolean }>("SELECT d.completed_at >= g.completed_at AS after FROM persistence_requests d, persistence_requests g WHERE d.source_id=$1 AND d.intent->>'kind'='managed_sync_delete' AND d.state='committed' AND g.id=$2::uuid", [f.id, foreground.id]);
+ expect(order).toEqual({ after: true });
+ expect(await engine.getPage('a', { sourceId: f.id })).toBeNull();
+ await disposePersistenceConsumer(engine);
+ }
+ } finally { hold.resolve(); }
}), 120_000);
-test('a crash inside a waiver run skips nothing and waives nothing twice; a lock timeout falls back to one entry at a time', async () => withEnv({ GBRAIN_HOME: home }, async () => {
- for (const engine of engines) {
- for (const fault of ['crash', 'lock_timeout'] as const) {
- const f = await deletedFixture(engine, manyNotes(6), manySlugs(6));
- let fired = 0;
- installFaultHook(point => {
- if (point !== 'sync:mid_waiver_run') return;
- fired++;
- if (fault === 'crash' && fired === 1) throw new Error('injected crash inside the waiver run');
- if (fault === 'lock_timeout') throw Object.assign(new Error('canceling statement due to lock timeout'), { code: '55P03' });
- });
+test('a CRLF-only working copy of a committed edit imports the committed bytes on the pass, with no refusal or receipt', async () =>
+ withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ for (const engine of engines) {
+ await engine.setConfig('sync.holds', 'fail');
try {
- if (fault === 'crash') await expect(performManagedSync(engine, { sourceId: f.id, ...WAIVER_OPTS })).rejects.toThrow('injected crash');
- const result = await performManagedSync(engine, { sourceId: f.id, ...WAIVER_OPTS });
- expect(result).toMatchObject({ status: 'synced', deleted: 0, waived: { imports: 0, deletes: 6 } });
- expect(await deleteRequests(engine, f.id)).toHaveLength(0);
- expect(fired).toBeGreaterThan(0);
- } finally { installFaultHook(undefined); await disposePersistenceConsumer(engine); }
+ const f = await fixture(engine, { 'notes/example.md': 'An original observation about the example system.\n' });
+ await performManagedSync(engine, { sourceId: f.id, noPull: true });
+ const pinned = 'A newly committed observation about the example system.\n';
+ const path = join(f.root, 'notes/example.md');
+ writeFileSync(path, pinned);
+ const target = commit(f.root);
+ const working = pinned.replace(/\n/g, '\r\n');
+ writeFileSync(path, working);
+ const result = await performManagedSync(engine, { sourceId: f.id, noPull: true });
+ expect(result).toMatchObject({ status: 'synced', modified: 1, toCommit: target });
+ expect(result.managedWrite).toBeUndefined();
+ expect((await engine.getPage('notes/example', { sourceId: f.id }))?.compiled_truth).toContain('newly committed');
+ expect(readFileSync(path, 'utf8')).toBe(working);
+ expect(loadSyncFailures().filter(row => row.source_id === f.id)).toHaveLength(0);
+ expect((await engine.executeRaw<{ state: string }>("SELECT state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import' ORDER BY sequence", [f.id])).map(row => row.state))
+ .toEqual(['committed', 'committed']);
+ expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(target);
+ } finally { await engine.executeRaw("DELETE FROM config WHERE key='sync.holds'"); }
}
- }
-}), 120_000);
+ }), 120_000);
test('the waiver lookup for unfinished page requests is served by the request indexes', async () => {
for (const engine of engines) {