Skip to content

Commit 202f07e

Browse files
omercangumusCopilottamirdresher
authored
fix(sdk): lock concurrent memory index writes (#2356)
Serialize governed-memory index updates with shared .squad locks and unique temp files. Initialize indexes atomically and retry transient Windows rename failures. Give the package smoke test setup enough time on slower CI runners. Closes #2334. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Tamir Dresher <tamir.dresher@gmail.com>
1 parent a1ea4e3 commit 202f07e

9 files changed

Lines changed: 192 additions & 47 deletions

File tree

‎.changeset/calm-index-lock.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@bradygaster/squad-sdk': patch
3+
---
4+
5+
Serialize memory index updates across local store instances and processes.

‎.github/workflows/squad-release-verify.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ jobs:
111111
run: npm run build
112112

113113
- name: Run Windows platform suite with JSON report
114-
run: npx vitest run test/mcp-root-write.test.ts --reporter=default --reporter=json --outputFile="$env:EVIDENCE_DIR\vitest-report.json"
114+
run: npx vitest run test/mcp-root-write.test.ts test/memory-providers.test.ts --reporter=default --reporter=json --outputFile="$env:EVIDENCE_DIR\vitest-report.json"
115115

116116
- name: Require the Windows-only test to execute
117117
if: always()

‎packages/squad-sdk/src/backend/local-backend.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,8 @@ export function createFileStateStore(squadDir: string, options: FileStateStoreOp
192192
fs.mkdirSync(path.dirname(lockPath), { recursive: true });
193193
return 'wait';
194194
}
195-
if (code !== 'EEXIST') throw err;
195+
// Windows may report a sharing violation instead of EEXIST for an active lock.
196+
if (code !== 'EEXIST' && code !== 'EACCES' && code !== 'EPERM') throw err;
196197
// Crash recovery: an abandoned lock is claimed by atomic rename, so exactly one waiter wins it.
197198
// The claimed file is re-checked; if it turns out to be a live holder's lock it is put back untouched.
198199
try {

‎packages/squad-sdk/src/memory/index.ts‎

Lines changed: 50 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,18 @@
11
import path from 'node:path';
22
import { randomUUID } from 'node:crypto';
3+
import { realpath } from 'node:fs/promises';
4+
import { createFileStateStore } from '../backend/local-backend.js';
5+
import { StateKeyConflictError } from '../storage/storage-error.js';
36
import type { StorageProvider } from '../storage/storage-provider.js';
47

8+
async function ensureMemoryIndex(storage: StorageProvider, indexPath: string): Promise<void> {
9+
try {
10+
await storage.createIfAbsent(indexPath, '[]\n');
11+
} catch (error) {
12+
if (!(error instanceof StateKeyConflictError)) throw error;
13+
}
14+
}
15+
516
export type MemoryClass =
617
| 'TRANSIENT'
718
| 'LOCAL'
@@ -596,9 +607,11 @@ export async function ensureMemoryGovernanceDefaults(
596607
}
597608

598609
const indexPath = path.join(memoryDir, 'index.json');
599-
if (!await storage.exists(indexPath)) {
600-
await storage.write(indexPath, '[]\n');
610+
try {
611+
await storage.createIfAbsent(indexPath, '[]\n');
601612
created.push(path.join('.squad', 'memory', 'index.json'));
613+
} catch (error) {
614+
if (!(error instanceof StateKeyConflictError)) throw error;
602615
}
603616

604617
const auditPath = path.join(memoryDir, 'audit.jsonl');
@@ -615,12 +628,6 @@ export class LocalMemoryStore {
615628
private readonly copilotProvider: HostInjectedCopilotMemoryAdapter;
616629
private readonly registeredProviders: MemoryProvider[];
617630
private readonly providerTimeoutMs: number;
618-
/**
619-
* Async mutex tail for index read-modify-write operations.
620-
* Each caller enqueues behind the current tail so concurrent writes
621-
* are serialized without OS-level file locking.
622-
*/
623-
private indexLockTail: Promise<unknown> = Promise.resolve();
624631

625632
constructor(
626633
private readonly storage: StorageProvider,
@@ -642,22 +649,24 @@ export class LocalMemoryStore {
642649
* Serialize all index read-modify-write operations.
643650
*
644651
* All callers that do readIndex() → mutate → writeIndex() must go through
645-
* this method so concurrent writes within the same store instance cannot
646-
* interleave and lose entries. The critical section is purely async
647-
* (no thread blocking), so this is safe in Node.js single-thread land.
652+
* this method so concurrent writers cannot interleave and lose entries.
653+
* The file lock coordinates callers across store instances and processes
654+
* sharing the same .squad directory.
648655
*/
649656
private async withIndexLock<T>(fn: () => Promise<T>): Promise<T> {
650-
let unlock!: () => void;
651-
// Append a new "release" promise to the tail of the lock chain.
652-
// The next caller will wait for this release before proceeding.
653-
const release = new Promise<void>(resolve => { unlock = resolve; });
654-
const prev = this.indexLockTail;
655-
this.indexLockTail = release;
656-
await prev;
657+
const resolvedSquadDir = path.resolve(this.squadDir);
658+
let lockRoot = resolvedSquadDir;
659+
try {
660+
lockRoot = await realpath(resolvedSquadDir);
661+
} catch (error) {
662+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
663+
}
664+
const fileLock = createFileStateStore(lockRoot);
665+
const releaseFileLock = await fileLock.lockAsync!('backend/locks/memory-index');
657666
try {
658667
return await fn();
659668
} finally {
660-
unlock();
669+
releaseFileLock();
661670
}
662671
}
663672

@@ -1328,9 +1337,7 @@ export class LocalMemoryStore {
13281337
await this.storage.write(configPath, JSON.stringify(DEFAULT_CONFIG, null, 2) + '\n');
13291338
}
13301339
const indexPath = path.join(memoryDir, 'index.json');
1331-
if (!await this.storage.exists(indexPath)) {
1332-
await this.storage.write(indexPath, '[]\n');
1333-
}
1340+
await ensureMemoryIndex(this.storage, indexPath);
13341341
const auditPath = path.join(memoryDir, 'audit.jsonl');
13351342
if (!await this.storage.exists(auditPath)) {
13361343
await this.storage.write(auditPath, '');
@@ -1414,11 +1421,28 @@ export class LocalMemoryStore {
14141421

14151422
private async writeIndex(index: MemoryIndexEntry[]): Promise<void> {
14161423
const indexPath = path.join(this.squadDir, 'memory', 'index.json');
1417-
const tmpPath = `${indexPath}.tmp`;
1418-
// Write to a temp file first, then atomically rename into place.
1419-
// This prevents a crash mid-write from leaving a partial/corrupt index.
1424+
const tmpPath = `${indexPath}.${process.pid}.${randomUUID()}.tmp`;
14201425
await this.storage.write(tmpPath, JSON.stringify(index, null, 2) + '\n');
1421-
await this.storage.rename(tmpPath, indexPath);
1426+
try {
1427+
for (let attempt = 0; ; attempt++) {
1428+
try {
1429+
await this.storage.rename(tmpPath, indexPath);
1430+
return;
1431+
} catch (error) {
1432+
const code = typeof error === 'object' && error !== null && 'code' in error
1433+
? String(error.code)
1434+
: undefined;
1435+
const retryable = process.platform === 'win32'
1436+
&& ['EACCES', 'EBUSY', 'EPERM'].includes(code ?? '')
1437+
&& attempt < 4;
1438+
if (!retryable) throw error;
1439+
await new Promise(resolve => setTimeout(resolve, 10 * 2 ** attempt));
1440+
}
1441+
}
1442+
} catch (error) {
1443+
try { await this.storage.delete(tmpPath); } catch { /* preserve the rename error */ }
1444+
throw error;
1445+
}
14221446
}
14231447

14241448
private async audit(record: Omit<MemoryAuditRecord, 'timestamp'>): Promise<void> {

‎packages/squad-sdk/src/storage/fs-storage-provider.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,15 @@ export class FSStorageProvider implements StorageProvider {
146146
fh = await open(safePath, 'wx');
147147
} catch (openErr: unknown) {
148148
const code = (openErr as NodeJS.ErrnoException).code;
149-
if (code === 'EEXIST') {
149+
// Windows can report a sharing violation instead of EEXIST for a racing creator.
150+
let existingFile = false;
151+
if (code === 'EACCES' || code === 'EPERM') {
152+
try {
153+
await access(safePath);
154+
existingFile = true;
155+
} catch { /* It may have disappeared after the exclusive open failed. */ }
156+
}
157+
if (code === 'EEXIST' || existingFile) {
150158
throw new StateKeyConflictError(filePath);
151159
}
152160
throw new StateBackendUncertaintyError(

‎scripts/release/test-reconciliation.mjs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,13 @@ export const CATEGORY_RULES = Object.freeze([
5050
runsOn: 'win32',
5151
reason: "it.runIf(process.platform === 'win32'): Windows-only legacy drive-hash reconciliation",
5252
},
53+
{
54+
category: 'env-gated',
55+
file: 'test/memory-providers.test.ts',
56+
title: '[platform: win32] retries transient Windows index rename sharing violations',
57+
runsOn: 'win32',
58+
reason: "it.skipIf(process.platform !== 'win32'): Windows-only index rename sharing violations",
59+
},
5360
{
5461
category: 'env-gated',
5562
file: 'test/mcp-root-write.test.ts',

‎test/cli-packaging-smoke.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ describe('CLI packaging smoke test', { timeout: 120_000 }, () => {
122122
};
123123

124124
installedCli = installPackedCli('squad-cli-test-');
125-
}, 90000);
125+
}, 180000);
126126

127127
afterAll(() => {
128128
// Cleanup - with retry logic for Windows file locks

‎test/memory-providers.test.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,12 @@
1111
*/
1212

1313
import { afterEach, describe, expect, it } from 'vitest';
14+
import { spawn } from 'node:child_process';
1415
import * as fs from 'node:fs';
1516
import * as path from 'node:path';
1617
import * as os from 'node:os';
1718
import { randomUUID } from 'node:crypto';
19+
import { pathToFileURL } from 'node:url';
1820
import { FSStorageProvider } from '../packages/squad-sdk/src/storage/fs-storage-provider.js';
1921
import {
2022
LocalMemoryStore,
@@ -561,6 +563,75 @@ describe('LocalMemoryStore — concurrent writes and index integrity', () => {
561563
expect(activeIds.has(id!)).toBe(true);
562564
}
563565
});
566+
567+
it('serializes writes from separate processes sharing the same memory index', async () => {
568+
const root = testRoot('concurrent-writes-separate-stores');
569+
const writesPerStore = 25;
570+
const memoryDir = path.join(root, '.squad', 'memory');
571+
for (const dir of ['local', 'policy-inbox', 'semantic-inbox', 'tombstones']) {
572+
fs.mkdirSync(path.join(memoryDir, dir), { recursive: true });
573+
}
574+
fs.writeFileSync(path.join(memoryDir, 'config.json'), '{}\n');
575+
fs.writeFileSync(path.join(memoryDir, 'audit.jsonl'), '');
576+
577+
const memoryModule = pathToFileURL(path.resolve('packages/squad-sdk/dist/memory/index.js')).href;
578+
const storageModule = pathToFileURL(path.resolve('packages/squad-sdk/dist/storage/fs-storage-provider.js')).href;
579+
const runWriter = (prefix: string) => {
580+
const script = `
581+
import { LocalMemoryStore } from ${JSON.stringify(memoryModule)};
582+
import { FSStorageProvider } from ${JSON.stringify(storageModule)};
583+
const store = new LocalMemoryStore(new FSStorageProvider(), ${JSON.stringify(root)});
584+
const results = await Promise.all(Array.from({ length: ${writesPerStore} }, (_, i) =>
585+
store.write({ content: ${JSON.stringify(prefix)} + i, title: ${JSON.stringify(prefix)} + i, requestedClass: 'LOCAL' })
586+
));
587+
if (results.some(result => !result.stored)) throw new Error('A memory write was rejected');
588+
`;
589+
return new Promise<void>((resolve, reject) => {
590+
const child = spawn(process.execPath, ['--input-type=module', '-e', script], { stdio: ['ignore', 'ignore', 'pipe'] });
591+
let stderr = '';
592+
child.stderr?.setEncoding('utf8');
593+
child.stderr?.on('data', chunk => { stderr += chunk; });
594+
child.once('error', reject);
595+
child.once('close', code => {
596+
if (code === 0) resolve();
597+
else reject(new Error(`Memory writer exited with code ${code}: ${stderr}`));
598+
});
599+
});
600+
};
601+
const writers = await Promise.allSettled([runWriter('first-'), runWriter('second-')]);
602+
const failedWriter = writers.find(result => result.status === 'rejected');
603+
if (failedWriter?.status === 'rejected') throw failedWriter.reason;
604+
605+
const indexDir = path.join(root, '.squad', 'memory');
606+
const index = JSON.parse(fs.readFileSync(path.join(indexDir, 'index.json'), 'utf8')) as Array<{ id: string; status: string; title: string }>;
607+
const activeEntries = index.filter(entry => entry.status === 'active');
608+
expect(activeEntries).toHaveLength(writesPerStore * 2);
609+
const titles = new Set(activeEntries.map(entry => entry.title));
610+
for (const prefix of ['first-', 'second-']) {
611+
for (let i = 0; i < writesPerStore; i++) expect(titles.has(`${prefix}${i}`)).toBe(true);
612+
}
613+
expect(fs.readdirSync(indexDir).some(name => name.endsWith('.tmp'))).toBe(false);
614+
}, 30_000);
615+
616+
it.skipIf(process.platform !== 'win32')('[platform: win32] retries transient Windows index rename sharing violations', async () => {
617+
const root = testRoot('index-rename-retry');
618+
const storage = new FSStorageProvider();
619+
const rename = storage.rename.bind(storage);
620+
let attempts = 0;
621+
storage.rename = async (oldPath, newPath) => {
622+
attempts++;
623+
if (attempts < 3) throw Object.assign(new Error('file is busy'), { code: 'EPERM' });
624+
await rename(oldPath, newPath);
625+
};
626+
627+
const store = new LocalMemoryStore(storage, root);
628+
const result = await store.write({ content: 'Retry the index rename.', title: 'Rename retry', requestedClass: 'LOCAL' });
629+
630+
expect(result.stored).toBe(true);
631+
expect(attempts).toBe(3);
632+
const indexDir = path.join(root, '.squad', 'memory');
633+
expect(fs.readdirSync(indexDir).some(name => name.endsWith('.tmp'))).toBe(false);
634+
});
564635
});
565636

566637
describe('LocalMemoryStore — corrupted index.json handling', () => {

‎test/test-reconciliation.test.ts‎

Lines changed: 46 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,11 @@
11
import { describe, expect, it } from 'vitest';
22
import { reconcile, resolvePlatform, shouldFail } from '../scripts/release/test-reconciliation.mjs';
33

4-
function reportFor(
5-
file: string,
6-
title: string,
7-
status: 'passed' | 'skipped',
8-
) {
4+
function reportForMany(tests: Array<{ file: string; title: string; status: 'passed' | 'skipped' }>) {
95
return {
10-
numTotalTests: 1,
6+
numTotalTests: tests.length,
117
numFailedTests: 0,
12-
testResults: [{
8+
testResults: tests.map(({ file, title, status }) => ({
139
name: file,
1410
status: 'passed',
1511
assertionResults: [{
@@ -18,10 +14,14 @@ function reportFor(
1814
status,
1915
failureMessages: [],
2016
}],
21-
}],
17+
})),
2218
};
2319
}
2420

21+
function reportFor(file: string, title: string, status: 'passed' | 'skipped') {
22+
return reportForMany([{ file, title, status }]);
23+
}
24+
2525
describe('release test reconciliation', () => {
2626
it('classifies NoopClaimProvider contract sections as structurally inapplicable', () => {
2727
const report = reportFor(
@@ -85,20 +85,48 @@ describe('release test reconciliation', () => {
8585
expect(shouldFail(result, { failOnUnexplained: true })).toBe(true);
8686
});
8787

88+
it('classifies the Windows-only memory rename retry skip on Linux', () => {
89+
const title = '[platform: win32] retries transient Windows index rename sharing violations';
90+
const result = reconcile(reportFor('test/memory-providers.test.ts', title, 'skipped'), { platform: 'linux' });
91+
92+
expect(result.summary).toMatchObject({
93+
byCategory: { 'env-gated': 1 },
94+
ok: true,
95+
});
96+
expect(result.nonPassing[0]).toMatchObject({
97+
file: 'test/memory-providers.test.ts',
98+
title,
99+
reason: "it.skipIf(process.platform !== 'win32'): Windows-only index rename sharing violations",
100+
});
101+
});
102+
88103
it('requires the Windows-only test to be present and passed in Windows evidence', () => {
89104
const title = '[platform: win32] removes the legacy raw uppercase Windows drive hash while preserving unrelated entries';
90-
const result = reconcile(reportFor('D:\\a\\squad\\squad\\test\\mcp-root-write.test.ts', title, 'passed'), {
105+
const memoryTitle = '[platform: win32] retries transient Windows index rename sharing violations';
106+
const result = reconcile(reportForMany([
107+
{ file: 'D:\\a\\squad\\squad\\test\\mcp-root-write.test.ts', title, status: 'passed' },
108+
{ file: 'D:\\a\\squad\\squad\\test\\memory-providers.test.ts', title: memoryTitle, status: 'passed' },
109+
]), {
91110
platform: 'win32',
92111
requirePlatformExecutions: true,
93112
});
94113

95-
expect(result.summary.requiredExecutions).toEqual([{
96-
file: 'test/mcp-root-write.test.ts',
97-
title,
98-
platform: 'win32',
99-
status: 'passed',
100-
ok: true,
101-
}]);
114+
expect(result.summary.requiredExecutions).toEqual([
115+
{
116+
file: 'test/mcp-root-write.test.ts',
117+
title,
118+
platform: 'win32',
119+
status: 'passed',
120+
ok: true,
121+
},
122+
{
123+
file: 'test/memory-providers.test.ts',
124+
title: memoryTitle,
125+
platform: 'win32',
126+
status: 'passed',
127+
ok: true,
128+
},
129+
]);
102130
expect(result.summary.ok).toBe(true);
103131
expect(shouldFail(result, { failOnUnexplained: true })).toBe(false);
104132
});
@@ -110,7 +138,8 @@ describe('release test reconciliation', () => {
110138
});
111139

112140
expect(result.summary.requiredExecutions).toEqual([
113-
expect.objectContaining({ platform: 'win32', status: 'missing', ok: false }),
141+
expect.objectContaining({ file: 'test/mcp-root-write.test.ts', platform: 'win32', status: 'missing', ok: false }),
142+
expect.objectContaining({ file: 'test/memory-providers.test.ts', platform: 'win32', status: 'missing', ok: false }),
114143
]);
115144
expect(result.summary.ok).toBe(false);
116145
expect(shouldFail(result, { failOnUnexplained: true })).toBe(true);

0 commit comments

Comments
 (0)