From 46ca1559fdfeefd301043219016fc9dd15ecdd50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matheus=20Galv=C3=A3o?= Date: Fri, 4 Dec 2026 11:22:45 -0300 Subject: [PATCH 1/3] Keep run files within the session save budget A CodeSignal session saves the workspace within 1 MB, and a file over 100 KB comes back empty after a return visit. A run over 90,000 bytes is now saved with its longest texts shortened (each cut marked), with the full record in data/runs/full/, which sessions do not save; reads prefer the full copy while it exists. Retention keeps the newest 20 runs within 800,000 bytes. Run files are written as compact JSON. --- AGENTS.md | 2 +- CLAUDE.md | 2 +- apps/server/src/report/build.test.ts | 6 + apps/server/src/report/build.ts | 5 + apps/server/src/services/persistence.test.ts | 159 +++++++++++++++++++ apps/server/src/services/persistence.ts | 87 ++++++++-- apps/server/src/services/run-size.ts | 116 ++++++++++++++ apps/server/src/services/workflow-file.ts | 8 +- docs/api.md | 2 +- docs/releases.md | 2 +- docs/report.md | 2 +- docs/run-persistence.md | 19 ++- packages/types/src/index.ts | 5 + 13 files changed, 387 insertions(+), 28 deletions(-) create mode 100644 apps/server/src/services/persistence.test.ts create mode 100644 apps/server/src/services/run-size.ts diff --git a/AGENTS.md b/AGENTS.md index 52e30ca..1d0e0ff 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,7 @@ This repository is an npm workspace monorepo: - `packages/workflow-graph`: Graph rules shared by the editor and the server (handles, conditions, legacy upgrades, run-readiness checks). - `packages/workflow-engine`: Reusable workflow runtime. - `design-system/`: Git submodule with UI tokens/components. -- `data/runs/`: Runtime run snapshots (gitignored); the newest 20 are kept. +- `data/runs/`: Runtime run snapshots (gitignored); the newest 20 within 800,000 bytes are kept, and a run over 90,000 bytes is saved shortened with its full record in `data/runs/full/` (see `docs/run-persistence.md`). - `data/workflow.json`: The learner's canvas, saved by the editor (gitignored). - `apps/server/src/report`: `npm run report`, the workflow and run report for an LLM grader. - `.config/config.json`: Provider/model definitions (committed); schema in `docs/configuration.md`. diff --git a/CLAUDE.md b/CLAUDE.md index 35eb5c2..086c831 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -73,7 +73,7 @@ Each run/resume operation persists `data/runs/_.json` (format - `currentNodeId` - `waitingForInput` -The newest 20 runs are kept; paused runs are never deleted. The editor also saves the canvas to `data/workflow.json` (`PUT /api/workflow`) and loads it first. `npm run report` (`apps/server/src/report`) turns both into the text an LLM grader reads; see `docs/report.md`. +The newest 20 runs within 800,000 bytes are kept; paused runs are never deleted. A run over 90,000 bytes is saved with its longest texts shortened, and in full under `data/runs/full/`, which sessions do not save (`apps/server/src/services/run-size.ts`). The editor also saves the canvas to `data/workflow.json` (`PUT /api/workflow`) and loads it first. `npm run report` (`apps/server/src/report`) turns both into the text an LLM grader reads; see `docs/report.md`. ## Paused-run restoration diff --git a/apps/server/src/report/build.test.ts b/apps/server/src/report/build.test.ts index 8a42e4d..674ea69 100644 --- a/apps/server/src/report/build.test.ts +++ b/apps/server/src/report/build.test.ts @@ -303,6 +303,12 @@ describe('buildReport', () => { expect(run).toContain('Branch taken: Otherwise (no condition matched) → Researcher'); }); + it('says when a run was saved with shortened texts', async () => { + const record = { ...(await recordRun(researchWorkflow(), { Researcher: 'READY' })), shortenedTexts: 3 }; + const run = section(buildReport(input({ runs: runsOf([record]) })), '### Run 1 ('); + expect(run).toContain('- Saved shortened: 3 long texts were cut to keep the run within the workspace save limit'); + }); + it('reads legacy runs that have no start time, models or condition type', () => { const workflow = researchWorkflow() as WorkflowGraph; workflow.nodes.find((node) => node.id === 'gate')!.type = 'if'; diff --git a/apps/server/src/report/build.ts b/apps/server/src/report/build.ts index 8d1f3b1..cbfa3d3 100644 --- a/apps/server/src/report/build.ts +++ b/apps/server/src/report/build.ts @@ -817,6 +817,11 @@ function runOutcome(view: RunView): string[] { function describeRunInFull(view: RunView, current: AnalysedWorkflow | null, info: ReportModelInfo): string[] { const lines = [`### Run ${view.number} (started ${formatTime(view.run.startedAtMs)})`, '']; lines.push(`- Status: ${view.record.status}, ${runDuration(view)}`); + if (view.record.shortenedTexts) { + lines.push( + `- Saved shortened: ${view.record.shortenedTexts} long ${view.record.shortenedTexts === 1 ? 'text was' : 'texts were'} cut to keep the run within the workspace save limit; each cut is marked.` + ); + } if (view.isCurrent === true) lines.push('- Workflow: the current workflow'); if (view.isCurrent === false && current) { const changes = describeChanges(view.workflow, current); diff --git a/apps/server/src/services/persistence.test.ts b/apps/server/src/services/persistence.test.ts new file mode 100644 index 0000000..d583268 --- /dev/null +++ b/apps/server/src/services/persistence.test.ts @@ -0,0 +1,159 @@ +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import type { WorkflowRunRecord } from '@agentflow/types'; +import { RUN_RECORD_FORMAT_VERSION } from '@agentflow/types'; +import { + FULL_RUNS_DIR, + listRunRecords, + pruneRunRecords, + readRunRecord, + runFileName, + saveRunRecord +} from './persistence.js'; +import { RUN_FILE_LIMIT_BYTES, RUNS_TOTAL_LIMIT_BYTES, fitRunRecord } from './run-size.js'; + +let runsDir: string; +let sequence = 0; + +beforeEach(async () => { + runsDir = path.join(await fs.mkdtemp(path.join(os.tmpdir(), 'agentflow-runs-')), 'runs'); +}); + +afterEach(async () => { + await fs.rm(path.dirname(runsDir), { recursive: true, force: true }); +}); + +/** A completed run whose agent wrote `outputLength` characters. */ +function run(outputLength: number, overrides: Partial = {}): WorkflowRunRecord { + sequence += 1; + const output = 'x'.repeat(outputLength); + const startedAt = new Date(Date.parse('2026-12-04T10:00:00.000Z') + sequence * 60_000).toISOString(); + return { + formatVersion: RUN_RECORD_FORMAT_VERSION, + runId: `run-${sequence}`, + startedAt, + finishedAt: startedAt, + workflow: { nodes: [{ id: 'start', type: 'start', x: 0, y: 0 }], connections: [] }, + models: {}, + logs: [ + { timestamp: startedAt, nodeId: 'a', type: 'step_start', content: 'Agent' }, + { + timestamp: startedAt, + nodeId: 'a', + type: 'subagent_call_end', + content: JSON.stringify({ callId: 'call-1', subagentNodeId: 'b', output }) + }, + { timestamp: startedAt, nodeId: 'a', type: 'llm_response', content: output } + ], + status: 'completed', + state: { previous_output: output, a: output }, + currentNodeId: null, + waitingForInput: false, + ...overrides + }; +} + +const savedSize = async (record: WorkflowRunRecord) => (await fs.stat(path.join(runsDir, runFileName(record)))).size; +const savedCopy = async (record: WorkflowRunRecord): Promise => + JSON.parse(await fs.readFile(path.join(runsDir, runFileName(record)), 'utf-8')) as WorkflowRunRecord; +const fullCopyExists = (record: WorkflowRunRecord) => + fs.access(path.join(runsDir, FULL_RUNS_DIR, runFileName(record))).then( + () => true, + () => false + ); + +describe('fitRunRecord', () => { + it('leaves a record that fits as it is', () => { + const record = run(1_000); + const fitted = fitRunRecord(record); + expect(fitted.shortenedTexts).toBe(0); + expect(JSON.parse(fitted.text)).toEqual(record); + }); + + it('shortens the longest texts to fit, keeps JSON log events parseable and marks each cut', () => { + const record = run(60_000); + const fitted = fitRunRecord(record); + expect(Buffer.byteLength(fitted.text)).toBeLessThanOrEqual(RUN_FILE_LIMIT_BYTES); + expect(fitted.shortenedTexts).toBe(4); + const saved = JSON.parse(fitted.text) as WorkflowRunRecord; + expect(saved.shortenedTexts).toBe(4); + expect(saved.logs[0].content).toBe('Agent'); + const event = JSON.parse(saved.logs[1].content) as { callId: string; output: string }; + expect(event.callId).toBe('call-1'); + expect(event.output).toMatch(/more characters were cut when this run was saved/); + expect(saved.logs[2].content.startsWith('x'.repeat(1_000))).toBe(true); + expect(saved.state?.previous_output).toMatch(/more characters were cut/); + expect(saved.workflow).toEqual(record.workflow); + }); + + it('never shortens the state of a paused run, which it resumes from', () => { + const record = run(40_000, { status: 'paused', waitingForInput: true, currentNodeId: 'gate' }); + const saved = JSON.parse(fitRunRecord(record).text) as WorkflowRunRecord; + expect(saved.state).toEqual(record.state); + expect(saved.logs[2].content).toMatch(/more characters were cut/); + }); +}); + +describe('saveRunRecord', () => { + it('saves a small run once, with no full copy', async () => { + const record = run(1_000); + await saveRunRecord(runsDir, record); + expect(await savedCopy(record)).toEqual(record); + expect(await fullCopyExists(record)).toBe(false); + }); + + it('saves a big run shortened, keeps the full record beside it, and reads the full one while it exists', async () => { + const record = run(150_000); + await saveRunRecord(runsDir, record); + expect(await savedSize(record)).toBeLessThanOrEqual(RUN_FILE_LIMIT_BYTES); + expect((await savedCopy(record)).shortenedTexts).toBeGreaterThan(0); + expect(await fullCopyExists(record)).toBe(true); + expect(await readRunRecord(runsDir, record.runId)).toEqual(record); + expect((await listRunRecords(runsDir)).map((stored) => stored.record)).toEqual([record]); + + // A return visit: the session saved data/runs but not data/runs/full. + await fs.rm(path.join(runsDir, FULL_RUNS_DIR), { recursive: true }); + const restored = await readRunRecord(runsDir, record.runId); + expect(restored?.shortenedTexts).toBeGreaterThan(0); + expect(restored?.logs[2].content).toMatch(/more characters were cut/); + }); + + it('drops the full copy when the run is saved again small enough', async () => { + const record = run(150_000, { status: 'paused', waitingForInput: true, currentNodeId: 'gate', state: {} }); + await saveRunRecord(runsDir, record); + expect(await fullCopyExists(record)).toBe(true); + await saveRunRecord(runsDir, { ...record, logs: record.logs.slice(0, 1), status: 'completed' }); + expect(await fullCopyExists(record)).toBe(false); + }); +}); + +describe('pruneRunRecords', () => { + it('keeps the newest runs within the count', async () => { + const records = [run(100), run(100), run(100)]; + for (const record of records) await saveRunRecord(runsDir, record); + expect(await pruneRunRecords(runsDir, 2)).toEqual([records[0].runId]); + }); + + it('deletes the oldest runs, and their full copies, until the saved files fit the total limit', async () => { + const records = Array.from({ length: 12 }, () => run(150_000)); + for (const record of records) await saveRunRecord(runsDir, record); + const deleted = await pruneRunRecords(runsDir); + const kept = await listRunRecords(runsDir); + expect(deleted.length).toBeGreaterThan(0); + expect(deleted).toContain(records[0].runId); + expect(kept.reduce((total, stored) => total + stored.sizeBytes, 0)).toBeLessThanOrEqual(RUNS_TOTAL_LIMIT_BYTES); + expect(kept.map((stored) => stored.record.runId)).toContain(records[11].runId); + expect(await fullCopyExists(records[0])).toBe(false); + }); + + it('never deletes a paused run', async () => { + const paused = run(150_000, { status: 'paused', waitingForInput: true, currentNodeId: 'gate' }); + await saveRunRecord(runsDir, paused); + for (let index = 0; index < 12; index += 1) await saveRunRecord(runsDir, run(150_000)); + const deleted = await pruneRunRecords(runsDir); + expect(deleted).not.toContain(paused.runId); + expect(await readRunRecord(runsDir, paused.runId)).toEqual(paused); + }); +}); diff --git a/apps/server/src/services/persistence.ts b/apps/server/src/services/persistence.ts index 82eb85f..ff6b6ff 100644 --- a/apps/server/src/services/persistence.ts +++ b/apps/server/src/services/persistence.ts @@ -1,7 +1,8 @@ import fs from 'node:fs/promises'; import path from 'node:path'; import type { WorkflowRunRecord } from '@agentflow/types'; -import { writeJsonAtomic } from './workflow-file.js'; +import { RUNS_TOTAL_LIMIT_BYTES, fitRunRecord } from './run-size.js'; +import { writeTextAtomic } from './workflow-file.js'; /** Run ids become file names, so only a conservative character set is accepted. */ export const RUN_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/; @@ -9,6 +10,13 @@ export const RUN_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/; /** Run files kept on disk; older finished runs are deleted when a run is saved. */ export const DEFAULT_RUNS_TO_KEEP = 20; +/** + * Subdirectory of the runs directory holding the full record of each run whose + * saved copy had to be shortened. Sessions leave it out of the saved workspace, + * so it is complete while the session runs and gone after a return visit. + */ +export const FULL_RUNS_DIR = 'full'; + /** Prefix of run files written before file names started with the run's start time. */ const LEGACY_PREFIX = 'run_'; @@ -59,15 +67,43 @@ async function filesForRun(runsDir: string, runId: string): Promise { return (await listRunFiles(runsDir)).filter((file) => runIdFromFileName(file) === runId); } +/** + * Saves the run under `runsDir`. A record too big for the workspace save limit + * is saved with its longest texts shortened, and in full under `full/`. + */ export async function saveRunRecord(runsDir: string, record: WorkflowRunRecord): Promise { const fileName = runFileName(record); + const fullDir = path.join(runsDir, FULL_RUNS_DIR); const previous = await filesForRun(runsDir, record.runId); - await writeJsonAtomic(path.join(runsDir, fileName), record); + const fitted = fitRunRecord(record); + if (fitted.shortenedTexts > 0) { + const full: WorkflowRunRecord = { ...record }; + delete full.shortenedTexts; + await writeTextAtomic(path.join(fullDir, fileName), JSON.stringify(full)); + } else { + await fs.rm(path.join(fullDir, fileName), { force: true }); + } + await writeTextAtomic(path.join(runsDir, fileName), fitted.text); // A run restored from an older record gets a start time on its next save, - // and with it a new file name; drop the file under the old name. - await Promise.all( - previous.filter((file) => file !== fileName).map((file) => fs.rm(path.join(runsDir, file), { force: true })) - ); + // and with it a new file name; drop the files under the old name. + await Promise.all(previous.filter((file) => file !== fileName).map((file) => removeRunFile(runsDir, file))); +} + +async function removeRunFile(runsDir: string, file: string): Promise { + await fs.rm(path.join(runsDir, file), { force: true }); + await fs.rm(path.join(runsDir, FULL_RUNS_DIR, file), { force: true }); +} + +/** The record in `file`, or its full copy when the saved one was shortened and the full one still exists. */ +async function readRunFile(runsDir: string, file: string): Promise { + const record = JSON.parse(await fs.readFile(path.join(runsDir, file), 'utf-8')) as WorkflowRunRecord; + if (!record.shortenedTexts) return record; + try { + const full = JSON.parse(await fs.readFile(path.join(runsDir, FULL_RUNS_DIR, file), 'utf-8')) as WorkflowRunRecord; + return full.runId === record.runId ? full : record; + } catch { + return record; + } } export async function readRunRecord(runsDir: string, runId: string): Promise { @@ -77,7 +113,7 @@ export async function readRunRecord(runsDir: string, runId: string): Promise void = () => {} @@ -99,8 +140,8 @@ export async function listRunRecords( for (const file of await listRunFiles(runsDir)) { const filePath = path.join(runsDir, file); try { - const [raw, stats] = await Promise.all([fs.readFile(filePath, 'utf-8'), fs.stat(filePath)]); - results.push({ file, record: JSON.parse(raw) as WorkflowRunRecord, modifiedAtMs: stats.mtimeMs }); + const [record, stats] = await Promise.all([readRunFile(runsDir, file), fs.stat(filePath)]); + results.push({ file, record, modifiedAtMs: stats.mtimeMs, sizeBytes: stats.size }); } catch (error) { onSkip(file, error); } @@ -119,17 +160,29 @@ export function runStartTimeMs(stored: StoredRunFile): number { } /** - * Keeps the newest `keep` runs and deletes older ones. A run paused at an - * approval is never deleted, since the learner can still resume it. - * Returns the ids of the deleted runs. + * Keeps the newest `keep` runs while their saved files total at most + * `limitBytes`, and deletes older ones. A run paused at an approval is never + * deleted, since the learner can still resume it. Returns the ids of the + * deleted runs. */ -export async function pruneRunRecords(runsDir: string, keep = DEFAULT_RUNS_TO_KEEP): Promise { +export async function pruneRunRecords( + runsDir: string, + keep = DEFAULT_RUNS_TO_KEEP, + limitBytes = RUNS_TOTAL_LIMIT_BYTES +): Promise { const stored = await listRunRecords(runsDir); const newestFirst = stored.sort((a, b) => runStartTimeMs(b) - runStartTimeMs(a)); const deleted: string[] = []; - for (const entry of newestFirst.slice(keep)) { - if (entry.record.status === 'paused') continue; - await fs.rm(path.join(runsDir, entry.file), { force: true }); + let kept = 0; + let keptBytes = 0; + for (const entry of newestFirst) { + const fits = kept < keep && keptBytes + entry.sizeBytes <= limitBytes; + if (fits || entry.record.status === 'paused') { + kept += 1; + keptBytes += entry.sizeBytes; + continue; + } + await removeRunFile(runsDir, entry.file); deleted.push(entry.record.runId); } return deleted; diff --git a/apps/server/src/services/run-size.ts b/apps/server/src/services/run-size.ts new file mode 100644 index 0000000..f4e02db --- /dev/null +++ b/apps/server/src/services/run-size.ts @@ -0,0 +1,116 @@ +import type { WorkflowRunRecord } from '@agentflow/types'; + +/** + * A CodeSignal session saves the learner's workspace within a budget: 1 MB in + * all, and a file over 100 KB comes back empty when the learner returns. Run + * files stay under both, with room left for `data/workflow.json`. + */ +export const RUN_FILE_LIMIT_BYTES = 90_000; +export const RUNS_TOTAL_LIMIT_BYTES = 800_000; + +/** Texts are never shortened below this many characters, even if the file stays too big. */ +const MIN_TEXT_LENGTH = 200; + +export interface FittedRunRecord { + /** The JSON to save. */ + text: string; + /** How many texts were shortened to fit; 0 when the record fits as it is. */ + shortenedTexts: number; +} + +function byteLength(text: string): number { + return Buffer.byteLength(text, 'utf-8'); +} + +function shortenText(text: string, maxLength: number): string { + const cut = text.length - maxLength; + return `${text.slice(0, maxLength)}\n[… ${cut} more characters were cut when this run was saved, to keep the file within the workspace save limit]`; +} + +interface Shortener { + maxLength: number; + count: number; +} + +function shortenValue(value: unknown, shortener: Shortener): unknown { + if (typeof value === 'string') { + if (value.length <= shortener.maxLength) return value; + shortener.count += 1; + return shortenText(value, shortener.maxLength); + } + if (Array.isArray(value)) return value.map((item) => shortenValue(item, shortener)); + if (value && typeof value === 'object') { + return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, shortenValue(item, shortener)])); + } + return value; +} + +/** Log contents that are JSON events (subagent calls, web searches) keep their structure. */ +function shortenLogContent(content: string, shortener: Shortener): string { + if (content.length <= shortener.maxLength) return content; + if (content.startsWith('{')) { + try { + const parsed: unknown = JSON.parse(content); + if (parsed && typeof parsed === 'object') return JSON.stringify(shortenValue(parsed, shortener)); + } catch { + // plain text that happens to start with a brace + } + } + return shortenValue(content, shortener) as string; +} + +function shortenRecord(record: WorkflowRunRecord, maxLength: number): FittedRunRecord { + const shortener: Shortener = { maxLength, count: 0 }; + const logs = record.logs.map((entry) => ({ ...entry, content: shortenLogContent(entry.content, shortener) })); + // A paused run resumes from its state, so its state is never shortened. + const state = + record.status === 'paused' || record.state === undefined + ? record.state + : (shortenValue(record.state, shortener) as Record); + const shortened: WorkflowRunRecord = { ...record, logs, state }; + if (shortener.count > 0) shortened.shortenedTexts = shortener.count; + return { text: JSON.stringify(shortened), shortenedTexts: shortener.count }; +} + +function longestText(record: WorkflowRunRecord): number { + let longest = 0; + const visit = (value: unknown): void => { + if (typeof value === 'string') longest = Math.max(longest, value.length); + else if (Array.isArray(value)) value.forEach(visit); + else if (value && typeof value === 'object') Object.values(value).forEach(visit); + }; + visit(record.logs); + visit(record.state); + return longest; +} + +/** + * The record as JSON within `limitBytes`. A record that is too big gets its + * longest texts (log contents and, unless the run is paused, its state) + * shortened to the longest length that fits, each with a note saying so. The + * workflow itself is never shortened. If the record cannot fit even with every + * text at the minimum length, that best effort is returned. + */ +export function fitRunRecord(record: WorkflowRunRecord, limitBytes = RUN_FILE_LIMIT_BYTES): FittedRunRecord { + const original: WorkflowRunRecord = { ...record }; + delete original.shortenedTexts; + const text = JSON.stringify(original); + if (byteLength(text) <= limitBytes) return { text, shortenedTexts: 0 }; + + let low = MIN_TEXT_LENGTH; + let high = longestText(original); + let best = shortenRecord(original, low); + if (byteLength(best.text) > limitBytes) return best; + // The longest length at which the record still fits. + while (low < high) { + const middle = Math.ceil((low + high) / 2); + const attempt = shortenRecord(original, middle); + if (byteLength(attempt.text) <= limitBytes) { + low = middle; + best = attempt; + } else { + high = middle - 1; + } + } + return best; +} diff --git a/apps/server/src/services/workflow-file.ts b/apps/server/src/services/workflow-file.ts index 216dab2..f0f5eb3 100644 --- a/apps/server/src/services/workflow-file.ts +++ b/apps/server/src/services/workflow-file.ts @@ -7,13 +7,17 @@ import { workflowFingerprint } from './fingerprint.js'; export const SAVED_WORKFLOW_FILE = 'workflow.json'; /** Writes through a temporary file, so a crash never leaves a truncated file. */ -export async function writeJsonAtomic(filePath: string, value: unknown): Promise { +export async function writeTextAtomic(filePath: string, text: string): Promise { await fs.mkdir(path.dirname(filePath), { recursive: true }); const tempPath = `${filePath}.${process.pid}.tmp`; - await fs.writeFile(tempPath, JSON.stringify(value, null, 2), 'utf-8'); + await fs.writeFile(tempPath, text, 'utf-8'); await fs.rename(tempPath, filePath); } +export async function writeJsonAtomic(filePath: string, value: unknown): Promise { + await writeTextAtomic(filePath, JSON.stringify(value, null, 2)); +} + /** The workflow the editor last saved, or null when nothing has been saved yet. */ export async function readSavedWorkflow(dataDir: string): Promise { try { diff --git a/docs/api.md b/docs/api.md index 75f2c85..7cec62c 100644 --- a/docs/api.md +++ b/docs/api.md @@ -197,7 +197,7 @@ Responses: ## Persistence and Lifecycle Notes -- All run and resume endpoints persist run records via `saveRunRecord`, then keep the newest 20 runs (paused runs are never deleted). +- All run and resume endpoints persist run records via `saveRunRecord`, then keep the newest 20 runs within 800,000 bytes (paused runs are never deleted); a run too big for the session's save budget is saved shortened, with its full record in `data/runs/full/`. - Non-paused runs are removed from in-memory active map after completion, failure or cancellation. - Paused runs remain active and resumable until completed, failed or cancelled. - A run that executes more than `WORKFLOW_MAX_STEPS` nodes in one run or resume call fails with an `error` log entry. diff --git a/docs/releases.md b/docs/releases.md index 2080693..54e3b75 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -46,6 +46,6 @@ The scripts the session runs belong to the base task; copies are kept in [`.code A task overrides the base task's models or starting workflow by shipping its own file at the same path. `setup.sh` copies them into `agentflow/.config/` on every start, so a changed file applies from the next session. -The learner's canvas and runs are written to `agentflow/data/`, which the session saves, so they survive a return visit. Run records count toward the session's save budget; retention keeps the newest 20. +The learner's canvas and runs are written to `agentflow/data/`, which the session saves, so they survive a return visit. Run files stay within the session's save budget (1 MB in all, 100 KB per file): a run too big for one file is saved shortened, with the full record in `agentflow/data/runs/full/`, and retention keeps the newest 20 runs within 800,000 bytes ([Run Persistence](./run-persistence.md#size-limits)). The base task's `ignoredPaths` must leave out `agentflow/data/runs/full` along with the release files and `agentflow/.config`, but never the rest of `agentflow/data`. Every model in `config.json` must also be allowed by the LLM proxy the session uses, and the proxy must provide a key for each provider in the file (`OPENAI_API_KEY` and `OPENAI_BASE_URL` for OpenAI, `ANTHROPIC_API_KEY` and `ANTHROPIC_BASE_URL` for Anthropic). The SDKs read the base URLs from the environment when the provider sets no `baseUrl`. diff --git a/docs/report.md b/docs/report.md index 223c152..5b0f54d 100644 --- a/docs/report.md +++ b/docs/report.md @@ -16,7 +16,7 @@ The command always exits 0 and prints something, because whatever it prints is a From the project root: - `data/workflow.json`: the learner's saved canvas. -- `data/runs/*.json`: run records, both the current and the legacy file names. +- `data/runs/*.json`: run records, both the current and the legacy file names. A run saved shortened is read from its full copy in `data/runs/full/` when that still exists; otherwise its step-by-step section says it was saved shortened. - `.config/default-workflow.json`: the task's starting workflow, to list what the learner changed. - `.config/config.json`: model names, effort settings and the default model. diff --git a/docs/run-persistence.md b/docs/run-persistence.md index 0249f29..e5b9a44 100644 --- a/docs/run-persistence.md +++ b/docs/run-persistence.md @@ -3,7 +3,7 @@ The server keeps two kinds of files in `data/` (gitignored): - `data/workflow.json`: the workflow on the learner's canvas, saved by the editor. -- `data/runs/`: one JSON record per run. +- `data/runs/`: one JSON record per run, and in `data/runs/full/` the full record of each run whose saved copy had to be shortened. `npm run report` turns both into a plain-text report (see [Report](./report.md)). @@ -49,6 +49,8 @@ On load, the editor uses the first of: the server's saved workflow (`GET /api/wo } ``` +Records are written as compact JSON. + Fields: - `formatVersion`: `2`. Absent on older records, which lack the fields marked "since 2". @@ -62,6 +64,7 @@ Fields: - `state`: engine internal state snapshot. `state.previous_output` holds the final output of a completed run. - `currentNodeId`: active node when paused/running. - `waitingForInput`: approval wait flag. +- `shortenedTexts`: only on a saved copy that was shortened (see [Size Limits](#size-limits)): how many texts were cut. ## When Records Are Written @@ -75,9 +78,17 @@ Records are saved after: Files are written to a temporary file and renamed, so a crash cannot leave a truncated record. Persistence is best-effort; save failures are logged server-side. +## Size Limits + +A CodeSignal session saves the learner's workspace within a budget: 1 MB in all, and a file over 100 KB comes back empty when the learner returns. Run files stay under both (`apps/server/src/services/run-size.ts`): + +- A record over 90,000 bytes is saved with its longest texts shortened to the longest length that fits (log contents, including the texts inside subagent-call and web-search events, and the `state` of a run that is not paused). Each cut ends with a note saying how many characters were cut and why, and the record gets `shortenedTexts`. The workflow and a paused run's state are never shortened. +- The full record is written to `data/runs/full/` under the same file name. Reads (`GET /api/run/:runId`, startup restore, the report) use the full record while it exists. Sessions leave `agentflow/data/runs/full` out of the saved workspace (`ignoredPaths`), so the full record is there for the whole session and only the shortened copy comes back after a return visit; the report then says the run was saved shortened. +- When the record fits again on a later save (a resumed run, for example), the full copy is deleted. + ## Retention -After each save the server keeps the newest 20 runs (by start time) and deletes older ones. A paused run is never deleted, since the learner can still resume it. This keeps `data/` within the Learn session save budget. +After each save the server keeps the newest 20 runs (by start time) whose saved files total at most 800,000 bytes, and deletes older ones together with their full copies. A paused run is never deleted, since the learner can still resume it, but it counts toward the total. With `data/workflow.json`, this keeps `data/` within the session's save budget. ## Active In-memory Runs @@ -92,7 +103,7 @@ Server keeps a map of active `WorkflowEngine` instances. `GET /api/run/:runId` lookup order: 1. In-memory active run (if still running/paused). -2. Persisted file from `data/runs/`, under either name. +2. Persisted file from `data/runs/`, under either name (its full copy in `data/runs/full/` when the saved one was shortened). If both missing, API returns `404`. @@ -122,4 +133,4 @@ To abandon a paused run instead of answering it, cancel it (`POST /api/cancel`, ## Data Hygiene - `data/` is gitignored. Do not commit run data or saved workflows. -- Retention bounds `data/runs/`. +- Retention and the size limits bound `data/runs/`. diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts index dc423da..44dd432 100644 --- a/packages/types/src/index.ts +++ b/packages/types/src/index.ts @@ -108,6 +108,11 @@ export interface WorkflowRunRecord { state?: Record; currentNodeId?: string | null; waitingForInput?: boolean; + /** + * Set on a saved copy whose longest texts were shortened to stay within the + * workspace save limit; the full record is kept in `data/runs/full/`. + */ + shortenedTexts?: number; } export const RUN_RECORD_FORMAT_VERSION = 2; From b8c837601e3bcf9bfa58d9ad8898d53583a4ac80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matheus=20Galv=C3=A3o?= Date: Fri, 4 Dec 2026 11:31:56 -0300 Subject: [PATCH 2/3] Address review: paused runs, cut counts, write order - Count the cut notes in the saved copy, so a run restored from a shortened copy keeps its notice when saved again. - Delete a stale full copy only after the new record is written. - Count paused runs toward the 800,000-byte total first, and stop at the first finished run that does not fit, so kept runs are the newest. - Shorten a paused run's state as a last resort rather than leave a file that would come back empty. --- apps/server/src/services/persistence.test.ts | 37 ++++++++- apps/server/src/services/persistence.ts | 25 +++--- apps/server/src/services/run-size.ts | 84 +++++++++++++------- docs/report.md | 2 +- docs/run-persistence.md | 4 +- 5 files changed, 109 insertions(+), 43 deletions(-) diff --git a/apps/server/src/services/persistence.test.ts b/apps/server/src/services/persistence.test.ts index d583268..fddbc7c 100644 --- a/apps/server/src/services/persistence.test.ts +++ b/apps/server/src/services/persistence.test.ts @@ -88,12 +88,28 @@ describe('fitRunRecord', () => { expect(saved.workflow).toEqual(record.workflow); }); - it('never shortens the state of a paused run, which it resumes from', () => { + it('keeps the state of a paused run, which it resumes from, when shortening the logs is enough', () => { const record = run(40_000, { status: 'paused', waitingForInput: true, currentNodeId: 'gate' }); const saved = JSON.parse(fitRunRecord(record).text) as WorkflowRunRecord; expect(saved.state).toEqual(record.state); expect(saved.logs[2].content).toMatch(/more characters were cut/); }); + + it("shortens a paused run's state too when the logs alone are not enough", () => { + const record = run(60_000, { status: 'paused', waitingForInput: true, currentNodeId: 'gate' }); + const fitted = fitRunRecord(record); + expect(Buffer.byteLength(fitted.text)).toBeLessThanOrEqual(RUN_FILE_LIMIT_BYTES); + const saved = JSON.parse(fitted.text) as WorkflowRunRecord; + expect(saved.state?.previous_output).toMatch(/more characters were cut/); + }); + + it('keeps counting the cuts of a record restored from a shortened copy', () => { + const shortened = JSON.parse(fitRunRecord(run(150_000)).text) as WorkflowRunRecord; + const { shortenedTexts: _count, ...restored } = shortened; + const fitted = fitRunRecord({ ...restored, status: 'completed' }); + expect(fitted.shortenedTexts).toBe(0); + expect((JSON.parse(fitted.text) as WorkflowRunRecord).shortenedTexts).toBe(shortened.shortenedTexts); + }); }); describe('saveRunRecord', () => { @@ -148,6 +164,25 @@ describe('pruneRunRecords', () => { expect(await fullCopyExists(records[0])).toBe(false); }); + it('keeps only the newest runs: from the first that does not fit, older ones go too', async () => { + const older = run(100); + const big = run(150_000); + const newer = Array.from({ length: 9 }, () => run(150_000)); + for (const record of [older, big, ...newer]) await saveRunRecord(runsDir, record); + const deleted = await pruneRunRecords(runsDir); + expect(deleted).toEqual(expect.arrayContaining([older.runId, big.runId])); + }); + + it('counts paused runs toward the total before keeping finished ones', async () => { + const paused = run(150_000, { status: 'paused', waitingForInput: true, currentNodeId: 'gate' }); + await saveRunRecord(runsDir, paused); + for (let index = 0; index < 9; index += 1) await saveRunRecord(runsDir, run(150_000)); + await pruneRunRecords(runsDir); + const kept = await listRunRecords(runsDir); + expect(kept.map((stored) => stored.record.runId)).toContain(paused.runId); + expect(kept.reduce((total, stored) => total + stored.sizeBytes, 0)).toBeLessThanOrEqual(RUNS_TOTAL_LIMIT_BYTES); + }); + it('never deletes a paused run', async () => { const paused = run(150_000, { status: 'paused', waitingForInput: true, currentNodeId: 'gate' }); await saveRunRecord(runsDir, paused); diff --git a/apps/server/src/services/persistence.ts b/apps/server/src/services/persistence.ts index ff6b6ff..7cbc899 100644 --- a/apps/server/src/services/persistence.ts +++ b/apps/server/src/services/persistence.ts @@ -80,10 +80,10 @@ export async function saveRunRecord(runsDir: string, record: WorkflowRunRecord): const full: WorkflowRunRecord = { ...record }; delete full.shortenedTexts; await writeTextAtomic(path.join(fullDir, fileName), JSON.stringify(full)); - } else { - await fs.rm(path.join(fullDir, fileName), { force: true }); } await writeTextAtomic(path.join(runsDir, fileName), fitted.text); + // Only once the new record is saved: a stale full copy would otherwise win over it. + if (fitted.shortenedTexts === 0) await fs.rm(path.join(fullDir, fileName), { force: true }); // A run restored from an older record gets a start time on its next save, // and with it a new file name; drop the files under the old name. await Promise.all(previous.filter((file) => file !== fileName).map((file) => removeRunFile(runsDir, file))); @@ -160,10 +160,12 @@ export function runStartTimeMs(stored: StoredRunFile): number { } /** - * Keeps the newest `keep` runs while their saved files total at most - * `limitBytes`, and deletes older ones. A run paused at an approval is never - * deleted, since the learner can still resume it. Returns the ids of the - * deleted runs. + * Keeps the newest `keep` finished runs whose saved files, with every paused + * run's, total at most `limitBytes`, and deletes the rest together with their + * full copies. A run paused at an approval is never deleted, since the learner + * can still resume it. From the first finished run that does not fit, every + * older finished run is deleted, so the kept runs are always the newest ones. + * Returns the ids of the deleted runs. */ export async function pruneRunRecords( runsDir: string, @@ -172,12 +174,15 @@ export async function pruneRunRecords( ): Promise { const stored = await listRunRecords(runsDir); const newestFirst = stored.sort((a, b) => runStartTimeMs(b) - runStartTimeMs(a)); - const deleted: string[] = []; + const paused = newestFirst.filter((entry) => entry.record.status === 'paused'); let kept = 0; - let keptBytes = 0; + let keptBytes = paused.reduce((total, entry) => total + entry.sizeBytes, 0); + let full = false; + const deleted: string[] = []; for (const entry of newestFirst) { - const fits = kept < keep && keptBytes + entry.sizeBytes <= limitBytes; - if (fits || entry.record.status === 'paused') { + if (entry.record.status === 'paused') continue; + full ||= kept >= keep || keptBytes + entry.sizeBytes > limitBytes; + if (!full) { kept += 1; keptBytes += entry.sizeBytes; continue; diff --git a/apps/server/src/services/run-size.ts b/apps/server/src/services/run-size.ts index f4e02db..73fa43c 100644 --- a/apps/server/src/services/run-size.ts +++ b/apps/server/src/services/run-size.ts @@ -14,17 +14,20 @@ const MIN_TEXT_LENGTH = 200; export interface FittedRunRecord { /** The JSON to save. */ text: string; - /** How many texts were shortened to fit; 0 when the record fits as it is. */ + /** How many texts this save shortened; 0 when the record fits as it is. */ shortenedTexts: number; } +/** Ends every note added to a shortened text; counted to keep `shortenedTexts` right across saves. */ +const CUT_NOTE = 'more characters were cut when this run was saved, to keep the file within the workspace save limit'; + function byteLength(text: string): number { return Buffer.byteLength(text, 'utf-8'); } function shortenText(text: string, maxLength: number): string { const cut = text.length - maxLength; - return `${text.slice(0, maxLength)}\n[… ${cut} more characters were cut when this run was saved, to keep the file within the workspace save limit]`; + return `${text.slice(0, maxLength)}\n[… ${cut} ${CUT_NOTE}]`; } interface Shortener { @@ -59,17 +62,30 @@ function shortenLogContent(content: string, shortener: Shortener): string { return shortenValue(content, shortener) as string; } -function shortenRecord(record: WorkflowRunRecord, maxLength: number): FittedRunRecord { +interface Attempt { + record: WorkflowRunRecord; + text: string; + shortenedTexts: number; +} + +/** + * Records `shortenedTexts` as the number of cut notes the saved text holds, so + * a run restored from a shortened copy and saved again keeps its notice. + */ +function finish(record: WorkflowRunRecord, shortenedTexts: number): Attempt { + const notes = JSON.stringify(record).split(CUT_NOTE).length - 1; + const saved: WorkflowRunRecord = { ...record }; + if (notes > 0) saved.shortenedTexts = notes; + return { record: saved, text: JSON.stringify(saved), shortenedTexts }; +} + +function shortenRecord(record: WorkflowRunRecord, maxLength: number, includePausedState: boolean): Attempt { const shortener: Shortener = { maxLength, count: 0 }; const logs = record.logs.map((entry) => ({ ...entry, content: shortenLogContent(entry.content, shortener) })); - // A paused run resumes from its state, so its state is never shortened. - const state = - record.status === 'paused' || record.state === undefined - ? record.state - : (shortenValue(record.state, shortener) as Record); - const shortened: WorkflowRunRecord = { ...record, logs, state }; - if (shortener.count > 0) shortened.shortenedTexts = shortener.count; - return { text: JSON.stringify(shortened), shortenedTexts: shortener.count }; + // A paused run resumes from its state, so its state is shortened only when nothing else is enough. + const keepState = record.state === undefined || (record.status === 'paused' && !includePausedState); + const state = keepState ? record.state : (shortenValue(record.state, shortener) as Record); + return finish({ ...record, logs, state }, shortener.count); } function longestText(record: WorkflowRunRecord): number { @@ -84,27 +100,15 @@ function longestText(record: WorkflowRunRecord): number { return longest; } -/** - * The record as JSON within `limitBytes`. A record that is too big gets its - * longest texts (log contents and, unless the run is paused, its state) - * shortened to the longest length that fits, each with a note saying so. The - * workflow itself is never shortened. If the record cannot fit even with every - * text at the minimum length, that best effort is returned. - */ -export function fitRunRecord(record: WorkflowRunRecord, limitBytes = RUN_FILE_LIMIT_BYTES): FittedRunRecord { - const original: WorkflowRunRecord = { ...record }; - delete original.shortenedTexts; - const text = JSON.stringify(original); - if (byteLength(text) <= limitBytes) return { text, shortenedTexts: 0 }; - +/** The longest text length at which the record fits, or null if it does not fit even at the minimum. */ +function search(record: WorkflowRunRecord, limitBytes: number, includePausedState: boolean): Attempt | null { let low = MIN_TEXT_LENGTH; - let high = longestText(original); - let best = shortenRecord(original, low); - if (byteLength(best.text) > limitBytes) return best; - // The longest length at which the record still fits. + let high = Math.max(low, longestText(record)); + let best = shortenRecord(record, low, includePausedState); + if (byteLength(best.text) > limitBytes) return null; while (low < high) { const middle = Math.ceil((low + high) / 2); - const attempt = shortenRecord(original, middle); + const attempt = shortenRecord(record, middle, includePausedState); if (byteLength(attempt.text) <= limitBytes) { low = middle; best = attempt; @@ -114,3 +118,25 @@ export function fitRunRecord(record: WorkflowRunRecord, limitBytes = RUN_FILE_LI } return best; } + +/** + * The record as JSON within `limitBytes`. A record that is too big gets its + * longest texts (log contents and, unless the run is paused, its state) + * shortened to the longest length that fits, each with a note saying so. A + * paused run's state is shortened too only when the logs alone are not enough: + * a resumable run with shortened texts beats a file that comes back empty. The + * workflow is never shortened; a record that cannot fit even with every text at + * the minimum length is returned with every text at the minimum. + */ +export function fitRunRecord(record: WorkflowRunRecord, limitBytes = RUN_FILE_LIMIT_BYTES): FittedRunRecord { + const original: WorkflowRunRecord = { ...record }; + delete original.shortenedTexts; + const whole = finish(original, 0); + const fitted = + byteLength(whole.text) <= limitBytes + ? whole + : search(original, limitBytes, false) ?? + search(original, limitBytes, true) ?? + shortenRecord(original, MIN_TEXT_LENGTH, true); + return { text: fitted.text, shortenedTexts: fitted.shortenedTexts }; +} diff --git a/docs/report.md b/docs/report.md index 5b0f54d..656a036 100644 --- a/docs/report.md +++ b/docs/report.md @@ -16,7 +16,7 @@ The command always exits 0 and prints something, because whatever it prints is a From the project root: - `data/workflow.json`: the learner's saved canvas. -- `data/runs/*.json`: run records, both the current and the legacy file names. A run saved shortened is read from its full copy in `data/runs/full/` when that still exists; otherwise its step-by-step section says it was saved shortened. +- `data/runs/*.json`: run records, both the current and the legacy file names. A run saved shortened is read from its full copy in `data/runs/full/` when that still exists; otherwise, when the run is one of those described step by step, its section says it was saved shortened. - `.config/default-workflow.json`: the task's starting workflow, to list what the learner changed. - `.config/config.json`: model names, effort settings and the default model. diff --git a/docs/run-persistence.md b/docs/run-persistence.md index e5b9a44..49885a6 100644 --- a/docs/run-persistence.md +++ b/docs/run-persistence.md @@ -82,13 +82,13 @@ Files are written to a temporary file and renamed, so a crash cannot leave a tru A CodeSignal session saves the learner's workspace within a budget: 1 MB in all, and a file over 100 KB comes back empty when the learner returns. Run files stay under both (`apps/server/src/services/run-size.ts`): -- A record over 90,000 bytes is saved with its longest texts shortened to the longest length that fits (log contents, including the texts inside subagent-call and web-search events, and the `state` of a run that is not paused). Each cut ends with a note saying how many characters were cut and why, and the record gets `shortenedTexts`. The workflow and a paused run's state are never shortened. +- A record over 90,000 bytes is saved with its longest texts shortened to the longest length that fits: log contents, including the texts inside subagent-call and web-search events, and the `state` of a run that is not paused. A paused run's state is shortened too only when shortening the logs is not enough, since a resumable run with shortened texts is better than a file that comes back empty. Each cut ends with a note saying how many characters were cut and why, and `shortenedTexts` counts the notes in the saved copy, so a run restored from a shortened copy and saved again keeps it. The workflow is never shortened. - The full record is written to `data/runs/full/` under the same file name. Reads (`GET /api/run/:runId`, startup restore, the report) use the full record while it exists. Sessions leave `agentflow/data/runs/full` out of the saved workspace (`ignoredPaths`), so the full record is there for the whole session and only the shortened copy comes back after a return visit; the report then says the run was saved shortened. - When the record fits again on a later save (a resumed run, for example), the full copy is deleted. ## Retention -After each save the server keeps the newest 20 runs (by start time) whose saved files total at most 800,000 bytes, and deletes older ones together with their full copies. A paused run is never deleted, since the learner can still resume it, but it counts toward the total. With `data/workflow.json`, this keeps `data/` within the session's save budget. +After each save the server keeps the newest 20 finished runs (by start time) whose saved files, together with every paused run's, total at most 800,000 bytes. From the first run that would pass either limit, that run and every older finished run are deleted with their full copies, so the kept runs are always the newest ones. A paused run is never deleted, since the learner can still resume it, but its file counts toward the total. With `data/workflow.json`, this keeps `data/` within the session's save budget. ## Active In-memory Runs From b8b56d71d74897a30771382bd1dce7d9b0dab4a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matheus=20Galv=C3=A3o?= Date: Fri, 4 Dec 2026 11:59:39 -0300 Subject: [PATCH 3/3] Fit runs that loop to the step limit; expire old paused runs - When shortening every text is not enough (a run that loops to the step limit with a search and a subagent call per step measured 127 KB), keep the first and last log entries that fit and add one warning entry saying how many were left out, so the file never comes back empty. - Pruning keeps a paused run only while it can be resumed (the startup restore's PAUSED_RUN_TTL_HOURS); an older one is pruned like a finished run, so paused runs cannot pile up past the save budget. --- CLAUDE.md | 2 +- apps/server/src/app.ts | 2 + apps/server/src/index.ts | 1 + apps/server/src/routes/workflows.ts | 8 ++- apps/server/src/services/persistence.test.ts | 31 +++++++++- apps/server/src/services/persistence.ts | 38 ++++++++---- apps/server/src/services/run-size.ts | 65 +++++++++++++++++--- docs/api.md | 2 +- docs/run-persistence.md | 9 ++- 9 files changed, 133 insertions(+), 25 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 086c831..0f355a9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -73,7 +73,7 @@ Each run/resume operation persists `data/runs/_.json` (format - `currentNodeId` - `waitingForInput` -The newest 20 runs within 800,000 bytes are kept; paused runs are never deleted. A run over 90,000 bytes is saved with its longest texts shortened, and in full under `data/runs/full/`, which sessions do not save (`apps/server/src/services/run-size.ts`). The editor also saves the canvas to `data/workflow.json` (`PUT /api/workflow`) and loads it first. `npm run report` (`apps/server/src/report`) turns both into the text an LLM grader reads; see `docs/report.md`. +The newest 20 runs within 800,000 bytes are kept; paused runs are kept while they can be resumed. A run over 90,000 bytes is saved with its longest texts shortened (and, as a last resort, middle log entries left out), and in full under `data/runs/full/`, which sessions do not save (`apps/server/src/services/run-size.ts`). The editor also saves the canvas to `data/workflow.json` (`PUT /api/workflow`) and loads it first. `npm run report` (`apps/server/src/report`) turns both into the text an LLM grader reads; see `docs/report.md`. ## Paused-run restoration diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts index 0863c4c..809cdf3 100644 --- a/apps/server/src/app.ts +++ b/apps/server/src/app.ts @@ -12,6 +12,7 @@ export interface CreateAppOptions { dataDir?: string; projectRoot: string; runsToKeep?: WorkflowRouterOptions['runsToKeep']; + pausedRunTtlMs?: WorkflowRouterOptions['pausedRunTtlMs']; resolveModels?: WorkflowRouterOptions['resolveModels']; now?: WorkflowRouterOptions['now']; maxSteps?: number; @@ -40,6 +41,7 @@ export function createApp(options: CreateAppOptions): { app: Express; store: Run dataDir: options.dataDir ?? path.dirname(options.runsDir), projectRoot: options.projectRoot, runsToKeep: options.runsToKeep, + pausedRunTtlMs: options.pausedRunTtlMs, resolveModels: options.resolveModels, now: options.now, maxSteps: options.maxSteps, diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index b00bd3e..7e5c157 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -49,6 +49,7 @@ async function bootstrap() { dataDir: config.dataDir, projectRoot: config.projectRoot, maxSteps: config.maxSteps, + pausedRunTtlMs: config.pausedRunTtlMs, preflight: (graph) => llmService.preflight(graph), resolveModels: (graph) => { const current = readConfig(configStore); diff --git a/apps/server/src/routes/workflows.ts b/apps/server/src/routes/workflows.ts index 59b0643..7f74e82 100644 --- a/apps/server/src/routes/workflows.ts +++ b/apps/server/src/routes/workflows.ts @@ -23,6 +23,8 @@ export interface WorkflowRouterOptions { projectRoot: string; /** Run files kept on disk. Default 20. */ runsToKeep?: number; + /** How long a paused run can be resumed; older paused runs are pruned like finished ones. */ + pausedRunTtlMs?: number; /** Model id each agent node of `graph` will run with. */ resolveModels?: (graph: WorkflowGraph) => Record; now?: () => Date; @@ -90,7 +92,11 @@ export function createWorkflowRouter(options: WorkflowRouterOptions): Router { }; try { await saveRunRecord(runsDir, record); - await pruneRunRecords(runsDir, runsToKeep); + await pruneRunRecords(runsDir, { + keep: runsToKeep, + pausedRunTtlMs: options.pausedRunTtlMs, + now: () => now().getTime() + }); } catch (error) { logger.error('Failed to persist run result', error); } diff --git a/apps/server/src/services/persistence.test.ts b/apps/server/src/services/persistence.test.ts index fddbc7c..1bce80e 100644 --- a/apps/server/src/services/persistence.test.ts +++ b/apps/server/src/services/persistence.test.ts @@ -103,6 +103,25 @@ describe('fitRunRecord', () => { expect(saved.state?.previous_output).toMatch(/more characters were cut/); }); + it('leaves out log entries from the middle of a run that loops to the step limit, keeping its start and end', () => { + const record = run(100); + record.logs = Array.from({ length: 600 }, (_, index) => ({ + timestamp: record.startedAt!, + nodeId: 'a', + type: 'llm_response', + content: `entry ${index} ${'x'.repeat(2_000)}` + })); + const fitted = fitRunRecord(record); + expect(Buffer.byteLength(fitted.text)).toBeLessThanOrEqual(RUN_FILE_LIMIT_BYTES); + const saved = JSON.parse(fitted.text) as WorkflowRunRecord; + const marker = saved.logs.find((entry) => entry.nodeId === 'system'); + expect(marker?.type).toBe('warn'); + expect(marker?.content).toMatch(/^\d+ log entries from the middle of this run were left out when it was saved/); + expect(saved.logs[0].content.startsWith('entry 0 ')).toBe(true); + expect(saved.logs.at(-1)?.content.startsWith('entry 599 ')).toBe(true); + expect(saved.logs.length).toBeGreaterThan(100); + }); + it('keeps counting the cuts of a record restored from a shortened copy', () => { const shortened = JSON.parse(fitRunRecord(run(150_000)).text) as WorkflowRunRecord; const { shortenedTexts: _count, ...restored } = shortened; @@ -149,7 +168,7 @@ describe('pruneRunRecords', () => { it('keeps the newest runs within the count', async () => { const records = [run(100), run(100), run(100)]; for (const record of records) await saveRunRecord(runsDir, record); - expect(await pruneRunRecords(runsDir, 2)).toEqual([records[0].runId]); + expect(await pruneRunRecords(runsDir, { keep: 2 })).toEqual([records[0].runId]); }); it('deletes the oldest runs, and their full copies, until the saved files fit the total limit', async () => { @@ -183,6 +202,16 @@ describe('pruneRunRecords', () => { expect(kept.reduce((total, stored) => total + stored.sizeBytes, 0)).toBeLessThanOrEqual(RUNS_TOTAL_LIMIT_BYTES); }); + it('prunes a paused run like a finished one once it can no longer be resumed', async () => { + const paused = run(100, { status: 'paused', waitingForInput: true, currentNodeId: 'gate' }); + await saveRunRecord(runsDir, paused); + await saveRunRecord(runsDir, run(100)); + const day = 24 * 60 * 60 * 1000; + expect(await pruneRunRecords(runsDir, { keep: 1, pausedRunTtlMs: day })).toEqual([]); + const later = () => Date.now() + 2 * day; + expect(await pruneRunRecords(runsDir, { keep: 1, pausedRunTtlMs: day, now: later })).toEqual([paused.runId]); + }); + it('never deletes a paused run', async () => { const paused = run(150_000, { status: 'paused', waitingForInput: true, currentNodeId: 'gate' }); await saveRunRecord(runsDir, paused); diff --git a/apps/server/src/services/persistence.ts b/apps/server/src/services/persistence.ts index 7cbc899..1c3bde4 100644 --- a/apps/server/src/services/persistence.ts +++ b/apps/server/src/services/persistence.ts @@ -159,28 +159,44 @@ export function runStartTimeMs(stored: StoredRunFile): number { return stored.modifiedAtMs; } +export interface PruneOptions { + /** Finished runs kept. Default 20. */ + keep?: number; + /** Most bytes the kept runs' saved files may total. Default 800,000. */ + limitBytes?: number; + /** + * How long a paused run can still be resumed (the startup restore's limit). + * A paused run saved longer ago than this is pruned like a finished one. + * Default: paused runs never expire. + */ + pausedRunTtlMs?: number; + now?: () => number; +} + /** * Keeps the newest `keep` finished runs whose saved files, with every paused * run's, total at most `limitBytes`, and deletes the rest together with their - * full copies. A run paused at an approval is never deleted, since the learner - * can still resume it. From the first finished run that does not fit, every - * older finished run is deleted, so the kept runs are always the newest ones. - * Returns the ids of the deleted runs. + * full copies. A run paused at an approval is never deleted while the learner + * can still resume it; the editor allows one paused run at a time, so few are + * kept. From the first other run that does not fit, every older one is deleted, + * so the kept runs are always the newest ones. Returns the ids of the deleted + * runs. */ -export async function pruneRunRecords( - runsDir: string, - keep = DEFAULT_RUNS_TO_KEEP, - limitBytes = RUNS_TOTAL_LIMIT_BYTES -): Promise { +export async function pruneRunRecords(runsDir: string, options: PruneOptions = {}): Promise { + const keep = options.keep ?? DEFAULT_RUNS_TO_KEEP; + const limitBytes = options.limitBytes ?? RUNS_TOTAL_LIMIT_BYTES; + const ttl = options.pausedRunTtlMs ?? Number.POSITIVE_INFINITY; + const now = (options.now ?? Date.now)(); + const resumable = (entry: StoredRunFile) => entry.record.status === 'paused' && now - entry.modifiedAtMs <= ttl; const stored = await listRunRecords(runsDir); const newestFirst = stored.sort((a, b) => runStartTimeMs(b) - runStartTimeMs(a)); - const paused = newestFirst.filter((entry) => entry.record.status === 'paused'); + const paused = newestFirst.filter(resumable); let kept = 0; let keptBytes = paused.reduce((total, entry) => total + entry.sizeBytes, 0); let full = false; const deleted: string[] = []; for (const entry of newestFirst) { - if (entry.record.status === 'paused') continue; + if (resumable(entry)) continue; full ||= kept >= keep || keptBytes + entry.sizeBytes > limitBytes; if (!full) { kept += 1; diff --git a/apps/server/src/services/run-size.ts b/apps/server/src/services/run-size.ts index 73fa43c..3b63523 100644 --- a/apps/server/src/services/run-size.ts +++ b/apps/server/src/services/run-size.ts @@ -120,13 +120,61 @@ function search(record: WorkflowRunRecord, limitBytes: number, includePausedStat } /** - * The record as JSON within `limitBytes`. A record that is too big gets its - * longest texts (log contents and, unless the run is paused, its state) - * shortened to the longest length that fits, each with a note saying so. A - * paused run's state is shortened too only when the logs alone are not enough: - * a resumable run with shortened texts beats a file that comes back empty. The - * workflow is never shortened; a record that cannot fit even with every text at - * the minimum length is returned with every text at the minimum. + * The record with only the first and last log entries, `keep` in all, and one + * warning entry in place of those left out. + */ +function omitMiddleLogs(record: WorkflowRunRecord, keep: number): WorkflowRunRecord { + const { logs } = record; + if (keep >= logs.length) return record; + const head = Math.floor(keep / 3); + const tail = keep - head; + const omitted = logs.length - keep; + const marker = { + timestamp: logs[head].timestamp, + nodeId: 'system', + type: 'warn', + content: `${omitted} log ${omitted === 1 ? 'entry' : 'entries'} from the middle of this run ${omitted === 1 ? 'was' : 'were'} left out when it was saved, to keep the file within the workspace save limit.` + }; + return { ...record, logs: [...logs.slice(0, head), marker, ...logs.slice(logs.length - tail)] }; +} + +/** + * Every text at the minimum length and as many log entries as fit, keeping the + * start and the end of the run; null if even no log entries do not fit. + */ +function searchLogCount(record: WorkflowRunRecord, limitBytes: number): Attempt | null { + const attemptWith = (keep: number) => shortenRecord(omitMiddleLogs(record, keep), MIN_TEXT_LENGTH, true); + let low = 0; + let high = record.logs.length; + let best = attemptWith(low); + if (byteLength(best.text) > limitBytes) return null; + while (low < high) { + const middle = Math.ceil((low + high) / 2); + const attempt = attemptWith(middle); + if (byteLength(attempt.text) <= limitBytes) { + low = middle; + best = attempt; + } else { + high = middle - 1; + } + } + return best; +} + +/** + * The record as JSON within `limitBytes`, so it never comes back empty after a + * return visit. A record that is too big, in order of preference: + * + * 1. gets its longest texts (log contents and, unless the run is paused, its + * state) shortened to the longest length that fits, each with a note; + * 2. also gets a paused run's state shortened: a resumable run with shortened + * texts beats a file that comes back empty; + * 3. keeps every text at the minimum length and only the first and last log + * entries that fit, with a warning entry saying how many were left out (a + * run that looped up to the step limit). + * + * The workflow is never shortened. A record that does not fit even with no log + * entries (a workflow of more than 90,000 bytes) is returned as small as it gets. */ export function fitRunRecord(record: WorkflowRunRecord, limitBytes = RUN_FILE_LIMIT_BYTES): FittedRunRecord { const original: WorkflowRunRecord = { ...record }; @@ -137,6 +185,7 @@ export function fitRunRecord(record: WorkflowRunRecord, limitBytes = RUN_FILE_LI ? whole : search(original, limitBytes, false) ?? search(original, limitBytes, true) ?? - shortenRecord(original, MIN_TEXT_LENGTH, true); + searchLogCount(original, limitBytes) ?? + shortenRecord(omitMiddleLogs(original, 0), MIN_TEXT_LENGTH, true); return { text: fitted.text, shortenedTexts: fitted.shortenedTexts }; } diff --git a/docs/api.md b/docs/api.md index 7cec62c..e9d3b9b 100644 --- a/docs/api.md +++ b/docs/api.md @@ -197,7 +197,7 @@ Responses: ## Persistence and Lifecycle Notes -- All run and resume endpoints persist run records via `saveRunRecord`, then keep the newest 20 runs within 800,000 bytes (paused runs are never deleted); a run too big for the session's save budget is saved shortened, with its full record in `data/runs/full/`. +- All run and resume endpoints persist run records via `saveRunRecord`, then keep the newest 20 runs within 800,000 bytes (paused runs are kept while they can be resumed); a run too big for the session's save budget is saved shortened, with its full record in `data/runs/full/`. - Non-paused runs are removed from in-memory active map after completion, failure or cancellation. - Paused runs remain active and resumable until completed, failed or cancelled. - A run that executes more than `WORKFLOW_MAX_STEPS` nodes in one run or resume call fails with an `error` log entry. diff --git a/docs/run-persistence.md b/docs/run-persistence.md index 49885a6..54a46f7 100644 --- a/docs/run-persistence.md +++ b/docs/run-persistence.md @@ -82,13 +82,18 @@ Files are written to a temporary file and renamed, so a crash cannot leave a tru A CodeSignal session saves the learner's workspace within a budget: 1 MB in all, and a file over 100 KB comes back empty when the learner returns. Run files stay under both (`apps/server/src/services/run-size.ts`): -- A record over 90,000 bytes is saved with its longest texts shortened to the longest length that fits: log contents, including the texts inside subagent-call and web-search events, and the `state` of a run that is not paused. A paused run's state is shortened too only when shortening the logs is not enough, since a resumable run with shortened texts is better than a file that comes back empty. Each cut ends with a note saying how many characters were cut and why, and `shortenedTexts` counts the notes in the saved copy, so a run restored from a shortened copy and saved again keeps it. The workflow is never shortened. +- A record over 90,000 bytes is saved smaller, in this order of preference: + 1. Its longest texts are shortened to the longest length that fits: log contents, including the texts inside subagent-call and web-search events, and the `state` of a run that is not paused. + 2. A paused run's state is shortened too, since a resumable run with shortened texts is better than a file that comes back empty. + 3. Every text is kept at 200 characters, and only the first and last log entries that fit are kept, with one `warn` entry from `system` saying how many were left out. This is for runs that loop up to the step limit; a run of 100 steps with a web search and a subagent call in each needs it. + + Each cut text ends with a note saying how many characters were cut and why, and `shortenedTexts` counts the notes in the saved copy, so a run restored from a shortened copy and saved again keeps it. The workflow is never shortened. - The full record is written to `data/runs/full/` under the same file name. Reads (`GET /api/run/:runId`, startup restore, the report) use the full record while it exists. Sessions leave `agentflow/data/runs/full` out of the saved workspace (`ignoredPaths`), so the full record is there for the whole session and only the shortened copy comes back after a return visit; the report then says the run was saved shortened. - When the record fits again on a later save (a resumed run, for example), the full copy is deleted. ## Retention -After each save the server keeps the newest 20 finished runs (by start time) whose saved files, together with every paused run's, total at most 800,000 bytes. From the first run that would pass either limit, that run and every older finished run are deleted with their full copies, so the kept runs are always the newest ones. A paused run is never deleted, since the learner can still resume it, but its file counts toward the total. With `data/workflow.json`, this keeps `data/` within the session's save budget. +After each save the server keeps the newest 20 finished runs (by start time) whose saved files, together with every paused run's, total at most 800,000 bytes. From the first run that would pass either limit, that run and every older finished run are deleted with their full copies, so the kept runs are always the newest ones. A paused run is never deleted while it can still be resumed (saved less than `PAUSED_RUN_TTL_HOURS` ago, as for the startup restore), but its file counts toward the total. An older paused run is pruned like a finished one. The editor allows only one paused run at a time, so few are ever kept. With `data/workflow.json`, this keeps `data/` within the session's save budget. ## Active In-memory Runs