Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(guard): check-durable-flush fails on fsync of a read-only descriptor outside fs-durable.ts

garrytane5e290005b80
diff --git a/package.json b/package.json
index 8596f78620..7884faf3d9 100644
--- a/package.json
+++ b/package.json
@@ -133,6 +133,7 @@
"check:module-size": "bash scripts/check-module-size.sh",
"check:function-size": "bun scripts/check-function-size.ts",
"check:layering": "bun scripts/check-layering.ts",
+ "check:durable-flush": "bun scripts/check-durable-flush.ts",
"check:engine-sql-ratchet": "bun scripts/check-engine-sql-ratchet.ts",
"check:engine-sql-dynamic": "bun scripts/check-engine-sql-dynamic.ts",
"check:engine-sql-brands": "bun scripts/check-engine-sql-brands.ts",
diff --git a/scripts/check-durable-flush.ts b/scripts/check-durable-flush.ts
new file mode 100644
index 0000000000..928374fdde
--- /dev/null
+++ b/scripts/check-durable-flush.ts
@@ -0,0 +1,138 @@
+#!/usr/bin/env bun
+/**
+ * Durable-flush guard (#5595, #5475; docs/TESTING.md#durable-flush-guard).
+ *
+ * Windows `FlushFileBuffers` needs write access and Windows has no directory
+ * flush, so the POSIX idiom `fsyncSync(openSync(path, 'r'))` fails with EPERM
+ * there. That idiom, copied across persistence, wedged the managed write queue
+ * (#5595) and every skill-bundle publication (#5475). Outside
+ * src/core/fs-durable.ts this guard fails on any `fsyncSync(fd)` in src/ whose
+ * `fd` is assigned from a read-only `openSync` (flags omitted, a flag string
+ * without w/a/+, or O_RDONLY without O_WRONLY/O_RDWR), file or directory, and
+ * on one whose flags it cannot read. Flushes of descriptors opened for writing
+ * stay as they are.
+ *
+ * Fix: flush the descriptor you wrote through before closing it, or call
+ * flushFile / flushDirectory from src/core/fs-durable.ts.
+ *
+ * Seam: GBRAIN_GUARD_ROOT (fixture tree root).
+ */
+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
+import { join, relative } from 'node:path';
+import ts from 'typescript';
+
+const ROOT = process.env.GBRAIN_GUARD_ROOT ?? join(import.meta.dir, '..');
+const ANCHOR = 'docs/TESTING.md#durable-flush-guard';
+const HELPER = 'src/core/fs-durable.ts';
+
+/** Files allowed to keep a read-only-handle flush until they migrate. Each entry names its reason; a stale entry fails. */
+const ALLOWLIST: Record<string, string> = {
+ 'src/core/binary-self-update.ts': 'AFTER-FW7, GBRA-35 self-upgrade',
+};
+
+function tsFiles(dir: string): string[] {
+ if (!existsSync(dir)) return [];
+ const out: string[] = [];
+ for (const entry of readdirSync(dir).sort()) {
+ const full = join(dir, entry);
+ if (statSync(full).isDirectory()) out.push(...tsFiles(full));
+ else if (entry.endsWith('.ts')) out.push(full);
+ }
+ return out;
+}
+
+const calleeName = (call: ts.CallExpression): string | null => {
+ const callee = call.expression;
+ if (ts.isIdentifier(callee)) return callee.text;
+ if (ts.isPropertyAccessExpression(callee)) return callee.name.text;
+ return null;
+};
+
+/** 'read' | 'write' | 'unknown' for an openSync call's flags argument. */
+function access(call: ts.CallExpression, sf: ts.SourceFile): 'read' | 'write' | 'unknown' {
+ const flags = call.arguments[1];
+ if (!flags) return 'read';
+ if (ts.isStringLiteralLike(flags)) return /[wa+]/.test(flags.text) ? 'write' : 'read';
+ const text = flags.getText(sf);
+ if (/\bO_(?:WRONLY|RDWR)\b/.test(text)) return 'write';
+ if (/\bO_RDONLY\b/.test(text)) return 'read';
+ return 'unknown';
+}
+
+/** Whether `scope` itself (not a nested block or function) declares the variable `name`. */
+function declaresDirectly(scope: ts.Node, name: string): boolean {
+ let found = false;
+ const visit = (node: ts.Node): void => {
+ if (found || ts.isBlock(node) || ts.isFunctionLike(node) || ts.isClassLike(node)) return;
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.name.text === name) found = true;
+ else ts.forEachChild(node, visit);
+ };
+ ts.forEachChild(scope, visit);
+ return found;
+}
+
+/** The nearest enclosing block, function or file that declares `name`; null when it is a parameter or undeclared. */
+function declaringScope(node: ts.Node, name: string): ts.Node | null {
+ for (let scope: ts.Node | undefined = node.parent; scope; scope = scope.parent) {
+ if (ts.isFunctionLike(scope) && scope.parameters.some(p => ts.isIdentifier(p.name) && p.name.text === name)) return null;
+ if ((ts.isBlock(scope) || ts.isSourceFile(scope)) && declaresDirectly(scope, name)) return scope;
+ }
+ return null;
+}
+
+/** Every `openSync` call assigned to `name` inside `scope` (declaration initializers and plain assignments). */
+function openCalls(scope: ts.Node, name: string): ts.CallExpression[] {
+ const out: ts.CallExpression[] = [];
+ const take = (value: ts.Expression | undefined) => {
+ if (value && ts.isCallExpression(value) && calleeName(value) === 'openSync') out.push(value);
+ };
+ const visit = (node: ts.Node): void => {
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.name.text === name) take(node.initializer);
+ if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken
+ && ts.isIdentifier(node.left) && node.left.text === name) take(node.right);
+ ts.forEachChild(node, visit);
+ };
+ visit(scope);
+ return out;
+}
+
+const violations: string[] = [];
+const flagged = new Set<string>();
+for (const abs of tsFiles(join(ROOT, 'src'))) {
+ const rel = relative(ROOT, abs).replace(/\\/g, '/');
+ if (rel === HELPER) continue;
+ const sf = ts.createSourceFile(abs, readFileSync(abs, 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
+ const line = (node: ts.Node) => sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;
+ const visit = (node: ts.Node): void => {
+ if (ts.isCallExpression(node) && calleeName(node) === 'fsyncSync') {
+ const fd = node.arguments[0];
+ const opens = fd && ts.isIdentifier(fd)
+ ? (() => { const scope = declaringScope(node, fd.text); return scope ? openCalls(scope, fd.text) : []; })()
+ : fd && ts.isCallExpression(fd) && calleeName(fd) === 'openSync' ? [fd] : [];
+ for (const open of opens) {
+ const kind = access(open, sf);
+ if (kind === 'write') continue;
+ flagged.add(rel);
+ if (ALLOWLIST[rel]) continue;
+ violations.push(`FAIL [durable_flush_read_handle]: ${rel}:${line(node)} fsyncs a descriptor opened ${kind === 'read' ? 'read-only' : 'with flags this guard cannot read'} at line ${line(open)} (${open.getText(sf).replace(/\s+/g, ' ').slice(0, 80)})\n`
+ + ` Fix: fsync the descriptor you wrote through before closing it, or call flushFile/flushDirectory from ${HELPER}`);
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(sf);
+}
+for (const [rel, reason] of Object.entries(ALLOWLIST)) {
+ if (existsSync(join(ROOT, rel)) && !flagged.has(rel)) {
+ violations.push(`FAIL [durable_flush_stale_allowlist]: ${rel} no longer fsyncs a read-only descriptor (allowlisted: ${reason})\n Fix: delete its ALLOWLIST entry in scripts/check-durable-flush.ts`);
+ }
+}
+
+if (violations.length) {
+ for (const v of violations) console.error(v);
+ console.error('Why: Windows refuses fsync on a read-only handle and has no directory flush (EPERM), so the write wedges there (#5595, #5475).');
+ console.error(`See: ${ANCHOR}`);
+ console.error(`check-durable-flush: ${violations.length} violation(s)`);
+ process.exit(1);
+}
+console.log(`check-durable-flush: ok (src/, helper ${HELPER}, ${Object.keys(ALLOWLIST).length} allowlisted)`);
diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsv
index c8a84a3027..18561943d3 100644
--- a/scripts/guards-manifest.tsv
+++ b/scripts/guards-manifest.tsv
@@ -70,6 +70,7 @@ check-engine-sql-dynamic.ts scanner yes CQ3/EO17 dynamic SQL in src/core/engine-
check-engine-sql-brands.ts scanner yes EO4/AR2 RLS read brands (TS AST + text): brand-key mentions outside engine-sql/brands.ts; casts onto ScopedRead/LegacyUnscopedRead or `as unknown as` executor types in src/; unscopedExecutor/LegacyUnscopedRead/scopedRead imports outside their allowlists, src/core/ops/** always denied
check-sync-run-state.ts scanner yes A17 (W4 sync): SyncRun mutable fields (non-readonly members of interface SyncRun) are never destructured or aliased into locals under src/commands/sync/; @checkpoint fields are assigned only in sync-run.ts (single owner); fixtures cover destructuring, aliasing, a parameter pattern in a nested dir, and an out-of-owner checkpoint write
check-layering.ts scanner yes EO10 layering (TS AST, every import form): src/core/engine-sql/** imports no engine façade; src/core/schema-migrations/** imports no migrate.ts
+check-durable-flush.ts scanner yes #5595/#5475 Windows durability (TS AST, scope-resolved): fsyncSync of a descriptor from a read-only or unreadable-flags openSync in src/ outside src/core/fs-durable.ts fails, file or directory; write-fd flushes pass; reasoned ALLOWLIST, stale entries fail; bad-directory fixture covers an O_RDONLY directory flush
check-schema-migrations-fresh.sh buildfresh exempt regenerates src/core/schema-migrations/registry.generated.ts + diffs; generator enforces filename/version/name cross-check and duplicate versions (unit: test/scripts/build-schema-migrations.test.ts)
check-schema-fresh.sh buildfresh exempt W2: regenerates the schema chain (fragments -> schema.sql regions -> schema-embedded -> PGLite template) into a temp dir and diffs every output; names the source to edit (unit: test/scripts/build-schema.test.ts)
check-retired-phrases.sh scanner yes W7 (refactor wave 1): retired contributor-workflow phrases (migrations array, two-engine SQL rule, CLI switch case, region policy, hand-synced PGLite schema) fail in CLAUDE.md, AGENTS.md, CONTRIBUTING.md, docs/, skills/; historical records and the porting kit exempt; GBRAIN_GUARD_ROOT seam; bad-<location> fixtures
diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.sh
index 3bbe877f09..240b3bf1f2 100755
--- a/scripts/run-verify-parallel.sh
+++ b/scripts/run-verify-parallel.sh
@@ -131,6 +131,9 @@ CHECKS=(
# EO10 (refactor wave 1): engine-sql/ and schema-migrations/ never import
# back up into the engine façades or migrate.ts (ESM TDZ cycles).
"check:layering"
+ # #5595/#5475: no fsync of a read-only descriptor outside src/core/fs-durable.ts
+ # (Windows refuses it with EPERM).
+ "check:durable-flush"
# Goal (a) (refactor wave 1): engine SQL only shrinks; baseline
# scripts/engine-sql-baseline.tsv.
"check:engine-sql-ratchet"
diff --git a/test/fixtures/guards/check-durable-flush.ts/bad-directory/src/core/persistence/bundle.ts b/test/fixtures/guards/check-durable-flush.ts/bad-directory/src/core/persistence/bundle.ts
new file mode 100644
index 0000000000..465b31fde8
--- /dev/null
+++ b/test/fixtures/guards/check-durable-flush.ts/bad-directory/src/core/persistence/bundle.ts
@@ -0,0 +1,8 @@
+import { closeSync, constants, fsyncSync, openSync } from 'node:fs';
+
+function flushBundleDirectory(directory: string): void {
+ const fd = openSync(directory, constants.O_RDONLY);
+ try { fsyncSync(fd); } finally { closeSync(fd); }
+}
+
+export function publish(directory: string): void { flushBundleDirectory(directory); }
diff --git a/test/fixtures/guards/check-durable-flush.ts/bad/src/core/writer.ts b/test/fixtures/guards/check-durable-flush.ts/bad/src/core/writer.ts
new file mode 100644
index 0000000000..5274fd95c9
--- /dev/null
+++ b/test/fixtures/guards/check-durable-flush.ts/bad/src/core/writer.ts
@@ -0,0 +1,7 @@
+import { chmodSync, closeSync, fsyncSync, openSync } from 'node:fs';
+
+export function publish(stagingPath: string, mode: number): void {
+ chmodSync(stagingPath, mode);
+ const fd = openSync(stagingPath, 'r');
+ try { fsyncSync(fd); } finally { closeSync(fd); }
+}
diff --git a/test/fixtures/guards/check-durable-flush.ts/good/src/core/fs-durable.ts b/test/fixtures/guards/check-durable-flush.ts/good/src/core/fs-durable.ts
new file mode 100644
index 0000000000..5e381f7a17
--- /dev/null
+++ b/test/fixtures/guards/check-durable-flush.ts/good/src/core/fs-durable.ts
@@ -0,0 +1,6 @@
+import { closeSync, fsyncSync, openSync } from 'node:fs';
+
+export function flushDirectory(path: string): void {
+ const fd = openSync(path, 'r');
+ try { fsyncSync(fd); } finally { closeSync(fd); }
+}
diff --git a/test/fixtures/guards/check-durable-flush.ts/good/src/core/writer.ts b/test/fixtures/guards/check-durable-flush.ts/good/src/core/writer.ts
new file mode 100644
index 0000000000..f4ea45f9fe
--- /dev/null
+++ b/test/fixtures/guards/check-durable-flush.ts/good/src/core/writer.ts
@@ -0,0 +1,16 @@
+import { closeSync, constants, fsyncSync, openSync, writeSync } from 'node:fs';
+import { dirname } from 'node:path';
+import { flushDirectory } from './fs-durable.ts';
+
+export function readHeader(path: string): number {
+ const fd = openSync(path, 'r');
+ try { return fd; } finally { closeSync(fd); }
+}
+
+export function writeDurably(path: string, bytes: Buffer): void {
+ const fd = openSync(path, 'wx', 0o600);
+ try { writeSync(fd, bytes); fsyncSync(fd); } finally { closeSync(fd); }
+ const out = openSync(`${path}.copy`, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);
+ try { fsyncSync(out); } finally { closeSync(out); }
+ flushDirectory(dirname(path));
+}
diff --git a/test/scripts/durable-flush-guard.test.ts b/test/scripts/durable-flush-guard.test.ts
new file mode 100644
index 0000000000..03b49b7a98
--- /dev/null
+++ b/test/scripts/durable-flush-guard.test.ts
@@ -0,0 +1,77 @@
+/**
+ * #5595/#5475: scripts/check-durable-flush.ts fails on an fsyncSync of a
+ * read-only descriptor (file or directory) anywhere in src/ outside
+ * src/core/fs-durable.ts, and leaves flushes of write descriptors alone.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+
+const REPO = resolve(import.meta.dir, '..', '..');
+const GUARD = join(REPO, 'scripts', 'check-durable-flush.ts');
+const dirs: string[] = [];
+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });
+
+function run(files: Record<string, string>, root?: string) {
+ const tree = root ?? mkdtempSync(join(tmpdir(), 'gbrain-durable-flush-'));
+ if (!root) dirs.push(tree);
+ for (const [rel, body] of Object.entries(files)) {
+ mkdirSync(join(tree, rel, '..'), { recursive: true });
+ writeFileSync(join(tree, rel), body);
+ }
+ const r = spawnSync(process.execPath, [GUARD], { encoding: 'utf8', env: { ...process.env, GBRAIN_GUARD_ROOT: tree } });
+ return { code: r.status, out: `${r.stdout}\n${r.stderr}` };
+}
+const IMPORTS = "import { closeSync, constants, fsyncSync, openSync, writeSync } from 'node:fs';\nimport * as fs from 'node:fs';\n";
+
+describe('check-durable-flush.ts', () => {
+ test.each([
+ ['a file opened with r', "export function f(p: string) {\n const fd = openSync(p, 'r');\n try { fsyncSync(fd); } finally { closeSync(fd); }\n}"],
+ ['flags omitted', "export function f(p: string) {\n const fd = openSync(p);\n fsyncSync(fd); closeSync(fd);\n}"],
+ ['an unguarded directory flush via O_RDONLY', "export function f(p: string) {\n const dir = openSync(p, constants.O_RDONLY | constants.O_DIRECTORY);\n try { fsyncSync(dir); } finally { closeSync(dir); }\n}"],
+ ['a let assigned inside try', "export function f(p: string) {\n let fd: number | undefined;\n try { fd = openSync(p, 'r'); fsyncSync(fd); } finally { if (fd !== undefined) closeSync(fd); }\n}"],
+ ['the fs namespace form', "export function f(p: string) {\n const fd = fs.openSync(p, 'r');\n fs.fsyncSync(fd); fs.closeSync(fd);\n}"],
+ ['an inline open', "export function f(p: string) { fsyncSync(openSync(p, 'r')); }"],
+ ['flags the guard cannot read', "export function f(p: string, flags: string) {\n const fd = openSync(p, flags);\n fsyncSync(fd); closeSync(fd);\n}"],
+ ])('%s fails with code, location, fix and docs anchor', (_label, body) => {
+ const r = run({ 'src/core/persistence/writer.ts': IMPORTS + body + '\n' });
+ expect(r.code).toBe(1);
+ expect(r.out).toContain('FAIL [durable_flush_read_handle]: src/core/persistence/writer.ts:');
+ expect(r.out).toContain('Fix: fsync the descriptor you wrote through before closing it, or call flushFile/flushDirectory from src/core/fs-durable.ts');
+ expect(r.out).toContain('See: docs/TESTING.md#durable-flush-guard');
+ });
+
+ test('write-descriptor flushes, fs-durable itself and same-named descriptors in other functions pass', () => {
+ const r = run({
+ 'src/core/fs-durable.ts': IMPORTS + "export function flushDirectory(p: string) { const fd = openSync(p, 'r'); try { fsyncSync(fd); } finally { closeSync(fd); } }\n",
+ 'src/core/backup/archive.ts': IMPORTS + [
+ "export function read(p: string) { const fd = openSync(p, 'r'); closeSync(fd); }",
+ "export function write(p: string, b: Buffer) { const fd = openSync(p, 'wx', 0o600); writeSync(fd, b); fsyncSync(fd); closeSync(fd); }",
+ "export function append(p: string) { const fd = openSync(p, 'r+'); fsyncSync(fd); closeSync(fd); }",
+ "export function exclusive(p: string) { const fd = openSync(p, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600); fsyncSync(fd); closeSync(fd); }",
+ "export function given(fd: number) { fsyncSync(fd); }",
+ ].join('\n') + '\n',
+ });
+ expect(r.out).toContain('check-durable-flush: ok');
+ expect(r.code).toBe(0);
+ });
+
+ test('a stale allowlist entry fails until it is removed', () => {
+ const r = run({ 'src/core/binary-self-update.ts': IMPORTS + "export function f(p: string) { const fd = openSync(p, 'r+'); fsyncSync(fd); closeSync(fd); }\n" });
+ expect(r.code).toBe(1);
+ expect(r.out).toContain('FAIL [durable_flush_stale_allowlist]: src/core/binary-self-update.ts');
+ });
+
+ test('the allowlisted self-upgrade flush stays allowed while it still needs migrating', () => {
+ const r = run({ 'src/core/binary-self-update.ts': IMPORTS + "export function f(p: string) { const fd = openSync(p, 'r'); fsyncSync(fd); closeSync(fd); }\n" });
+ expect(r.code).toBe(0);
+ });
+
+ test('the repository passes', () => {
+ const r = spawnSync(process.execPath, [GUARD], { encoding: 'utf8', env: { ...process.env, GBRAIN_GUARD_ROOT: REPO } });
+ expect(`${r.stdout}${r.stderr}`).toContain('check-durable-flush: ok');
+ expect(r.status).toBe(0);
+ });
+});