Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Lane G: streamed secret scan owns claims by match start; large-file before stage never wedges recovery; retained-heap bound on managed sync

garrytana95035f4f3c6
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 939134c397..da7f81de32 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -2263,7 +2263,9 @@ source.
recovery whose prior file is over the 24 MiB single-string ceiling. Its prior
bytes are kept as a staged copy beside the file (named in the record, with its
SHA-256) instead of inside the record, and the preview's diff would read both
-files whole, so nothing was changed. Inspect the request read-only with
+files whole, so nothing was changed. The preview lists such a recovery under
+`refused` with this code and still lists the source's other recoveries; with
+`--request-id` naming it, the command refuses with this code. Inspect the request read-only with
`gbrain sources writer status --source <id> --json`, ask the user which version
to keep, put those bytes at the canonical path by hand (the staged copy holds
the prior bytes; never delete it), and let the resident writer finish the
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 77b39ff41b..80e4eff9dd 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -661,7 +661,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: 'TBD', text: 'A write that stores a page in segments says in its receipt whether search sees it: `searchable: true` when it commits (every new page up to 4 MiB and every rewrite), or `searchable: "pending"` for a larger new page while its chunks are built after commit, with `searchable_retry_after_ms` and a `searchable_fix` that reads the receipt again (`get_write_request`) until it says `searchable: true`. A new page up to 4 MiB was previously searchable only once a post-commit build finished.' },
{ since: 'TBD', text: '`gbrain projections drain` now builds pages stored in segments whose post-commit build never ran or died, skipping one another process is still building (claim renewed within 60 s), so a brain with no resident writer can make a large new page searchable. A pending receipt\'s `searchable_fix` names it as the fallback after the re-read wait, and doctor `text_projection_readiness` counts such pages (`segmented_pending`) and points to it.' },
{ since: 'TBD', text: 'The maintenance sweep (`gbrain sweep`, the serve idle sweep) links a page stored in segments on its own after the inline pages, smallest first, and stops reading one at its time budget; a page that does not fit is skipped with reason `budget_deferred:segmented_page`, left for `gbrain extract --stale`, and later sweeps in the same process skip it (`segmented_page_deferred`) until it changes. Derived passes over a page stored in segments no longer refuse a page of short lines or dated bullets over 8 MiB with `page_body_segmented`.' },
- { since: 'TBD', text: 'Deleting and restoring a page over 24 MiB on a source backed by files is now lossless up to the page ceiling (`pages.max_bytes`). `restore_page` and `gbrain restore` write the file back byte for byte by streaming it from the stored segments into its staging file, including a file over the 25 MiB pre-push scan cap (the restore used to refuse with `request_too_large`, so the file a soft delete had removed could not be put back on disk). A delete or restore that replaces or removes a file over 24 MiB keeps the prior file as a staged copy beside it (a hidden `.<sha256>.tmp.before-<uuid>` file) until the write commits, named in its recovery record by path and SHA-256 instead of embedded in it: the record stays a few hundred bytes, the recovery reservation counts the file once (a 90 MiB delete used to need 283 MB against the 256 MiB `persistence.limits.worktree_recovery_bytes` budget and was refused), and a crash between removing the file and committing renames the copy back. A page whose file plus its staging does not fit that budget (a Postgres page near the 256 MiB ceiling) is still refused with `request_too_large` before anything is touched. `gbrain repair stuck-recovery` refuses such a recovery with `recovery_large_file_unsupported` (resolve it by hand; the resident writer finishes it).' },
+ { since: 'TBD', text: 'Deleting and restoring a page over 24 MiB on a source backed by files is now lossless up to the page ceiling (`pages.max_bytes`). `restore_page` and `gbrain restore` write the file back byte for byte by streaming it from the stored segments into its staging file, including a file over the 25 MiB pre-push scan cap (the restore used to refuse with `request_too_large`, so the file a soft delete had removed could not be put back on disk). A delete or restore that replaces or removes a file over 24 MiB keeps the prior file as a staged copy beside it (a hidden `.<sha256>.tmp.before-<uuid>` file) until the write commits, named in its recovery record by path and SHA-256 instead of embedded in it: the record stays a few hundred bytes, the recovery reservation counts the file once (a 90 MiB delete used to need 283 MB against the 256 MiB `persistence.limits.worktree_recovery_bytes` budget and was refused), and a crash between removing the file and committing renames the copy back. A page whose file plus its staging does not fit that budget (a Postgres page near the 256 MiB ceiling) is still refused with `request_too_large` before anything is touched. The copy is written under a temporary name and renamed once it is complete and flushed, so a crash while it is being copied leaves nothing the recovery waits on: recovery removes a copy that never got its name, and drops a copy that is incomplete while the file still holds its prior bytes. `gbrain repair stuck-recovery` lists such a recovery as refused with `recovery_large_file_unsupported` (resolve it by hand; the resident writer finishes it) and still previews the other recoveries of the source.' },
{ since: 'TBD', text: 'A page purge (`delete_page` with `purge: true`, `gbrain delete --purge` and the 72-hour hard delete of soft-deleted pages) of a page stored in segments no longer breaks another page\'s write that is still being prepared with some of the same text: the purge keeps exactly the segment texts such a write staged, and still deletes every other text only the purged page used. `restore_page` of a page over 24 MiB whose old chunks were still waiting to be removed returns `projection: "pending"` and makes the page searchable once they are gone, instead of showing the old text in search.' },
{ since: 'TBD', text: 'Chunks of a page stored in segments keep a Markdown heading with the text after it, so a section appended after a full last chunk re-embeds only its own chunk (was two). Inline pages chunk as before.' },
{ since: 'TBD', text: 'The pre-push secret scan (`gbrain sources push` and the automatic pushes) now scans a staged file over 25 MiB in bounded 8 Mi-character windows streamed from git, instead of refusing the push as `blocked_unscannable`: a clean large file pushes, and one holding a secret is refused as `blocked_secrets` naming its file and line. A staged file over 512 MiB still refuses as `blocked_unscannable`.' },
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 459ddfe066..f5cab21ab2 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -163,7 +163,8 @@ async function stageLargeFiles(engine: BrainEngine, row: WriteRequest, file: Pag
const before = record.staging?.before, publication = record.staging?.publication;
if (!before && !isStreamedContent(file.content)) return;
await withFilesystemPublication([file.root], async () => {
- if (before && !stageBeforeCopy(file.path, before, record.mode)) throw localEditRefusal('The canonical file changed after preparation.', row, false, 'while its prior bytes were being staged');
+ if (before && !await stageBeforeCopy(file.path, before, record.mode,
+ phase => faultPoint(`large_file:${phase}`, { requestId: row.request_id, sourceId: row.source_id, operation: row.operation }))) throw localEditRefusal('The canonical file changed after preparation.', row, false, 'while its prior bytes were being staged');
if (isStreamedContent(file.content)) {
prepareParent(file);
await stageStreamedContent(engine, file.path, file.content, publication!, record.mode);
@@ -582,9 +583,39 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostId
const actual = current.recovery.version === 2 ? bundleFileHash(record) : fileHash(record.path);
if (actual !== record.beforeHash && actual !== record.afterHash) throw unexpectedRecoveryBytes('Canonical recovery bytes changed outside publication.', current, 'was edited outside gbrain and');
}
+ // A terminal outcome's prior-file copy is dropped unread when its canonical file still holds the prior bytes.
await withFilesystemPublication([...new Set(records.map(record => record.root))], async () => {
- for (const record of records) cleanupRecoveryStaging(record, { keepBefore: !isTerminal(current) });
+ for (const record of records) cleanupRecoveryStaging(record, { keepBefore: !isTerminal(current),
+ priorIntact: isTerminal(current) && !!record.staging?.before && fileHash(record.path) === record.beforeHash });
});
+ // A live request's restoration runs inside this guard too, so a refusal there is recorded as its blocked reason.
+ if (!isTerminal(current)) for (let index = 0; index < records.length; index++) {
+ const record = records[index];
+ hooks.fileBoundary?.('before_restore', current, index);
+ const actual = current.recovery.version === 2 ? bundleFileHash(record) : fileHash(record.path);
+ if (actual !== record.beforeHash && actual !== record.afterHash) throw unexpectedRecoveryBytes('Canonical recovery bytes changed during restoration.', current, 'changed while recovery was restoring it and');
+ if (record.staging?.before) {
+ await withFilesystemPublication([record.root], async () => {
+ if (actual === record.afterHash && actual !== record.beforeHash) restoreBeforeStage(record, phase => hooks.fileBoundary?.(`restoration_${phase}`, current, index));
+ else cleanupRecoveryStaging(record, { priorIntact: actual === record.beforeHash });
+ });
+ } else if (actual === record.afterHash && actual !== record.beforeHash) {
+ await withFilesystemPublication([record.root], async () => {
+ const file = { path: record.path, root: record.root, content: record.before === null ? null : Buffer.from(record.before, 'base64') };
+ if (current.recovery!.version === 2) {
+ const restored = { ...record, beforeHash: record.afterHash, afterHash: record.beforeHash,
+ mode: record.afterHash === null ? null : record.afterMode ?? record.mode, afterMode: record.mode ?? undefined,
+ staging: { publication: record.staging?.restoration } };
+ stageBundleFile(file, restored);
+ if (file.content !== null) hooks.fileBoundary?.('restoration_staging_flushed', current, index);
+ publishStagedBundleFile(restored, phase => hooks.fileBoundary?.(`restoration_${phase}`, current, index));
+ } else publishFile(file, record.staging?.restoration?.path,
+ () => hooks.fileBoundary?.('restoration_staging_flushed', current, index), record.mode);
+ });
+ }
+ hooks.fileBoundary?.('after_restore', current, index);
+ assertRecoveryStagingAbsent(record);
+ }
}
catch (error) {
if (!(error instanceof OperationError) || !['unexpected_staging_bytes','unexpected_file_bytes','storage_error'].includes(error.code)) throw error;
@@ -597,33 +628,6 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostId
// A delivered or durable terminal outcome is immutable. Only its known
// temporary files are cleaned; its canonical file is never restored.
if (isTerminal(current)) return { ...current, blocked_reason: null };
- for (let index = 0; index < records.length; index++) {
- const record = records[index];
- hooks.fileBoundary?.('before_restore', current, index);
- const actual = current.recovery.version === 2 ? bundleFileHash(record) : fileHash(record.path);
- if (actual !== record.beforeHash && actual !== record.afterHash) throw unexpectedRecoveryBytes('Canonical recovery bytes changed during restoration.', current, 'changed while recovery was restoring it and');
- if (record.staging?.before) {
- await withFilesystemPublication([record.root], async () => {
- if (actual === record.afterHash && actual !== record.beforeHash) restoreBeforeStage(record, phase => hooks.fileBoundary?.(`restoration_${phase}`, current, index));
- else cleanupRecoveryStaging(record);
- });
- } else if (actual === record.afterHash && actual !== record.beforeHash) {
- await withFilesystemPublication([record.root], async () => {
- const file = { path: record.path, root: record.root, content: record.before === null ? null : Buffer.from(record.before, 'base64') };
- if (current.recovery!.version === 2) {
- const restored = { ...record, beforeHash: record.afterHash, afterHash: record.beforeHash,
- mode: record.afterHash === null ? null : record.afterMode ?? record.mode, afterMode: record.mode ?? undefined,
- staging: { publication: record.staging?.restoration } };
- stageBundleFile(file, restored);
- if (file.content !== null) hooks.fileBoundary?.('restoration_staging_flushed', current, index);
- publishStagedBundleFile(restored, phase => hooks.fileBoundary?.(`restoration_${phase}`, current, index));
- } else publishFile(file, record.staging?.restoration?.path,
- () => hooks.fileBoundary?.('restoration_staging_flushed', current, index), record.mode);
- });
- }
- hooks.fileBoundary?.('after_restore', current, index);
- assertRecoveryStagingAbsent(record);
- }
// Withdrawal is authoritative DB state and is never rolled back here.
const failure: PublicationFailure | undefined = terminalError ?? (current.error_code ? {code:current.error_code,message:current.error_message ?? 'Publication failed before database completion.',
...(current.error_detail ? { detail: current.error_detail as unknown as PublicationFailureDetail } : {})} : undefined);
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index e0a0d9bc41..311d2f2c86 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -4,7 +4,7 @@
* recovery path must finish: publication boundaries, after an effect's side
* effect but before its completion is recorded, before a recovery record is
* cleared, between sync checkpoints, after the consumer prepared a
- * claimed request, (`sync:after_freeze`) after a managed sync import entry is frozen and before it is admitted, (`lane:applied`) when a lane group has applied its pages and waits for its commit turn, (`stuck_recovery:*`) between the steps of a stuck-recovery resolution, and (`segmented:*`) between the stages of a segmented write. Production never installs a hook, so every call is a
+ * claimed request, (`sync:after_freeze`) after a managed sync import entry is frozen and before it is admitted, (`lane:applied`) when a lane group has applied its pages and waits for its commit turn, (`stuck_recovery:*`) between the steps of a stuck-recovery resolution, (`segmented:*`) between the stages of a segmented write, and (`large_file:*`) while a large prior file is copied to its before stage. Production never installs a hook, so every call is a
* no-op there; the gate's workers install one that SIGKILLs or stalls the
* process at a chosen point.
*/
@@ -27,7 +27,10 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect
| 'stuck_recovery:backed_up' | 'stuck_recovery:written' | 'stuck_recovery:abandoned' | 'stuck_recovery:recovered'
// Wave B segmented writes (spec 3.4 crash windows): after the texts, the staged manifest rows and the staged chunks of a
// preparation, after the generation flip (inside the publication transaction), and after a projection staged its chunks (before its seal).
- | 'segmented:texts_staged' | 'segmented:manifest_staged' | 'segmented:chunks_staged' | 'segmented:flipped' | 'segmented:projection_staged';
+ | 'segmented:texts_staged' | 'segmented:manifest_staged' | 'segmented:chunks_staged' | 'segmented:flipped' | 'segmented:projection_staged'
+ // A prior file over the single-string ceiling copied to its before stage (large-file.ts `stageBeforeCopy`): after the copy is
+ // written under its temporary name (unverified, unflushed: a crash during the copy) and once it is flushed, before its rename.
+ | 'large_file:stage_copying' | 'large_file:stage_flushed';
/**
* `signal` (#6278, `consumer:preparing` only): the preparation's abort signal, so
* a stalling hook can model both the reporter's cases: a preparer that honours
diff --git a/src/core/persistence/large-file.ts b/src/core/persistence/large-file.ts
index 8cca9cab42..93eb954b12 100644
--- a/src/core/persistence/large-file.ts
+++ b/src/core/persistence/large-file.ts
@@ -7,7 +7,7 @@
* (`stageBeforeCopy`, model.ts) instead of embedding its bytes.
*/
import { createHash } from 'node:crypto';
-import { closeSync, constants, copyFileSync, existsSync, fchmodSync, fstatSync, fsyncSync, openSync, readSync, unlinkSync, writeSync } from 'node:fs';
+import { closeSync, constants, copyFileSync, existsSync, fchmodSync, fstatSync, fsyncSync, lstatSync, openSync, readSync, renameSync, unlinkSync, writeSync } from 'node:fs';
import { dirname } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
@@ -123,6 +123,12 @@ const BEFORE_STAGE = '.tmp.before-';
* Older binaries accept only `.tmp.<uuid>` stage names, so a record naming one blocks them instead of being misread.
*/
export function beforeStagePath(path: string): string { return atomicStagingPath(path).replace(/\.tmp\.(?=[0-9a-f-]{36}$)/, BEFORE_STAGE); }
+/**
+ * Where `stageBeforeCopy` writes the copy before renaming it to its before stage, so a copy a crash cut short is never
+ * at the stage's name. Recovery removes it unread: the rename is the commit point, so a copy still under this name was
+ * never the prior file's only copy (publication starts after the rename).
+ */
+export function beforeStageCopyPath(stagePath: string): string { return `${stagePath}.copying`; }
export function validateBeforeStagePath(path: string, stagePath: string): void {
const at = stagePath.lastIndexOf(BEFORE_STAGE);
if (at < 0) throw new Error('atomic-write: invalid journaled staging path');
@@ -171,27 +177,41 @@ export async function stageStreamedContent(engine: BrainEngine, path: string, co
}
/**
- * Copies the canonical file at `path` to its reserved before stage (exclusive; the kernel copies, no user-space
- * buffer), sets its recorded mode, fsyncs it and checks it holds the recorded bytes. False (the copy removed) when
- * the file changed since its digest was recorded.
+ * Copies the canonical file at `path` to its reserved before stage: the kernel copies it (no user-space buffer) to
+ * `beforeStageCopyPath` (exclusive), its recorded mode is set, it is checked to hold the recorded bytes and fsynced,
+ * and only then renamed to the stage's name, so a stage under that name is always a whole copy. False (the copy
+ * removed) when the file changed since its digest was recorded; a copy that fails or throws is removed too.
+ * `boundary` (crash seams): after the copy is written (`stage_copying`, unverified and unflushed) and once it is
+ * flushed (`stage_flushed`, before the rename).
*/
-export function stageBeforeCopy(path: string, stage: RecoveryStagingFile, mode: number | null): boolean {
+export async function stageBeforeCopy(path: string, stage: RecoveryStagingFile, mode: number | null,
+ boundary?: (phase: 'stage_copying' | 'stage_flushed') => Promise<void>): Promise<boolean> {
assertManagedFilesystemWrite(path);
validateBeforeStagePath(path, stage.path);
- copyFileSync(path, stage.path, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE);
+ const copying = beforeStageCopyPath(stage.path);
let staged = false;
- const fd = openSync(stage.path, constants.O_RDWR | (constants.O_NOFOLLOW ?? 0));
try {
- if (mode !== null) fchmodSync(fd, mode);
- const copy = hashDescriptor(fd);
- largeFileWork.bytesCopied += copy.bytes;
- if (copy.bytes !== stage.bytes || copy.hash !== stage.hash) return false;
- fsyncSync(fd);
+ copyFileSync(path, copying, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE);
+ await boundary?.('stage_copying');
+ const fd = openSync(copying, constants.O_RDWR | (constants.O_NOFOLLOW ?? 0));
+ try {
+ if (mode !== null) fchmodSync(fd, mode);
+ const copy = hashDescriptor(fd);
+ largeFileWork.bytesCopied += copy.bytes;
+ if (copy.bytes !== stage.bytes || copy.hash !== stage.hash) return false;
+ fsyncSync(fd);
+ } finally { closeSync(fd); }
+ await boundary?.('stage_flushed');
+ if (existsAt(stage.path)) throw opError('unexpected_staging_bytes', 'A file already holds the reserved before stage name.',
+ 'A recovery staging file changed outside gbrain. Inspect the pending recovery in writer status and tell the user; never delete or edit staging files by hand.');
+ renameSync(copying, stage.path);
staged = true;
} finally {
- closeSync(fd);
- if (!staged) removeOwnStage(stage.path);
+ if (!staged) removeOwnStage(copying);
}
flushDirectory(dirname(stage.path));
return true;
}
+function existsAt(path: string): boolean {
+ try { lstatSync(path); return true; } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false; throw error; }
+}
diff --git a/src/core/persistence/recovery-resolve.ts b/src/core/persistence/recovery-resolve.ts
index 48104921ec..83b62385e5 100644
--- a/src/core/persistence/recovery-resolve.ts
+++ b/src/core/persistence/recovery-resolve.ts
@@ -21,7 +21,9 @@
* A terminal request whose recovery record is still set is refused (`recovery_choice_refused`): its outcome is immutable,
* recovery never restores its canonical file, and `--keep prior` would roll back a committed write. A withdrawal-mirror
* effect recovery blocking the worktree is listed as refused (`recovery_effect_unsupported`): it only finishes forward,
- * and either choice could put withdrawn content back on disk.
+ * and either choice could put withdrawn content back on disk. So is a page recovery whose prior file is over the
+ * single-string ceiling (`recovery_large_file_unsupported`: its diff would read both files whole), when it is blocked on
+ * unexpected bytes or its file (hashed in pieces) matches neither recorded version.
*
* The apply runs on the owner host under the worktree lock, so the resident recovery pass cannot interleave. Each
* record moves through a journal (`op_checkpoints`, op `stuck-recovery-resolution`, keyed by request and preview
@@ -52,6 +54,7 @@ import { isTerminal, recoveryFiles, type FileRecoveryRecord, type WriteRequest }
import { finishUnpublishedFailure, publishPersistenceFile, recoverPublication, transientDatabaseFailure } from './coordinator.ts';
import { mayReprepare } from './semantic.ts';
import { cleanupRecoveryStaging, upgradeRecoveryStaging } from './staging.ts';
+import { hashFile } from './large-file.ts';
import { withFilesystemPublication } from './filesystem-guard.ts';
import { readHeadBlockers } from './head-blocker.ts';
import { previewChangedError } from './preview-approval.ts';
@@ -81,8 +84,11 @@ export interface StuckRecovery {
/** Digest of the identity, each file's disk bytes and the page revision: what an apply re-verifies. */
digest: string;
}
-/** A blocked terminal request or a withdrawal-mirror effect recovery: listed, never resolved (see the module comment). */
-export interface RefusedRecovery { code: 'recovery_choice_refused' | 'recovery_effect_unsupported'; request_id: string; source_id: string; slug: string; state: string;
+/**
+ * A blocked terminal request, a withdrawal-mirror effect recovery or a page recovery whose prior file is over the
+ * single-string ceiling: listed, never resolved (see the module comment).
+ */
+export interface RefusedRecovery { code: 'recovery_choice_refused' | 'recovery_effect_unsupported' | 'recovery_large_file_unsupported'; request_id: string; source_id: string; slug: string; state: string;
blocked_reason: string | null; reason: string; effect_id?: string }
export interface StuckRecoveryScan { items: StuckRecovery[]; residuals: Record<string, number>; refused: RefusedRecovery[];
heads: Array<{ source_id: string; queued_request_id: string | null; blocked_by: string | null }> }
@@ -173,7 +179,7 @@ function writeArtifacts(dir: string, item: { files: RecoveryFileView[] }, record
async function readItem(engine: BrainEngine, row: WriteRequest, binding: WorktreeBinding): Promise<{ item: StuckRecovery; records: FileRecoveryRecord[]; disks: Array<Buffer | null> }> {
if (row.recovery?.version === 2) throw catalogueError('recovery_bundle_unsupported', `Request ${row.request_id} in source ${row.source_id} is a shared-skill bundle recovery, which gbrain repair stuck-recovery does not resolve.`,
`Nothing was changed. Inspect it read-only with gbrain sources writer status --source ${row.source_id} --json and ask the user which version of each skill file to keep; resolve the bundle by hand, then let the resident writer finish its recovery.`);
- if (row.recovery?.version === 1 && row.recovery.staging?.before) throw catalogueError('recovery_large_file_unsupported', `Request ${row.request_id} in source ${row.source_id} holds a page recovery whose prior file is over the single-string ceiling, which gbrain repair stuck-recovery does not resolve.`,
+ if (row.recovery?.version === 1 && row.recovery.staging?.before) throw catalogueError('recovery_large_file_unsupported', largeFileReason(row),
`Nothing was changed. Inspect it read-only with gbrain sources writer status --source ${row.source_id} --json and ask the user which version of the file to keep; its prior bytes are the staged copy the record names. Put the chosen bytes in place by hand, then let the resident writer finish its recovery.`);
const records = recoveryFiles(row.recovery!);
const [page] = await engine.executeRaw<{ revision: string | null }>('SELECT knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND slug=$2', [row.source_id, row.slug]);
@@ -250,6 +256,17 @@ export async function scanStuckRecoveries(engine: BrainEngine, sourceIds: string
continue;
}
if (row.blocked_reason === 'unexpected_staging_bytes') { residual('unexpected_staging_bytes'); continue; }
+ if (!opts.requestId && row.recovery?.version === 1 && row.recovery.staging?.before) {
+ const record = row.recovery;
+ const contained = isWriteTargetContained(record.path, record.root) && isWriteTargetContained(record.path, binding.local_path!);
+ const leaf = contained ? lstatSync(record.path, { throwIfNoEntry: false }) : undefined;
+ const disk = !contained ? undefined : !leaf ? null : leaf.isFile() ? hashFile(record.path) : undefined;
+ if (row.blocked_reason !== 'unexpected_file_bytes' && (disk === record.beforeHash || disk === record.afterHash)) { residual('recovers_on_its_own'); continue; }
+ scan.refused.push({ code: 'recovery_large_file_unsupported', request_id: row.request_id, source_id: row.source_id, slug: row.slug, state: row.state,
+ blocked_reason: row.blocked_reason ?? null, reason: largeFileReason(row) });
+ residual('large_file_refused');
+ continue;
+ }
const { item, records, disks } = await readItem(engine, row, binding);
if (row.blocked_reason !== 'unexpected_file_bytes' && item.files.every(file => file.matches !== 'neither')) { residual('recovers_on_its_own'); continue; }
if (opts.artifacts) {
@@ -269,6 +286,9 @@ function terminalReason(row: WriteRequest): string {
+ `--keep prior would roll back ${row.state === 'committed' ? 'a committed write' : 'the outcome it recorded'} and --keep disk has nothing to abandon. Its recovery only waits `
+ `for staging cleanup (${row.blocked_reason}), which this command does not perform.`;
}
+function largeFileReason(row: WriteRequest): string {
+ return `Request ${row.request_id} in source ${row.source_id} holds a page recovery whose prior file is over the single-string ceiling, which gbrain repair stuck-recovery does not resolve.`;
+}
function effectReason(kind: string): string {
return `A ${kind} effect recovery blocks the worktree. It only finishes forward (it never restores the bytes from before a withdrawal), and either `
+ '--keep choice could put withdrawn content back on disk, so gbrain repair stuck-recovery does not resolve it.';
diff --git a/src/core/persistence/staging.ts b/src/core/persistence/staging.ts
index f0b25387a0..5b24bf6271 100644
--- a/src/core/persistence/staging.ts
+++ b/src/core/persistence/staging.ts
@@ -7,7 +7,7 @@ import { opError, OperationError } from '../ops/contract.ts';
import { sha256 } from './digest.ts';
import type { BrainEngine } from '../engine.ts';
import { readJournalLimits } from './limits.ts';
-import { hashDescriptor, validateBeforeStagePath } from './large-file.ts';
+import { beforeStageCopyPath, hashDescriptor, validateBeforeStagePath } from './large-file.ts';
import { declarePersistenceProtocol } from './protocol.ts';
export interface RecoveryStagingFile { path: string; hash: string; bytes: number }
@@ -80,12 +80,31 @@ function withVerifiedStage(stage: RecoveryStagingFile, settle: (fd: number) => v
}
/**
- * Called under the owner lock. Partial/unknown stages are preserved, never guessed. `keepBefore`: a live request's
- * recovery keeps the prior file's copy until it has decided whether to rename it back (`restoreBeforeStage`).
+ * Removes a regular file at `path` unread (a symlink, directory or other leaf refuses); flushes its directory.
*/
-export function cleanupRecoveryStaging(record: StagedRecovery, opts: { keepBefore?: boolean } = {}): void {
+function removeUnread(path: string): void {
+ const leaf = statIfPresent(path);
+ if (leaf && !leaf.isFile()) throw blocked();
+ if (leaf) unlinkSync(path);
+ flushParent(path);
+}
+
+/**
+ * Called under the owner lock. Partial/unknown stages are preserved, never guessed, with two exceptions that hold no
+ * bytes recovery needs: a before stage's copy still under its temporary name (`beforeStageCopyPath`: the copy was never
+ * renamed, so publication never started) is always removed, and `priorIntact` (the canonical file still holds the
+ * recorded prior bytes, `beforeHash`) removes the before stage itself unread, so a copy a crash cut short at the stage's
+ * name (a binary that copied in place) cannot block the worktree. `keepBefore`: a live request's recovery keeps the
+ * prior file's copy until it has decided whether to rename it back (`restoreBeforeStage`).
+ */
+export function cleanupRecoveryStaging(record: StagedRecovery, opts: { keepBefore?: boolean; priorIntact?: boolean } = {}): void {
+ const before = record.staging?.before;
for (const stage of stages(record)) {
- if (opts.keepBefore && stage === record.staging?.before) continue;
+ if (stage === before) {
+ removeUnread(beforeStageCopyPath(stage.path));
+ if (opts.keepBefore) continue;
+ if (opts.priorIntact) { removeUnread(stage.path); continue; }
+ }
withVerifiedStage(stage, () => unlinkSync(stage.path));
flushParent(stage.path);
}
@@ -111,7 +130,7 @@ export function restoreBeforeStage(record: StagedRecovery & { mode: number | nul
/** The final accounting fence also protects direct terminal-cleanup callers. */
export function assertRecoveryStagingAbsent(record: StagedRecovery): void {
for (const stage of stages(record)) {
- if (statIfPresent(stage.path)) throw blocked();
+ if (statIfPresent(stage.path) || (stage === record.staging?.before && statIfPresent(beforeStageCopyPath(stage.path)))) throw blocked();
flushParent(stage.path);
}
}
diff --git a/src/core/secret-scan-stream.ts b/src/core/secret-scan-stream.ts
index 6cbc4f9445..a7ac59a49b 100644
--- a/src/core/secret-scan-stream.ts
+++ b/src/core/secret-scan-stream.ts
@@ -14,10 +14,17 @@
* lines and indentation, under 18 Ki) and the bounded line values (jwt
* 3 x 4096 + 2, basic_auth 2048, URL userinfo 384, assignment values 4096).
*
- * OWNERSHIP. A window keeps a claim that starts before the next window's start
- * (it lies wholly inside this window, since it is shorter than the overlap);
- * the next window sees every later claim with all of the overlap behind it.
- * The last window keeps everything. A claim lying wholly inside a span kept by
+ * OWNERSHIP. A claim belongs to the window holding the start of the match that
+ * made it, anchor included (`from`: the `Bearer ` or `Authorization: Basic `
+ * keyword, an assignment key, or the boundary character before a value), not
+ * to the window holding the value's first character: a mid-line cut between
+ * an anchor and its value leaves the next window a value with no anchor, which
+ * no pattern claims. A window keeps a claim whose match starts before the next
+ * window's start (the whole match lies inside this window, since it is shorter
+ * than the overlap); the next window sees every match that starts at or after
+ * its start. The last window keeps everything. A match longer than the overlap
+ * (an anchor whose whitespace run before the token is that long) is the
+ * accepted miss. A claim lying wholly inside a span kept by
* an earlier window is the seam's partial view of it (the body of a key cut at
* the window start, a suffix of a split line) and is dropped, which also drops
* an exact duplicate (same offset and pattern). Line numbers are 1-based over
@@ -71,7 +78,7 @@ export async function scanTextStream(
if (text.length > streamScanWork.largestWindow) streamScanWork.largestWindow = text.length;
const kept: Array<{ start: number; end: number }> = [];
for (const claim of scanTextSpans(text, opts)) {
- if (claim.start >= next) continue;
+ if (claim.from >= next) continue;
const start = base + claim.start;
const end = base + claim.end;
if (carried.some((c) => c.start <= start && end <= c.end)) continue;
diff --git a/src/core/secret-scan.ts b/src/core/secret-scan.ts
index 426348a60e..d4ca3cf30b 100644
--- a/src/core/secret-scan.ts
+++ b/src/core/secret-scan.ts
@@ -801,6 +801,8 @@ interface RawHit extends LineSpan {
line: number; // 1-based
/** Absolute offset of `value` within the scanned text (redactFindings splices on it). */
abs: number;
+ /** Absolute offset where the match that made this claim starts, its anchor included (<= abs). */
+ from: number;
lineText: string;
spans: LineSpans;
/**
@@ -842,7 +844,7 @@ function scanPemBlocks(text: string, claims: PemClaim[]): RawHit[] {
}
const value = text.slice(c.start, c.end);
const span: LineSpan = { pattern: 'private_key_pem', value, start: 0 };
- const hit: RawHit = { ...span, line, abs: c.start, lineText: value, spans: { all: [span] } };
+ const hit: RawHit = { ...span, line, abs: c.start, from: c.start, lineText: value, spans: { all: [span] } };
if (c.kind === 'forward' && c.end > c.headerEnd) hit.legacyValue = text.slice(c.start, c.headerEnd);
hits.push(hit);
}
@@ -909,7 +911,7 @@ function scanInternal(text: string, opts: ScanOpts): RawHit[] {
// line's FIRST hit only (most lines have none), then O(value) to test and
// to mark. Same answer as scanning every prior span for an intersection.
let taken: Uint8Array | null = null;
- const claim = (pattern: string, value: string, start: number): void => {
+ const claim = (pattern: string, value: string, start: number, from: number): void => {
if (work) work.claims++;
taken!.fill(1, start, start + value.length);
// A hit entirely inside a private-key claim (a vendor-shaped run in a
@@ -917,7 +919,7 @@ function scanInternal(text: string, opts: ScanOpts): RawHit[] {
// characters for the first-wins dedupe but is not reported.
if (pem.length > 0 && insideClaim(pem, lineStart + start, lineStart + start + value.length)) return;
spans.all.push({ pattern, value, start });
- hits.push({ pattern, value, start, abs: lineStart + start, line: i + 1, lineText: line, spans });
+ hits.push({ pattern, value, start, abs: lineStart + start, from: lineStart + from, line: i + 1, lineText: line, spans });
};
for (const p of patterns) {
if (p.continuation && p.continuation !== dangling) continue;
@@ -960,15 +962,15 @@ function scanInternal(text: string, opts: ScanOpts): RawHit[] {
// the surrounding `db_url_credentials` span was dropped).
for (let a = start, k = start; k <= end; k++) {
if (k < end && !taken[k]) continue;
- if (a < k) claim(p.name, line.slice(a, k), a);
+ if (a < k) claim(p.name, line.slice(a, k), a, m.index);
a = k + 1;
}
continue;
}
- claim(p.name, value, start);
+ claim(p.name, value, start, m.index);
}
}
- for (const c of cells) if (!taken || !anyTaken(taken, c.start, c.start + c.value.length)) { taken ??= new Uint8Array(line.length); claim('labeled_credential', c.value, c.start); }
+ for (const c of cells) if (!taken || !anyTaken(taken, c.start, c.start + c.value.length)) { taken ??= new Uint8Array(line.length); claim('labeled_credential', c.value, c.start, c.start); }
}
return hits;
}
@@ -1105,15 +1107,17 @@ export function scanText(text: string, opts: ScanOpts = {}): SecretFinding[] {
/**
* `scanText` with each claim's absolute span [start, end) in `text` (UTF-16
- * offsets of the claimed value). An allowlisted claim keeps its span with
- * `finding: null`, so the windowed scan (secret-scan-stream.ts) can still
- * drop a seam's partial copy of it.
+ * offsets of the claimed value) and `from`, where the match that made it
+ * starts: its anchor (`Bearer `, `Authorization: Basic `, an assignment
+ * key) or the boundary character before the value. An allowlisted claim keeps
+ * its span with `finding: null`, so the windowed scan (secret-scan-stream.ts)
+ * can still drop a seam's partial copy of it.
*/
-export function scanTextSpans(text: string, opts: ScanOpts = {}): Array<{ start: number; end: number; finding: SecretFinding | null }> {
+export function scanTextSpans(text: string, opts: ScanOpts = {}): Array<{ start: number; end: number; from: number; finding: SecretFinding | null }> {
const allowlist = opts.allowlist ?? [];
return scanInternal(text, opts).map((hit) => {
const fullHex = sha256Hex(hit.value);
- return { start: hit.abs, end: hit.abs + hit.value.length, finding: valueAllowlisted(fullHex, allowlist) ? null : toFinding(hit, fullHex) };
+ return { start: hit.abs, end: hit.abs + hit.value.length, from: hit.from, finding: valueAllowlisted(fullHex, allowlist) ? null : toFinding(hit, fullHex) };
});
}
diff --git a/test/fixtures/large-delete-crash-worker.ts b/test/fixtures/large-delete-crash-worker.ts
index b336e97101..95be953f09 100644
--- a/test/fixtures/large-delete-crash-worker.ts
+++ b/test/fixtures/large-delete-crash-worker.ts
@@ -1,7 +1,8 @@
/**
- * Child process for test/large-pages/segmented-delete-crash.slow.test.ts: one managed source whose page over the
- * single-string ceiling has a canonical file, a soft delete stopped (for SIGKILL) at a publication seam, and the
- * owner's recovery pass, stopped at a restoration seam or run to the end. Prints one JSON line per step.
+ * Child process for test/large-pages/segmented-delete-crash.slow.test.ts and segmented-delete-stage-crash.slow.test.ts:
+ * one managed source whose page over the single-string ceiling has a canonical file, a soft delete stopped (for
+ * SIGKILL) at a publication or before-stage seam, the owner's recovery pass, stopped at a restoration seam or run to
+ * the end, and the `gbrain repair stuck-recovery` preview scan. Prints one JSON line per step.
*/
import { randomUUID } from 'node:crypto';
import { execFileSync } from 'node:child_process';
@@ -12,6 +13,7 @@ import { PostgresEngine } from '../../src/core/postgres-engine.ts';
import type { OperationContext } from '../../src/core/operations.ts';
import { installFaultHook } from '../../src/core/persistence/fault-points.ts';
import { recoverPublication } from '../../src/core/persistence/coordinator.ts';
+import { scanStuckRecoveries } from '../../src/core/persistence/recovery-resolve.ts';
import { localHostId, registerLocalWriter } from '../../src/core/persistence/identity.ts';
import { importManagedFile } from '../../src/core/persistence/import-mutations.ts';
import { claimWorktree } from '../../src/core/persistence/ownership.ts';
@@ -82,6 +84,9 @@ try {
fileBoundary: point => { if (point === boundary) { emit({ boundary: point }); hang(); } },
});
emit({ recovered: recovered.state, recovery: recovered.recovery === null ? null : 'set', blocked_reason: recovered.blocked_reason ?? null });
+ } else if (mode === 'scan') {
+ const scan = await scanStuckRecoveries(engine, [config.sourceId]).catch((error: { code?: string }) => ({ error: error.code ?? String(error) }));
+ emit('error' in scan ? scan : { items: scan.items.length, refused: scan.refused.map(entry => entry.code), residuals: scan.residuals });
}
} finally {
await disposePersistenceConsumer(engine).catch(() => undefined);
diff --git a/test/large-pages/managed-sync-streamed-memory.slow.test.ts b/test/large-pages/managed-sync-streamed-memory.slow.test.ts
index 2f4669a2e4..1b3ccd287b 100644
--- a/test/large-pages/managed-sync-streamed-memory.slow.test.ts
+++ b/test/large-pages/managed-sync-streamed-memory.slow.test.ts
@@ -6,11 +6,21 @@
* PGLite (frozen by reference, streamed by its owner in the same process), in
* a fresh child process, peaks (VmHWM, reset after setup) under 450 MiB above
* the same child syncing a 1 MiB page (the single-string path), as the
- * streamed import does (segmented-ingest-memory.slow.test.ts).
+ * streamed import does (segmented-ingest-memory.slow.test.ts), and retains
+ * under 16 MiB more heap than it: the heap is sampled after a full GC at every
+ * persistence seam the sync passes (freeze, preparation, staging, flip,
+ * commit, projection) and at its end, and the largest sample is compared.
+ * The two are measured in separate children, so the sampling GCs never lower
+ * the peak.
+ * The peak bound alone let through code that keeps the whole page alive (a
+ * mutant holding every segment's text peaked 256 MiB above, under 450); the
+ * retained bound is half the page, so holding it whole at any seam fails.
* Fails when: the freeze or the preparation reads the file as one buffer or
- * string (the journal, the screen, the pinned-blob window), or the page is
- * held instead of published.
- * Seams: a child process per sync (VmHWM is per process); no mocks.
+ * string (the journal, the screen, the pinned-blob window), anything keeps
+ * the whole page reachable across a seam, or the page is held instead of
+ * published.
+ * Seams: a child process per sync (VmHWM is per process); the process-wide
+ * fault hook (fault-points.ts) as the sampling point; no mocks.
*/
import { afterAll, describe, expect, test } from 'bun:test';
import { execFileSync, spawnSync } from 'node:child_process';
@@ -21,6 +31,7 @@ import { conversationPage } from '../helpers/conversation-page.ts';
const REPO = resolve(import.meta.dir, '../..');
const PEAK_DELTA_LIMIT_MIB = 450;
+const RETAINED_DELTA_LIMIT_MIB = 16;
const dir = mkdtempSync(join(tmpdir(), 'managed-sync-streamed-memory-'));
afterAll(() => rmSync(dir, { recursive: true, force: true }));
@@ -30,7 +41,8 @@ import { createEngine } from ${JSON.stringify(join(REPO, 'src/core/engine-factor
import { claimWorktree } from ${JSON.stringify(join(REPO, 'src/core/persistence/ownership.ts'))};
import { performManagedSync } from ${JSON.stringify(join(REPO, 'src/core/persistence/sync-run.ts'))};
import { disposePersistenceConsumer } from ${JSON.stringify(join(REPO, 'src/core/persistence/service.ts'))};
-const [root, brain] = process.argv.slice(-2);
+import { installFaultHook } from ${JSON.stringify(join(REPO, 'src/core/persistence/fault-points.ts'))};
+const [root, brain, mode] = process.argv.slice(-3);
const engine = await createEngine({ engine: 'pglite', database_path: brain });
await engine.connect({ engine: 'pglite', database_path: brain });
await engine.initSchema();
@@ -41,39 +53,50 @@ await claimWorktree(engine, 'memory', root);
await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
Bun.gc(true);
writeFileSync('/proc/self/clear_refs', '5');
+let retained = 0;
+let samples = 0;
+const sample = () => { Bun.gc(true); retained = Math.max(retained, process.memoryUsage().heapUsed / 2 ** 20); samples++; };
+if (mode === 'retained') installFaultHook(sample);
let result;
for (let pass = 0; pass < 30; pass++) {
result = await performManagedSync(engine, { sourceId: 'memory', noPull: true, noEmbed: true });
if (result.status !== 'partial') break;
}
+if (mode === 'retained') { sample(); installFaultHook(undefined); }
const peak = Number(/^VmHWM:\\s+(\\d+) kB$/m.exec(readFileSync('/proc/self/status', 'utf8'))[1]) / 1024;
const [page] = await engine.executeRaw("SELECT body_storage FROM pages WHERE source_id='memory' AND slug='notes/memory-example'");
await disposePersistenceConsumer(engine);
await engine.disconnect();
-console.log(JSON.stringify({ status: result.status, storage: page?.body_storage ?? null, peak }));
+console.log(JSON.stringify({ status: result.status, storage: page?.body_storage ?? null, peak, retained, samples }));
`;
-function syncInChild(mib: number): { status: string; storage: string | null; peak: number } {
- const root = join(dir, `repo-${mib}`);
+function syncInChild(mib: number, mode: 'peak' | 'retained'): { status: string; storage: string | null; peak: number; retained: number; samples: number } {
+ const root = join(dir, `repo-${mib}-${mode}`);
mkdirSync(join(root, 'notes'), { recursive: true });
writeFileSync(join(root, 'notes/memory-example.md'), conversationPage(mib * 2 ** 20, { seed: 1 }));
const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { stdio: ['ignore', 'pipe', 'pipe'] });
git('init', '-q'); git('add', '-A'); git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'memory');
- const run = spawnSync(process.execPath, ['--no-env-file', '-e', CHILD, root, join(dir, `brain-${mib}`)],
+ const run = spawnSync(process.execPath, ['--no-env-file', '-e', CHILD, root, join(dir, `brain-${mib}-${mode}`), mode],
{ cwd: REPO, encoding: 'utf8', timeout: 300_000, maxBuffer: 1 << 22,
- env: { ...process.env, GBRAIN_HOME: join(dir, `home-${mib}`), OPENAI_API_KEY: '', VOYAGE_API_KEY: '', ANTHROPIC_API_KEY: '' } });
+ env: { ...process.env, GBRAIN_HOME: join(dir, `home-${mib}-${mode}`), OPENAI_API_KEY: '', VOYAGE_API_KEY: '', ANTHROPIC_API_KEY: '' } });
const line = run.stdout.trim().split('\n').pop() ?? '';
if (run.status !== 0 || !line.startsWith('{')) throw new Error(`child sync of ${mib} MiB failed (${run.status}):\n${run.stderr.slice(-2000)}`);
return JSON.parse(line);
}
describe.skipIf(!existsSync('/proc/self/status'))('managed sync streamed memory', () => {
- test(`a 32 MiB page syncs segmented and peaks under ${PEAK_DELTA_LIMIT_MIB} MiB above a 1 MiB one`, () => {
- const small = syncInChild(1);
- const large = syncInChild(32);
+ test(`a 32 MiB page syncs segmented, peaks under ${PEAK_DELTA_LIMIT_MIB} MiB and retains under ${RETAINED_DELTA_LIMIT_MIB} MiB above a 1 MiB one`, () => {
+ const small = syncInChild(1, 'peak');
+ const large = syncInChild(32, 'peak');
+ const smallHeap = syncInChild(1, 'retained');
+ const largeHeap = syncInChild(32, 'retained');
expect(small.status).toBe('first_sync');
expect(large).toMatchObject({ status: 'first_sync', storage: 'segmented' });
- process.stderr.write(`managed sync peak: 1 MiB ${small.peak.toFixed(0)} MiB, 32 MiB ${large.peak.toFixed(0)} MiB\n`);
+ expect(largeHeap).toMatchObject({ status: 'first_sync', storage: 'segmented' });
+ process.stderr.write(`managed sync peak: 1 MiB ${small.peak.toFixed(0)} MiB, 32 MiB ${large.peak.toFixed(0)} MiB; `
+ + `retained after GC: 1 MiB ${smallHeap.retained.toFixed(0)} MiB, 32 MiB ${largeHeap.retained.toFixed(0)} MiB (${largeHeap.samples} samples)\n`);
expect(large.peak - small.peak).toBeLessThan(PEAK_DELTA_LIMIT_MIB);
+ expect(largeHeap.samples).toBeGreaterThan(5);
+ expect(largeHeap.retained - smallHeap.retained).toBeLessThan(RETAINED_DELTA_LIMIT_MIB);
}, 600_000);
});
diff --git a/test/large-pages/segmented-delete-stage-crash.slow.test.ts b/test/large-pages/segmented-delete-stage-crash.slow.test.ts
new file mode 100644
index 0000000000..858e9743d8
--- /dev/null
+++ b/test/large-pages/segmented-delete-stage-crash.slow.test.ts
@@ -0,0 +1,131 @@
+/**
+ * A soft delete of a file-backed page over the single-string ceiling killed while its prior file was being copied to
+ * its before stage, and recovery when that copy is incomplete (PR 2 fix lane G).
+ *
+ * 1. Protects: the copy is written under a temporary name and renamed only once complete and flushed, so a SIGKILL
+ * during the copy (`large_file:stage_copying`, the temporary copy then torn) or during the rename
+ * (`large_file:stage_flushed`) leaves the canonical file untouched and nothing recovery waits on: the next pass
+ * removes the temporary copy and requeues the request with the exact prior bytes and no recovery bytes held. A copy
+ * torn at the stage's own name (what a crash mid-copy left before the temporary name) while the file still holds
+ * its prior bytes is dropped the same way. When recovery truly cannot proceed (the file was removed and its copy is
+ * torn) the pass records `unexpected_staging_bytes` instead of throwing, and the `gbrain repair stuck-recovery`
+ * preview still runs: it counts that record, and lists a large-file record blocked on an edited file as refused
+ * (`recovery_large_file_unsupported`) instead of aborting.
+ * 2. Fails when: a torn copy at the stage name throws `unexpected_staging_bytes` on every pass without recording it (the
+ * worktree wedges), the copy is made in place, a temporary copy is left behind, or the preview aborts on a large-file
+ * record.
+ * 3. Existing coverage: segmented-delete-crash.slow.test.ts kills after the file was removed (`publication:after_publication`,
+ * `before_commit`) with a whole copy, and recovery after the rename back.
+ * 4. Fault seams: the process-wide fault hook (fault-points.ts), including the two `large_file:*` seams in stageBeforeCopy.
+ * Serial: SIGKILLs child processes that hold a brain. Runs on PGLite, and on Postgres when DATABASE_URL is set.
+ */
+import { expect, test } from 'bun:test';
+import { appendFileSync, mkdtempSync, rmSync, statSync, truncateSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import postgres from '#postgres';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+
+const worker = join(import.meta.dir, '../fixtures/large-delete-crash-worker.ts');
+const MiB = 1024 * 1024;
+const tear = (path: string) => truncateSync(path, Math.floor(statSync(path).size / 2));
+
+type Run = (mode: string, boundary?: string) => Promise<Record<string, any>>;
+interface Case {
+ name: string; seam: string;
+ /** After the kill: what is staged, then what the test does to the files. */
+ crashed(crashed: Record<string, any>, initialized: Record<string, any>, file: string): void;
+ /** The recovery pass and what follows it. */
+ recover(run: Run, initialized: Record<string, any>): Promise<void>;
+}
+
+const requeued = async (run: Run, initialized: Record<string, any>) => {
+ expect(await run('recover')).toMatchObject({ recovered: 'queued', recovery: null, blocked_reason: null });
+ expect(await run('inspect')).toMatchObject({ state: 'queued', file_sha: initialized.sha, stages: [], page_deleted: false, recovery_bytes: 0, counters_zero: true });
+};
+
+const cases: Case[] = [
+ { name: 'killed during the copy, the temporary copy torn', seam: 'large_file:stage_copying', crashed(crashed, initialized) {
+ expect(crashed.file_sha).toBe(initialized.sha);
+ expect(crashed.stages).toEqual([{ path: `${crashed.before_stage.path}.copying`, sha: initialized.sha }]);
+ tear(crashed.stages[0].path);
+ }, recover: requeued },
+ { name: 'killed during the rename', seam: 'large_file:stage_flushed', crashed(crashed, initialized) {
+ expect(crashed.file_sha).toBe(initialized.sha);
+ expect(crashed.stages).toEqual([{ path: `${crashed.before_stage.path}.copying`, sha: initialized.sha }]);
+ }, recover: requeued },
+ { name: 'a copy torn at the stage name while the file holds its prior bytes', seam: 'publication:prepared', crashed(crashed, initialized) {
+ expect(crashed.file_sha).toBe(initialized.sha);
+ expect(crashed.stages).toEqual([{ path: crashed.before_stage.path, sha: initialized.sha }]);
+ tear(crashed.before_stage.path);
+ }, recover: requeued },
+ { name: 'the file removed and its copy torn: blocked, recorded, and the preview counts it', seam: 'publication:before_commit', crashed(crashed, initialized) {
+ expect(crashed.file_sha).toBeNull();
+ expect(crashed.stages).toEqual([{ path: crashed.before_stage.path, sha: initialized.sha }]);
+ tear(crashed.before_stage.path);
+ }, async recover(run) {
+ for (let pass = 0; pass < 2; pass++) expect(await run('recover')).toMatchObject({ recovered: 'recovering', recovery: 'set', blocked_reason: 'unexpected_staging_bytes' });
+ expect(await run('scan')).toEqual({ items: 0, refused: [], residuals: { unexpected_staging_bytes: 1 } });
+ } },
+ { name: 'the file edited after its copy: the preview lists it as refused', seam: 'publication:prepared', crashed(crashed, initialized, file) {
+ expect(crashed.file_sha).toBe(initialized.sha);
+ appendFileSync(file, 'edited by hand\n');
+ }, async recover(run) {
+ expect(await run('recover')).toMatchObject({ recovered: 'recovering', recovery: 'set', blocked_reason: 'unexpected_file_bytes' });
+ expect(await run('scan')).toEqual({ items: 0, refused: ['recovery_large_file_unsupported'], residuals: { large_file_refused: 1 } });
+ } },
+];
+
+for (const c of cases) {
+ test(`a large soft delete ${c.name}`, async () => {
+ for (const kind of testBackends()) {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-large-stage-crash-'));
+ const configPath = join(home, 'worker.json');
+ const database = `gbrain_test_large_stage_${randomUUID().replaceAll('-', '')}`;
+ let admin: ReturnType<typeof postgres> | undefined;
+ let databaseUrl: string | undefined;
+ if (kind === 'postgres') {
+ assertSafeE2eDatabaseUrl(process.env.DATABASE_URL!);
+ admin = postgres(process.env.DATABASE_URL!, { max: 1, prepare: false });
+ await admin.unsafe(`CREATE DATABASE ${database}`);
+ const url = new URL(process.env.DATABASE_URL!); url.pathname = `/${database}`; databaseUrl = url.toString();
+ }
+ const root = join(home, 'root');
+ writeFileSync(configPath, JSON.stringify({ engine: kind, database_path: join(home, 'db'), database_url: databaseUrl, root,
+ sourceId: 'stage-crash-example', slug: 'notes/large', bytes: 25 * MiB }));
+ const env = { ...process.env, GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,
+ GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_BACKUP_CHECK: '0', GBRAIN_SWEEP: '0', OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+ const run: Run = async (mode, boundary = '') => {
+ const child = Bun.spawn([process.execPath, worker, mode, configPath, boundary], { cwd: home, env, stdout: 'pipe', stderr: 'pipe' });
+ const errors = new Response(child.stderr).text();
+ const timer = setTimeout(() => child.kill('SIGKILL'), 600_000);
+ let output = '';
+ try {
+ for await (const bytes of child.stdout) {
+ output += new TextDecoder().decode(bytes);
+ if (boundary && output.includes(`"boundary":"${boundary}"`)) { child.kill('SIGKILL'); break; }
+ }
+ const code = await child.exited;
+ if (boundary) expect({ output, code }).toMatchObject({ output: expect.stringContaining(`"boundary":"${boundary}"`) });
+ else expect({ mode, code, stderr: code === 0 ? '' : (await errors).slice(-2000) }).toEqual({ mode, code: 0, stderr: '' });
+ return JSON.parse(output.trim().split('\n').at(-1)!);
+ } finally { clearTimeout(timer); if (child.exitCode === null) { child.kill('SIGKILL'); await child.exited; } }
+ };
+ try {
+ const initialized = await run('initialize');
+ expect(initialized).toMatchObject({ initialized: 'imported', body_storage: 'segmented' });
+ await run('delete', c.seam);
+ const crashed = await run('inspect');
+ expect(crashed).toMatchObject({ before: null, before_hash: initialized.sha, page_deleted: false });
+ expect(crashed.before_stage).toMatchObject({ hash: initialized.sha, bytes: initialized.size });
+ c.crashed(crashed, initialized, join(root, 'notes/large.md'));
+ await c.recover(run, initialized);
+ } finally {
+ if (admin) { await admin.unsafe(`DROP DATABASE ${database} WITH (FORCE)`); await admin.end(); }
+ rmSync(home, { recursive: true, force: true });
+ }
+ }
+ }, 1_800_000);
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index c988f9609f..7c50a418a0 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -94,6 +94,7 @@ test/large-pages/segmented-conversation-sidecar-token.test.ts
test/large-pages/segmented-create-searchable.test.ts
test/large-pages/segmented-delete-crash.slow.test.ts
test/large-pages/segmented-delete-restore-file.slow.test.ts
+test/large-pages/segmented-delete-stage-crash.slow.test.ts
test/large-pages/segmented-derived-parity.test.ts
test/large-pages/segmented-derived-passes.test.ts
test/large-pages/segmented-derived-work.test.ts
diff --git a/test/secret-scan-stream.test.ts b/test/secret-scan-stream.test.ts
index c554aee93c..89b9fb7536 100644
--- a/test/secret-scan-stream.test.ts
+++ b/test/secret-scan-stream.test.ts
@@ -86,6 +86,48 @@ describe('scanTextStream', () => {
expect(streamScanWork.windows).toBeLessThanOrEqual(Math.ceil(buf.length / (W - O - 100)) + 1);
});
+test('every pattern slid across a mid-line cut at every offset matches the whole-text scan', async () => {
+ const W2 = 2 * O;
+ const cut = O; // a newline-free window is cut mid-line at exactly the overlap before its end
+ const filler = rs(W2 + 6000, ALNUM.slice(0, 26) + ' ');
+ const b64 = (s: string): string => Buffer.from(s).toString('base64');
+ const hex = (n: number): string => rs(n, '0123456789abcdef');
+ const cases: Array<{ s: string; highEntropy?: boolean }> = [
+ { s: 'Bearer ' + rs(40) }, { s: 'BEARER ' + rs(40) }, { s: 'bearer\t\t' + rs(24) },
+ { s: 'Authorization: Basic ' + b64('alice:' + rs(10)) }, { s: 'authorization:basic ' + b64('u:p') },
+ { s: 'Basic ' + b64('alice:' + rs(20)) },
+ { s: 'postgres' + '://alice:' + rs(16) + '@db.example:5432/app' }, { s: 'https' + '://alice:' + rs(16) + '@host.example/x' },
+ { s: 'eyJ' + rs(20) + '.' + rs(20) + '.' + rs(20) },
+ { s: 'sk-ant-' + rs(30) }, { s: 'sk-proj-' + rs(30) }, { s: 'sk-' + rs(40) }, { s: 'pa-' + rs(30) },
+ { s: 'github_pat_' + rs(30) }, { s: 'gh' + 'p_' + rs(36) }, { s: 'glpat-' + rs(24) }, { s: 'xox' + 'b-' + rs(20) },
+ { s: 'AKIA' + rs(16, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') }, { s: 'AIza' + rs(35) },
+ { s: 'sk_' + 'live_' + rs(24) }, { s: 'whsec_' + rs(30) }, { s: 'SG.' + rs(20) + '.' + rs(20) },
+ { s: 'AC' + hex(32) }, { s: 'sb_secret_' + rs(24) }, { s: 'sbp_' + hex(40) }, { s: 'npm_' + rs(36) },
+ { s: 'hf_' + rs(34) }, { s: 'dop_v1_' + hex(64) }, { s: 'gbrain_at_' + hex(64) },
+ { s: 'Bearer ' + 'sk-ant-' + rs(30) }, { s: 'Bearer ' + rs(12) + 'gh' + 'p_' + rs(36) },
+ { s: 'api_key = "' + rs(18) + '7Q"', highEntropy: true }, { s: 'SMTP_PASSWORD=' + rs(14) + '9z', highEntropy: true },
+ { s: 'token: ' + rs(16) + '3x', highEntropy: true },
+ ];
+ let probes = 0;
+ let found = 0;
+ for (const { s, highEntropy } of cases) {
+ const opts = highEntropy ? { highEntropy: true } : {};
+ for (let into = -2; into <= Math.min(s.length, 32); into++) {
+ const at = cut - into;
+ const text = filler.slice(0, at - 1) + ' ' + s + ' ' + filler.slice(at + s.length + 1, W2 + 6000);
+ const buf = Buffer.from(text);
+ const whole = scanText(text, opts);
+ const streamed = await scanTextStream(chunks(buf, () => 1 + Math.floor(rnd() * 70_000)), opts, W2);
+ expect({ s: s.slice(0, 12), into, got: keys(streamed) }).toEqual({ s: s.slice(0, 12), into, got: keys(whole) });
+ expect(whole.length).toBeGreaterThan(0);
+ probes++;
+ found += streamed.length;
+ }
+ }
+ expect(probes).toBeGreaterThan(cases.length * 20);
+ expect(found).toBeGreaterThanOrEqual(probes);
+ });
+
test('a window under twice the overlap is refused', async () => {
await expect(scanTextStream(chunks(Buffer.from('x'), () => 1), {}, 2 * O - 1)).rejects.toThrow(RangeError);
});
diff --git a/test/workspace-push-large-blob.serial.test.ts b/test/workspace-push-large-blob.serial.test.ts
index 5e29b96a43..e050ad2fc6 100644
--- a/test/workspace-push-large-blob.serial.test.ts
+++ b/test/workspace-push-large-blob.serial.test.ts
@@ -143,6 +143,31 @@ describe('pre-push secret scan over the 25 MiB cap', () => {
expect(streamScanWork.bytes).toBe(SIZE);
}, T);
+ test('a newline-free stretch cut mid-line between an anchor and its value still blocks: Bearer and Basic at every seam', async () => {
+ // One line: every window is cut mid-line at exactly the overlap before its end.
+ const cut = (k: number): number => k * (W - STREAM_SCAN_OVERLAP_CHARS);
+ const token = 'Q7' + randomBytes(30).toString('hex');
+ const basic = Buffer.from('alice:' + randomBytes(9).toString('hex')).toString('base64');
+ const placed: Array<{ at: number; text: string }> = [
+ { at: cut(1) - ' Bearer '.length, text: ' Bearer ' + token + ' ' },
+ { at: cut(2) - ' Bearer '.length + 4, text: ' Bearer ' + token.split('').reverse().join('') + ' ' },
+ { at: cut(3) - ' Authorization: Basic '.length, text: ' Authorization: Basic ' + basic + ' ' },
+ ];
+ const size = 30 * 1024 ** 2;
+ expect(cut(3) + STREAM_SCAN_OVERLAP_CHARS).toBeLessThan(size);
+ const body = Buffer.alloc(size, 'a');
+ for (const p of placed) body.write(p.text, p.at, 'latin1');
+ writeFileSync(join(work, 'big.md'), body);
+ const before = git(bare, 'rev-parse', 'refs/heads/main');
+ const r = await push();
+ expect(r.status).toBe('blocked_secrets');
+ expect((r.findings ?? []).map((f) => `${f.file}:${f.line}:${f.pattern}`).sort()).toEqual(['big.md:1:basic_auth', 'big.md:1:bearer', 'big.md:1:bearer']);
+ expect(JSON.stringify(r).includes(token)).toBe(false);
+ expect(git(bare, 'rev-parse', 'refs/heads/main')).toBe(before);
+ expect(streamScanWork.windows).toBe(4);
+ expect(streamScanWork.largestWindow).toBeLessThanOrEqual(STREAM_SCAN_WINDOW_CHARS);
+ }, T);
+
test('a staged blob over the streamed-scan ceiling still blocks as unscannable', async () => {
const huge = join(work, 'huge.bin');
writeFileSync(huge, '');