Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/world-local-tagged-clear-locks.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@workflow/world-local": patch
---

Make a tagged `clear()` delete only its own tag's lock files, so it no longer reopens another tag's disposed hooks mid-run.
47 changes: 43 additions & 4 deletions packages/world-local/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,48 @@ export type LocalWorld = World & {
clear(): Promise<void>;
};

/**
* Delete one tag's lock files: dispose locks, terminal markers, create
* claims and staged hook events, all named `.locks/<kind>/<id>.<state>.<tag>`.
*
* `.locks` is shared by every tag, and a lock is the durable record that its
* hook or entity is closed, so a tagged `clear()` must leave other tags' locks
* alone. Vitest workers each clear under their own tag when a test file
* starts, while other workers' runs are in flight: deleting a disposed hook's
* lock there makes it look live to the token claim rebuild, and the run that
* recreates its token then conflicts with its own disposed hook.
*/
async function clearTaggedLocks(basedir: string, tag: string): Promise<void> {
const locksDir = path.join(basedir, '.locks');
let lockKindEntries: import('node:fs').Dirent[];
try {
lockKindEntries = await fs.readdir(locksDir, { withFileTypes: true });
} catch {
lockKindEntries = [];
}
await settleAll(
lockKindEntries
.filter((entry) => entry.isDirectory())
.map(async (entry) => {
const lockKindDir = path.join(locksDir, entry.name);
const lockNames = await fs
.readdir(lockKindDir)
.catch(() => [] as string[]);
await settleAll(
lockNames
.filter((name) => name.endsWith(`.${tag}`))
.map((name) =>
// Recursive: a run's staged hook events are a directory.
fs.rm(path.join(lockKindDir, name), {
recursive: true,
force: true,
})
)
);
})
);
}

/**
* Creates a local world instance that combines queue, storage, and streamer functionalities.
*
Expand Down Expand Up @@ -221,10 +263,7 @@ export function createWorld(args?: Partial<Config>): LocalWorld {
})
);
}
// Clean up lock files used for atomic terminal-state guards
await fs
.rm(path.join(basedir, '.locks'), { recursive: true, force: true })
.catch(() => {});
await clearTaggedLocks(basedir, tag);
// Delete tagged stream chunks (.{tag}.bin files). Chunks are sharded
// one directory per stream (streams/chunks/<streamName>/<chunkId>.{tag}.bin),
// so iterate each per-stream directory: the top-level chunks dir now
Expand Down
77 changes: 77 additions & 0 deletions packages/world-local/src/tag.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { promises as fs } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { SPEC_VERSION_CURRENT } from '@workflow/world';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { listJSONFiles, stripTag } from './fs.js';
import { createStorage } from './storage.js';
import {
createHook,
createRun,
createStep,
disposeHook,
updateRun,
updateStep,
} from './test-helpers.js';
Expand Down Expand Up @@ -389,6 +391,81 @@ describe('File tagging', () => {

await world.close?.();
});

it("should delete only its own tag's lock files", async () => {
const { createWorld } = await import('./index.js');

const world0 = createWorld({ dataDir: testDir, tag: 'vitest-0' });
const world1 = createWorld({ dataDir: testDir, tag: 'vitest-1' });
await world0.start?.();

for (const [world, hookId] of [
[world0, 'hook_0'],
[world1, 'hook_1'],
] as const) {
const run = await createRun(world, {
deploymentId: 'dep-1',
workflowName: 'hook-wf',
input: new Uint8Array(),
});
await updateRun(world, run.runId, 'run_started');
await createHook(world, run.runId, {
hookId,
token: `token-${hookId}`,
});
await disposeHook(world, run.runId, hookId);
}

const hookLocksDir = path.join(testDir, '.locks', 'hooks');
expect((await fs.readdir(hookLocksDir)).sort()).toEqual([
'hook_0.disposed.vitest-0',
'hook_1.disposed.vitest-1',
]);

await world0.clear();

expect(await fs.readdir(hookLocksDir)).toEqual([
'hook_1.disposed.vitest-1',
]);

await world0.close?.();
await world1.close?.();
});

// Regression: clear() deleted all of `.locks`, so another vitest worker
// starting a test file reopened this worker's disposed hook, and the run
// recreating its token conflicted with itself (hook-token-reuse.test.ts).
it("should not reopen another tag's disposed hook", async () => {
const { createWorld } = await import('./index.js');

const world0 = createWorld({ dataDir: testDir, tag: 'vitest-0' });
const world1 = createWorld({ dataDir: testDir, tag: 'vitest-1' });
await world0.start?.();

const run = await createRun(world1, {
deploymentId: 'dep-1',
workflowName: 'hook-wf',
input: new Uint8Array(),
});
await updateRun(world1, run.runId, 'run_started');
const token = 'reused-token';
await createHook(world1, run.runId, { hookId: 'hook_0', token });
await disposeHook(world1, run.runId, 'hook_0');

await world0.clear();

const result = await world1.events.create(run.runId, {
eventType: 'hook_created',
specVersion: SPEC_VERSION_CURRENT,
correlationId: 'hook_1',
eventData: { token },
});
expect(result.event?.eventType).toBe('hook_created');
expect(result.hook?.hookId).toBe('hook_1');

await world0.close?.();
await world1.close?.();
});
});

describe('untagged clear()', () => {
Expand Down
Loading