Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: name PowerShell timeouts and missed session-start packs; isolate the live-serve hook test; report loop-lag worst stretches

garrytan0e0daa7a89d3
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index bfd602ef89..ce8b61f816 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -273,6 +273,13 @@ jobs:
# on this row once a Bun release carries that change.
- name: Teardown bounds that used to park the Windows unit run (#5332)
run: bun test --timeout 120000 test/postgres-disconnect-bounded.test.ts
+ # Every earlier step runs under PowerShell 7, so Windows PowerShell 5.1, which the backup's owner-only protection
+ # launches, is still cold here: on #7409 its first starts outlasted the warm-up's 30 s and the protection's 15 s
+ # bounds. The cold path itself is covered by test/backup-powershell-warmup.serial.test.ts.
+ - name: Start Windows PowerShell once before the backup steps
+ if: runner.os == 'Windows'
+ timeout-minutes: 3
+ run: powershell.exe -NoLogo -NoProfile -NonInteractive -Command "exit 0"
- name: Backup archive round trip on this host (#5312)
run: bun test --timeout 60000 test/backup-archive-roundtrip-5312.test.ts
# The stale-socket sweep's native AF_UNIX reparse-point path exists only on Windows; macOS runs the POSIX cases
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1e66e446a3..e7466e60e9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,28 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.60.400.0] - 2026-10-23
+
+**A Windows backup whose PowerShell starts too slowly now says so instead of blaming the destination's permissions, and a post-compaction SessionStart whose serve did not answer in time now says so in its heartbeat.** Three CI flakes behind these are fixed without loosening any bound.
+
+### What changed
+
+| Situation | Before | Now |
+|---|---|---|
+| Windows backup: PowerShell 5.1 does not start within the protection step's 15 s (a cold machine's first starts) | refused with `private_backup_path_unavailable`: "this destination's permissions prevented…", which pointed at the wrong cause | refused with `private_backup_protection_timeout`: PowerShell did not start in time, run the backup again; a real ACL refusal still reports `private_backup_path_unavailable` |
+| SessionStart's context pack when a live serve answers nothing within the 1 s client timeout | no pack, heartbeat `ok` with no reason | no pack, heartbeat `degraded` / `ipc_unavailable`, as the user-prompt and compact hooks already report; no serve at all still reads `ok` |
+| CI: Windows security-regressions backup round trip | PowerShell 5.1 was still cold when the test ran (46 s: both bounds expired) | the job starts Windows PowerShell once before the backup steps; the cold path is covered by a simulated 50 s cold start |
+| CI: bootstrap-hook-under-serve in the serial pool | three pooled neighbours could starve the real serve past the hook's 1 s IPC timeout (Pin 3b at 1,008 ms) | runs on the sequential exclusive lane; the exclusive cap is 4 |
+| CI: a loop-lag bound that fails | printed only the reading | also prints the worst stretch's wall time and the thread's schedstat (time on a CPU, time runnable waiting) |
+
+### Itemized changes
+
+- `src/core/backup/private-path.ts`: a protection launch killed at its bound throws `private_backup_protection_timeout` (`test/backup-powershell-warmup.serial.test.ts`: the simulator keeps a virtual cold-start clock, so a warm-up killed at 30 s leaves the next launch cold).
+- `src/core/context/session-start-pack.ts`, `src/commands/hook.ts`: `ipcUnavailable` when a secret exists but the round trip failed (`test/hook-session-start-serve-wait.serial.test.ts`).
+- `scripts/run-serial-tests.sh`, `scripts/serial-files.tsv`, `test/scripts/serial-files.test.ts`: bootstrap-hook-under-serve joins `EXCLUSIVE_FILES`; the growth guard allows 4.
+- `.github/workflows/test.yml`: Windows PowerShell start step in security-regressions.
+- `test/helpers/cpu-time.ts`: `watchLoopLag({ reportAtMs })`; the five yield-bound tests pass their bound.
+
## [0.60.399.0] - 2026-10-23
**The dream summary, the `think --save` page and the drift report keep an edit made while they were being composed, and every overwrite is restorable; the timeline, mention and concept-provenance writers act only on the page revision they read (GBRA-161 PR 5).** These writers used to overwrite or delete against whatever the page held when they finished, so an edit made in between was lost and an overwritten page had no saved copy.
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 73260ecdc4..26e2914342 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -418,7 +418,7 @@ Test command tiers, each with a clear scope:
| `bun run ci:local` | Independent host gitleaks scans, then frozen dependencies, guards/typecheck, the complete serial and slow lanes, and four unit/E2E shards inside Docker. Each E2E shard has its own pgvector database; selected PgBouncer tests must execute against the transaction-mode pooler. Unit, serial, and slow lanes have database URL overrides unset. Any failed stage fails the command. Complete shard logs survive container teardown under `.context/ci-local-shards/`. `ci:local:diff` runs only gitleaks and the doc checks on a doc-only diff and the full gate otherwise; `--no-shard` runs unit/E2E sequentially. Doc-only diffs still require successful gitleaks scans. | Depends on the full corpus | Full local gate before shipping. |
| `bun run ci:ubicloud` | The `ci:local` lanes (gitleaks, guards/typecheck, serial, slow, unit, all E2E with required PgBouncer execution) fanned out across ephemeral Ubicloud VMs from one heaviest-first work queue; `ci:ubicloud:diff` takes the same doc-only fast path as `ci:local:diff`. Needs `UBICLOUD_API_KEY` or `UBICLOUD_API_TOKEN`, no local Docker. See "Ubicloud fan-out" below. | ~5 min | Full gate before shipping when a Ubicloud token is available. |
| `bun run test:slow` | Just the `*.slow.test.ts` set (intentional cold-path correctness checks). | seconds-to-minutes | When touching slow-path code. |
-| `bun run test:serial` | The `*.serial.test.ts` set listed in `scripts/serial-files.tsv`, one Bun process per file, run through a pool of concurrent per-file processes (`min(detect_cpus, 4)`, memory-adapted) heaviest-first from `scripts/serial-weights.json` (absent weights fall back to the corpus p75; scheduling only). The `EXCLUSIVE_FILES` in `scripts/run-serial-tests.sh` (machine-global state, at most 3) run sequentially after the pool, on shard 1 only. Per-test timeout 120s; each pooled file is killed at 300s. `SHARD=N/M` partitions pooled files by duration. Externally killed files get one sequential rescue run. Knobs: `GBRAIN_SERIAL_POOL=N` (`1` is fully sequential), `GBRAIN_SERIAL_FILE_TIMEOUT`. | a few minutes at pool=4 | Debugging quarantined files; CI's serial-tests job. |
+| `bun run test:serial` | The `*.serial.test.ts` set listed in `scripts/serial-files.tsv`, one Bun process per file, run through a pool of concurrent per-file processes (`min(detect_cpus, 4)`, memory-adapted) heaviest-first from `scripts/serial-weights.json` (absent weights fall back to the corpus p75; scheduling only). The `EXCLUSIVE_FILES` in `scripts/run-serial-tests.sh` (machine-global state or contention-critical timing, at most 4) run sequentially after the pool, on shard 1 only. Per-test timeout 120s; each pooled file is killed at 300s. `SHARD=N/M` partitions pooled files by duration. Externally killed files get one sequential rescue run. Knobs: `GBRAIN_SERIAL_POOL=N` (`1` is fully sequential), `GBRAIN_SERIAL_FILE_TIMEOUT`. | a few minutes at pool=4 | Debugging quarantined files; CI's serial-tests job. |
| `bun run test:e2e` | Real Postgres E2E. Requires Docker + `DATABASE_URL`. Sequential within a shard; `SHARD=N/M` fans out against separate databases (ci-local runs 4 containers). Activates the PGLite snapshot like every other runner (per-file cold-path opt-outs where the test asserts the path TO post-initSchema state), exporting it as an ABSOLUTE path so CLI children spawned with varying cwd still find it. | ~5-10min | Pre-ship; nightly. |
| `bun run test:compile-smoke` | Self-update integrity verify under a REAL `bun build --compile` binary, offline; also runs unconditionally in the serial lane. The unit suite mocks the network seams; this proves the dependency-free crypto/base64/JSON verify path survives compilation — the failure mode `sigstore-js` would have hit. | under 1s (one small compile) | When touching `src/core/binary-self-update.ts`; pre-ship on self-update changes. |
| `bun run regen:all` | Regenerates every generated artifact (schema, migrations registry, error-code docs, protocol blocks, tool catalog, skills manifest, structural suites, `llms.txt` last, and the others in `scripts/regen-all.ts`) offline and keyless, and lists what changed; a second run changes nothing. `--check` is read-only and runs in `verify` as `check:regen-all`. `--goldens` also regenerates the offline contract goldens, a deliberate act each PR justifies; Postgres goldens are named with their own commands. | about a minute | After any change a freshness check flags; before `/ship`. |
@@ -1390,7 +1390,7 @@ Triage rule: a `warn-pass` EXIT-HANG line in `.context/test-summary.txt` is NOT
- `*.test.ts`: the parallel unit loop.
- `*.slow.test.ts`: `bun run test:slow` only (intentional cold-path or long workloads that would dominate the fast loop). In CI they run in named slow jobs or inside the unit shards.
-- `*.serial.test.ts`: `bun run test:serial` after the parallel pass, one Bun process per file (`--max-concurrency=1` in a shared process still leaks `mock.module` through the module registry), with those processes pooled. Each file is listed with its class and reason in `scripts/serial-files.tsv` (see [When to quarantine](#when-to-quarantine-instead-of-fix)); machine-global files (launchd/cron) run on the sequential `EXCLUSIVE_FILES` lane, at most three. Do not put parallelism back on a serial file without fixing the contention root cause.
+- `*.serial.test.ts`: `bun run test:serial` after the parallel pass, one Bun process per file (`--max-concurrency=1` in a shared process still leaks `mock.module` through the module registry), with those processes pooled. Each file is listed with its class and reason in `scripts/serial-files.tsv` (see [When to quarantine](#when-to-quarantine-instead-of-fix)); machine-global files (launchd/cron) and contention-critical timing run on the sequential `EXCLUSIVE_FILES` lane, at most four. Do not put parallelism back on a serial file without fixing the contention root cause.
- `test/e2e/*.test.ts`: real-Postgres E2E, skipped when `DATABASE_URL` is unset. `test/phantom-redirect-engine-parity.test.ts` also rides this lane (its PGLite arm lives in `test/`; its Postgres arm needs a `DATABASE_URL` lane). `run-e2e.sh` wraps each file in a hard outer timeout (default 180s, `GBRAIN_E2E_FILE_TIMEOUT=<seconds>` overrides) because a blocking PGLite WASM call can outlive Bun's timer-based `--timeout`; LLM-bound Tier 2 files get four times the cap.
- `tests/heavy/*.sh`: ops-shape shell scripts (pg_upgrade matrix, RSS budget, read latency under sync, sync lock regression) costing minutes; `bun run test:heavy` or the nightly `heavy-tests.yml`. Files prefixed `_` are helpers the runner skips. `tests/heavy/README.md` says when a script belongs here instead of `*.slow.test.ts`.
- `test/fuzz/*.test.ts`: property-based fuzzing in the default loop (about 3s). Targets in `pure-validators.test.ts` must pass `scripts/check-fuzz-purity.sh` (in `verify`), which bundles each target and rejects `node:fs`, `node:child_process` and engine imports; others live in `mixed-validators.test.ts` or `filesystem-validators.test.ts`.
diff --git a/docs/guides/in-agent-setup.md b/docs/guides/in-agent-setup.md
index a857f7bfa0..cc5269a85f 100644
--- a/docs/guides/in-agent-setup.md
+++ b/docs/guides/in-agent-setup.md
@@ -187,7 +187,9 @@ paths, never changes existing parent permissions, and refuses with
or verified at the destination (some locations' inherited permissions prevent
it; a new path inside your user profile works). The destination must be on a
local filesystem with Windows ACL support, with built-in Windows PowerShell
-permitted. A busy database or a
+permitted. When Windows PowerShell does not start within the protection step's
+15 seconds (a slow first start on a cold machine), it refuses with
+`private_backup_protection_timeout` instead; run the backup again. A busy database or a
changing file fails the operation instead of publishing a success receipt.
Before the dump, the command removes gbrain's own IPC socket files
diff --git a/llms-full.txt b/llms-full.txt
index 99e2e527bb..0f86ed6d16 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -1212,7 +1212,9 @@ paths, never changes existing parent permissions, and refuses with
or verified at the destination (some locations' inherited permissions prevent
it; a new path inside your user profile works). The destination must be on a
local filesystem with Windows ACL support, with built-in Windows PowerShell
-permitted. A busy database or a
+permitted. When Windows PowerShell does not start within the protection step's
+15 seconds (a slow first start on a cold machine), it refuses with
+`private_backup_protection_timeout` instead; run the backup again. A busy database or a
changing file fails the operation instead of publishing a success receipt.
Before the dump, the command removes gbrain's own IPC socket files
diff --git a/scripts/run-serial-tests.sh b/scripts/run-serial-tests.sh
index e1fda9e9ba..33536ce77b 100755
--- a/scripts/run-serial-tests.sh
+++ b/scripts/run-serial-tests.sh
@@ -88,7 +88,7 @@ fi
# (machine-global state or contention-critical timing). They run sequentially
# AFTER the pool drains, without the wall-clock kill (a SIGKILL
# mid-registration could strand a real scheduled job). Growth guard:
-# test/scripts/serial-files.test.ts fails when this list grows past 3
+# test/scripts/serial-files.test.ts fails when this list grows past 4
# entries — every addition needs a justification comment like the entries
# below.
# ──────────────────────────────────────────────────────────────────────────
@@ -110,6 +110,12 @@ EXCLUSIVE_FILES=(
# restores master-era timing until the probe learns to retry ref-lock
# contention.
"test/brain-repo-durability.serial.test.ts"
+ # Pins a REAL serve's answer inside the hook's 1 s IPC client timeout (Pin 3
+ # and Pin 3b need an `ok` round trip). The serve answers in ~10 ms on an
+ # idle machine; pooled beside three heavy files its main thread is starved
+ # (160-1,200 ms with the file pinned to one core beside three CPU hogs), and
+ # Pin 3b timed out at 1,008 ms in #7409's full gate.
+ "test/bootstrap-hook-under-serve.serial.test.ts"
)
is_exclusive() {
diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsv
index fc83e65cc6..a22975f490 100644
--- a/scripts/serial-files.tsv
+++ b/scripts/serial-files.tsv
@@ -47,7 +47,7 @@ test/bootstrap-adopted-connection.serial.test.ts R1 R1: mutates process.env (GBR
test/bootstrap-dispatcher.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, CODEX_HOME, HOME, CLAUDE_CONFIG_DIR)
test/bootstrap-harness-lifecycle.serial.test.ts global-state global-state: patches process stdout/stderr/console
test/bootstrap-harness.serial.test.ts global-state global-state: patches process stdout/stderr/console
-test/bootstrap-hook-under-serve.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_SOURCE, GBRAIN_DATABASE_URL, DATABASE_URL (+3 more))
+test/bootstrap-hook-under-serve.serial.test.ts exclusive exclusive: pins a REAL serve's answer inside the hook's 1 s IPC client timeout (Pin 3 and Pin 3b need an ok round trip); pooled beside heavy files the serve's main thread is starved past it (Pin 3b timed out at 1,008 ms in #7409's full gate). Also mutates process.env (GBRAIN_HOME, GBRAIN_SOURCE, GBRAIN_DATABASE_URL, DATABASE_URL (+3 more))
test/bootstrap-interview.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
test/bootstrap-opencode-door.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, XDG_CONFIG_HOME)
test/bootstrap-plugin-lane.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, CODEX_HOME, CLAUDE_CONFIG_DIR, HOME)
diff --git a/src/commands/hook.ts b/src/commands/hook.ts
index 174d844116..4e9fbbda53 100644
--- a/src/commands/hook.ts
+++ b/src/commands/hook.ts
@@ -564,6 +564,7 @@ async function hookSessionStart(io: HookIo): Promise<number> {
awaitServe,
});
serveNotReady = res.serveNotReady;
+ if (res.ipcUnavailable && outcome === 'ok') { outcome = 'degraded'; reason = 'ipc_unavailable'; }
const pack = res.pack;
if (pack && !pack.ok && pack.error === 'source_mismatch' && outcome === 'ok') { outcome = 'degraded'; reason = 'source_mismatch'; } // #5941
if (pack?.ok && pack.degradedReason === 'server_budget' && outcome === 'ok') { outcome = 'degraded'; reason = 'server_budget'; }
diff --git a/src/core/backup/private-path.ts b/src/core/backup/private-path.ts
index 761c7f1ee5..c93a1d4c36 100644
--- a/src/core/backup/private-path.ts
+++ b/src/core/backup/private-path.ts
@@ -69,6 +69,7 @@ export function __resetPowerShellWarmupForTests(): void { warmed = null; }
export async function protectNewBackupPath(path: string, kind: 'directory' | 'file'): Promise<void> {
if (process.platform !== 'win32') return;
+ let timedOut = false;
try {
await warmPowerShell();
assertNoSymlinks(path);
@@ -80,7 +81,10 @@ export async function protectNewBackupPath(path: string, kind: 'directory' | 'fi
['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(protect, 'utf16le').toString('base64')], {
env: { ...process.env, GBRAIN_BACKUP_PRIVATE_PATH: path, GBRAIN_BACKUP_PRIVATE_KIND: kind },
encoding: 'utf8', timeout: 15_000, maxBuffer: 64 * 1024, windowsHide: true,
- }, (error, stdout) => error || inputFailed ? reject(error ?? new Error('Private path input failed')) : resolve(stdout));
+ }, (error, stdout) => {
+ if (error?.killed && !inputFailed) timedOut = true;
+ if (error || inputFailed) reject(error ?? new Error('Private path input failed')); else resolve(stdout);
+ });
const inputFailure = () => { inputFailed = true; child.kill(); };
if (!child.stdin) { inputFailure(); return; }
child.stdin.once('error', inputFailure);
@@ -92,6 +96,9 @@ export async function protectNewBackupPath(path: string, kind: 'directory' | 'fi
|| before.birthtimeNs !== after.birthtimeNs
|| (kind === 'directory' ? readdirSync(path).length !== 0 : after.size !== 0n || after.nlink !== 1n)) throw new Error('Private path verification failed');
} catch {
+ // A protection launch killed at its 15 s bound says nothing about this destination's permissions: Windows
+ // PowerShell did not start in time (a cold runner's first starts measured 30 s and more, after the warm-up).
+ if (timedOut) throw new AgentInstallError('private_backup_protection_timeout', "Windows PowerShell did not start within 15 seconds, so GBrain could not establish owner-only access (plus SYSTEM) on this new path. No payload was written to it. This is usually a slow first start of PowerShell on this machine; run the backup again. Existing files and parent permissions were not changed.");
// #5312 B(i): the text names what was observed (protection attempted and verified by the script above, and it
// did not hold here), not a categorical rule about drive roots; the user profile is the destination that works.
throw new AgentInstallError('private_backup_path_unavailable', "This destination's permissions prevented GBrain from establishing owner-only access (plus SYSTEM); use a new path inside your user profile. No payload was written to this new path. The destination must be on a local filesystem with Windows ACL support, with built-in Windows PowerShell available and permitted. Existing files and parent permissions were not changed.");
diff --git a/src/core/context/session-start-pack.ts b/src/core/context/session-start-pack.ts
index 4829f86ee9..662ceccac0 100644
--- a/src/core/context/session-start-pack.ts
+++ b/src/core/context/session-start-pack.ts
@@ -45,6 +45,8 @@ export interface SessionStartPackResult {
pack: ContextPackResponse | null;
/** The wait ran out before a serve answered. */
serveNotReady: boolean;
+ /** A serve's secret exists but its round trip failed or outlasted the client timeout. */
+ ipcUnavailable?: boolean;
}
/**
@@ -72,7 +74,7 @@ export async function requestSessionStartPack(
}, { timeoutMs: Math.min(CONTEXT_PACK_CLIENT_TIMEOUT_MS, remaining) })
: IPC_UNAVAILABLE;
if (res !== IPC_UNAVAILABLE) return { pack: 'degraded' in res ? null : res as ContextPackResponse, serveNotReady: false };
- if (!opts.awaitServe) return { pack: null, serveNotReady: false };
+ if (!opts.awaitServe) return { pack: null, serveNotReady: false, ...(secret ? { ipcUnavailable: true } : {}) };
await new Promise((r) => setTimeout(r, POLL_MS));
}
}
diff --git a/test/backup-powershell-warmup.serial.test.ts b/test/backup-powershell-warmup.serial.test.ts
index d6f73cec2a..de43f80208 100644
--- a/test/backup-powershell-warmup.serial.test.ts
+++ b/test/backup-powershell-warmup.serial.test.ts
@@ -12,27 +12,28 @@ type Launch = { kind: 'warmup' | 'protection'; timeout: number | undefined; exec
type Outcome = 'ok' | 'timeout' | 'error' | 'throw';
/**
- * Simulates Windows PowerShell on any host. `coldMs` is how long the first
- * launch in the process takes: a launch whose bound is shorter fails as
- * execFile's timeout kill does. Later launches are warm. `warmup` forces the
- * warm-up launch's outcome instead; `protection: 'timeout'` makes every
- * protection launch hang past its bound.
+ * Simulates Windows PowerShell on any host. `coldMs` is how long PowerShell
+ * takes to start for the first time, on a virtual clock: each launch waits for
+ * what is left of it and fails as execFile's timeout kill does when its bound
+ * is shorter, so a warm-up killed at its bound leaves the next launch still
+ * cold. `warmup` forces the warm-up launch's outcome instead; `protection`
+ * forces every protection launch to hang past its bound or fail.
*/
-function simulatePowerShell(options: { coldMs?: number; warmup?: Outcome; protection?: 'timeout' }) {
+function simulatePowerShell(options: { coldMs?: number; warmup?: Outcome; protection?: 'timeout' | 'error' }) {
const launches: Launch[] = [];
const execute = childProcess.execFile;
- let cold = true;
+ let elapsed = 0;
const spy = spyOn(childProcess, 'execFile').mockImplementation(new Proxy(execute, {
apply(target, thisArg, args) {
if (args[0] !== powershell) return Reflect.apply(target, thisArg, args);
const launchOptions = args[2] as childProcess.ExecFileOptionsWithStringEncoding;
const kind = launchOptions.env?.GBRAIN_BACKUP_PRIVATE_PATH ? 'protection' : 'warmup';
launches.push({ kind, timeout: launchOptions.timeout, executable: args[0], args: [...args[1]] });
- const startup = cold ? options.coldMs ?? 0 : 0;
- cold = false;
+ const startup = Math.max(0, (options.coldMs ?? 0) - elapsed);
const forced = kind === 'warmup' ? options.warmup : options.protection;
if (forced === 'throw') throw new Error('injected warm-up launch failure');
const timedOut = forced === 'timeout' || startup > (launchOptions.timeout ?? Infinity);
+ elapsed += timedOut ? launchOptions.timeout ?? 0 : startup;
const done = args[3];
return Reflect.apply(target, thisArg, [process.execPath, ['--no-env-file', '--eval',
"process.stdin.resume(); process.stdin.on('end', () => process.stdout.write(process.env.GBRAIN_BACKUP_PRIVATE_PATH ? 'private' : ''))"],
@@ -99,6 +100,28 @@ test('a protection timeout after the warm-up stays final: one launch, no retry',
try {
const result = await protectFresh();
expect(shell.launches.map(launch => launch.kind)).toEqual(['warmup', 'protection']);
+ expect(result.error).toMatchObject({ code: 'private_backup_protection_timeout' });
+ } finally { shell.restore(); }
+});
+
+// security-regressions (windows-latest, Bun 1.4.0) on #7409: the round trip failed after 46,063 ms, the warm-up's 30 s
+// bound plus the protection launch's 15 s, and reported the destination's permissions.
+test('a 50 s cold start outlasts both bounds and is reported as a PowerShell timeout, not a permissions refusal', async () => {
+ privacy.__resetPowerShellWarmupForTests();
+ const shell = simulatePowerShell({ coldMs: 50_000 });
+ try {
+ const result = await protectFresh();
+ expect(shell.launches.map(launch => launch.kind)).toEqual(['warmup', 'protection']);
+ expect(result.error).toMatchObject({ code: 'private_backup_protection_timeout' });
+ expect((result.error as Error).message).toContain('did not start within 15 seconds');
+ } finally { shell.restore(); }
+});
+
+test('a protection launch that fails without a timeout still reports the destination refusal', async () => {
+ privacy.__resetPowerShellWarmupForTests();
+ const shell = simulatePowerShell({ protection: 'error' });
+ try {
+ const result = await protectFresh();
expect(result.error).toMatchObject({ code: 'private_backup_path_unavailable' });
} finally { shell.restore(); }
});
diff --git a/test/helpers/cpu-time.ts b/test/helpers/cpu-time.ts
index cf5f39b32e..77554f0017 100644
--- a/test/helpers/cpu-time.ts
+++ b/test/helpers/cpu-time.ts
@@ -1,3 +1,5 @@
+import { readFileSync } from 'node:fs';
+
/** The calling thread's CPU time, in milliseconds from an arbitrary origin. */
export function threadCpuNow(): number {
const used = process.threadCpuUsage();
@@ -17,10 +19,41 @@ export function spinCpuMs(ms: number): void {
* on a starved helper thread or on a spawned child that has not reached exec yet. On a 4-vCPU CI shard a 60 ms
* stretch read 133 ms that way (#6712 PR 4b, test/sync-pass-shared-budget-6712.test.ts).
*/
-export function watchLoopLag(intervalMs = 5): { stop(): { maxLag: number; ticks: number } } {
- let last = threadCpuNow(), maxLag = 0, ticks = 0;
- const timer = setInterval(() => { const now = threadCpuNow(); maxLag = Math.max(maxLag, now - last); last = now; ticks++; }, intervalMs);
- return { stop: () => { clearInterval(timer); return { maxLag: Math.max(maxLag, threadCpuNow() - last), ticks }; } };
+export function watchLoopLag(opts: { intervalMs?: number; reportAtMs?: number } = {}): { stop(): { maxLag: number; ticks: number } } {
+ const { intervalMs = 5, reportAtMs } = opts;
+ // With reportAtMs, a worst stretch at or past it prints its wall time and the kernel's schedstat for the thread (time on
+ // a CPU, time runnable but waiting), so a CI failure says whether the thread worked longer, ran slower or waited.
+ const sched = reportAtMs === undefined ? null : schedstat();
+ const snap = () => ({ cpu: threadCpuNow(), wall: performance.now(), ...(sched ? schedstat() : null) });
+ let last = snap(), maxLag = 0, ticks = 0, worst = '';
+ const take = () => {
+ const now = snap();
+ if (now.cpu - last.cpu > maxLag) {
+ maxLag = now.cpu - last.cpu;
+ if (reportAtMs !== undefined) worst = `${maxLag.toFixed(1)} ms thread CPU, ${(now.wall - last.wall).toFixed(1)} ms wall`
+ + (sched && now.run !== undefined && last.run !== undefined ? `, schedstat ${(now.run - last.run).toFixed(1)} ms on a CPU and ${(now.wait! - last.wait!).toFixed(1)} ms runnable waiting` : '');
+ }
+ last = now;
+ };
+ const timer = setInterval(() => { take(); ticks++; }, intervalMs);
+ return {
+ stop: () => {
+ clearInterval(timer);
+ take();
+ if (reportAtMs !== undefined && Math.round(maxLag) >= reportAtMs) console.error(`[watchLoopLag] worst stretch: ${worst}`);
+ return { maxLag, ticks };
+ },
+ };
+}
+
+/** The calling thread's /proc schedstat in ms (Linux): time on a CPU and time runnable but waiting; null elsewhere. */
+function schedstat(): { run: number; wait: number } | null {
+ try {
+ const [run, wait] = readFileSync('/proc/thread-self/schedstat', 'utf8').split(' ').map(Number);
+ return Number.isFinite(run) && Number.isFinite(wait) ? { run: run! / 1e6, wait: wait! / 1e6 } : null;
+ } catch {
+ return null;
+ }
}
/**
diff --git a/test/hook-session-start-serve-wait.serial.test.ts b/test/hook-session-start-serve-wait.serial.test.ts
index b96df6b863..bfa91a28c4 100644
--- a/test/hook-session-start-serve-wait.serial.test.ts
+++ b/test/hook-session-start-serve-wait.serial.test.ts
@@ -13,11 +13,13 @@
*/
import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { createServer } from 'node:net';
import type net from 'node:net';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { runHook, readHeartbeatTail, SESSION_START_DEADLINE_MS, SESSION_START_SERVE_WAIT_DEADLINE_MS } from '../src/commands/hook.ts';
import {
+ CONTEXT_PACK_CLIENT_TIMEOUT_MS,
ensureIpcSecretForConfig,
resolveSocketPathForConfig,
startResolveIpcServer,
@@ -226,3 +228,32 @@ describe('SessionStart does not wait when no serve is being started', () => {
expect((await sessionStart('startup')).out).toContain(FACT);
}, 20_000);
});
+
+describe('SessionStart names a pack the serve did not deliver in time', () => {
+ // #7409's gate: a starved serve answered the post-compaction pack after the client timeout, and the heartbeat still
+ // read ok with no reason, so the empty pack named nothing.
+ test('a live serve that answers nothing within the client timeout: no pack, heartbeat degraded ipc_unavailable', async () => {
+ const cfg = pgliteConfig();
+ writeConfig(cfg);
+ ensureIpcSecretForConfig(cfg);
+ // A serve whose main thread is starved: it accepts the connection and answers nothing within the client timeout.
+ const server = createServer(() => {});
+ await new Promise<void>(resolve => server.listen(resolveSocketPathForConfig(cfg, 'resolve')!, resolve));
+ servers.push(server);
+ const { out, ms } = await sessionStart('compact');
+ expect(ms).toBeGreaterThanOrEqual(CONTEXT_PACK_CLIENT_TIMEOUT_MS);
+ expect(out).not.toContain(FACT);
+ const hb = await lastSessionStartHeartbeat();
+ expect(hb?.outcome).toBe('degraded');
+ expect(hb?.reason).toBe('ipc_unavailable');
+ }, 20_000);
+
+ test('no serve was ever started (no secret): the heartbeat stays ok', async () => {
+ const cfg = pgliteConfig();
+ writeConfig(cfg);
+ await sessionStart('compact');
+ const hb = await lastSessionStartHeartbeat();
+ expect(hb?.outcome).toBe('ok');
+ expect(hb?.reason).toBeUndefined();
+ }, 20_000);
+});
diff --git a/test/scripts/serial-files.test.ts b/test/scripts/serial-files.test.ts
index ba09373e4c..97ce4e6d57 100644
--- a/test/scripts/serial-files.test.ts
+++ b/test/scripts/serial-files.test.ts
@@ -88,9 +88,11 @@ describe('EXCLUSIVE_FILES (pooled-runner opt-out) guards', () => {
it('the exclusive list does not silently grow (quarantine-growth guard)', () => {
// Exclusivity re-serializes the runner one file at a time — the exact
// 8.5-minute disease the pool removed. Each entry must carry a
- // justification comment; past 3 entries, stop and rethink the design
+ // justification comment; past 4 entries, stop and rethink the design
// (per-file PATH shims are usually the right fix) instead of quarantining.
- expect(entries().length).toBeLessThanOrEqual(3);
+ // The fourth entry (#7409) pins a live serve's answer inside the hook's
+ // 1 s IPC timeout, which pooled neighbours starve.
+ expect(entries().length).toBeLessThanOrEqual(4);
});
it('a missing exit sentinel is a failure, never a silent pass', () => {
diff --git a/test/sync-pass-batch-entries-6712.test.ts b/test/sync-pass-batch-entries-6712.test.ts
index 754d71384a..0257281d8a 100644
--- a/test/sync-pass-batch-entries-6712.test.ts
+++ b/test/sync-pass-batch-entries-6712.test.ts
@@ -45,7 +45,7 @@ describe('GBRA-133 PR 2b: a first sync builds its batch in linear time', () => {
const stop = new AbortController();
window.open = false;
installFaultHook(async point => {
- if (point === 'sync:batch_entries' && !lag) { lag = watchLoopLag(); window.open = inWindow(); }
+ if (point === 'sync:batch_entries' && !lag) { lag = watchLoopLag({ reportAtMs: MAX_LAG_MS }); window.open = inWindow(); }
if (point === 'sync:after_freeze' && lag && maxLag === undefined) { window.open = false; maxLag = lag.stop().maxLag; stop.abort(); }
});
await performManagedSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true, signal: stop.signal }).catch(() => undefined);
diff --git a/test/sync-pass-loop-lag-6712.test.ts b/test/sync-pass-loop-lag-6712.test.ts
index a0374b2bf0..e4cdb28a22 100644
--- a/test/sync-pass-loop-lag-6712.test.ts
+++ b/test/sync-pass-loop-lag-6712.test.ts
@@ -50,7 +50,7 @@ describe('#6712 PR 4b ruling 4: a level read yields to the event loop', () => {
for (let read = 0; read < READS; read++) {
let level: Awaited<ReturnType<typeof readShadowLevel>>;
let maxLag = 0, ticks = 0;
- const lag = watchLoopLag();
+ const lag = watchLoopLag({ reportAtMs: MAX_LAG_MS });
try {
level = await readShadowLevel(engine, { sourceId: 'default', context });
} finally {
diff --git a/test/sync-pass-patched-domain-yield.test.ts b/test/sync-pass-patched-domain-yield.test.ts
index f078ecd3fa..f3a69a6ba4 100644
--- a/test/sync-pass-patched-domain-yield.test.ts
+++ b/test/sync-pass-patched-domain-yield.test.ts
@@ -36,7 +36,7 @@ isolatedTest(import.meta.path, 'a confirm round that patches every page yields;
const full = await levelDomain(input());
const expected = { domain: [...full.domain].sort(), byOrigin: [...full.byOrigin].sort() };
costly = true;
- const lag = watchLoopLag();
+ const lag = watchLoopLag({ reportAtMs: MAX_LAG_MS });
let patched: Awaited<ReturnType<typeof levelDomain>>, maxLag = 0;
try { patched = await levelDomain(input({ cache: domainCache(full, 'tree'), changed: { rewritten: [], from: 0 }, oldKey: sourcePath => sourcePath })); }
finally { ({ maxLag } = lag.stop()); }
diff --git a/test/sync-pass-shared-budget-6712.test.ts b/test/sync-pass-shared-budget-6712.test.ts
index c122b5f20c..269a8f2e9e 100644
--- a/test/sync-pass-shared-budget-6712.test.ts
+++ b/test/sync-pass-shared-budget-6712.test.ts
@@ -74,7 +74,7 @@ for (const backend of testBackends()) {
// Lag as the thread's own CPU between timer runs: the stretches the read holds, not what a loaded VM adds.
let level: Awaited<ReturnType<typeof readShadowLevel>>;
let maxLag = 0;
- const lag = watchLoopLag();
+ const lag = watchLoopLag({ reportAtMs: MAX_LAG_MS });
try {
level = await readShadowLevel(engine, { sourceId: 'default', context });
} finally {
diff --git a/test/sync-probe-dirtiness-yield.test.ts b/test/sync-probe-dirtiness-yield.test.ts
index 8136c0b7df..4e8000aee2 100644
--- a/test/sync-probe-dirtiness-yield.test.ts
+++ b/test/sync-probe-dirtiness-yield.test.ts
@@ -37,7 +37,7 @@ isolatedTest(import.meta.path, 'the dirtiness probe yields between file reads; n
const read = discovery.readSyncFile;
let reads = 0;
spies.push(spyOn(discovery, 'readSyncFile').mockImplementation(((...args: Parameters<typeof read>) => { reads++; spinCpuMs(READ_CPU_MS); return read(...args); }) as typeof read));
- const lag = watchLoopLag();
+ const lag = watchLoopLag({ reportAtMs: MAX_LAG_MS });
let probed: Awaited<ReturnType<typeof probeDirtiness>>, maxLag = 0;
try { probed = await probeDirtiness(root, root, [...tree.keys()], tree, index); }
finally { ({ maxLag } = lag.stop()); }