Public: anyone can read this; the crew can change it.

Finished run logs archive to the BlobStore #16710

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/4545-finished-run-logs-archive-to-the-blobsto → main 0 commits fork 2 threads · 2 unresolved

  • Merged. torque/4545-finished-run-logs-archive-to-the-blobsto was merged into main as d6e4708.

Review

Sign in to review this change.
17 files changed +454 −48
docs/BLOBS.md +13 −2
@@ -48,5 +48,16 @@ Blobs over a size policy are copied here by object id after a push and served by
4848
4949 ## Not here yet
5050
51 Archiving finished run logs and attachments onto the store and the cold-tier lifecycle are later steps of #4481, each with
52 its own issue.
51 Attachments and the cold-tier lifecycle are later steps of #4481, each with its own issue.
52
53 ## Run logs (#4545)
54
55 `src/runs/archive.ts`. Once a run is finished, the hourly sweep (`crew/dispatch.ts`, before the prune) puts `runs/<id>.log` to the store as `runs/<id>.log`, streamed from disk, class `infrequent`. The store is the bucket when `S3_*` is set, else `<data>/run-archive`. A put that fails leaves the file local for the next sweep; a local log is evicted only once the store holds the same number of bytes and it has been idle a day. The run page, the REST log and the MCP `run_log` bring an evicted finished log back from the store before reading it; a run in progress is never archived or restored, and its live tail is unchanged.
56
57 ## Packs: the repository in the bucket
58
59 `src/blob/packs.ts` (#4491, step 4 of #4481; the write path and the rebuild, the first slice). Inside `pre-receive`, after the forge's own checks pass and before git moves a ref, a push's new objects are written to the store as one pack (`packs/<owner>/<name>/pending/<hash>/<seq>.pack`). A store that fails, or gives no answer in 60 s, refuses the push with a 503 and nothing moves, so the pusher is acked only for a push the store holds. The record of its ref updates (`<seq>.json`) is written in `post-receive`, after git applied them: a push git then refused leaves a pack no record names, which a rebuild never reads. The first time the store is used for a repository that already has refs, its history is written first as a base record (`0000000000000-base.json` and `base.pack`), so a rebuild has what the first push's old values name.
60
61 `bun scripts/rebuild-repo.ts <data-dir> <owner> <name> <empty-target-dir>` makes a bare repository from nothing: it indexes each record's pack in order and replays its updates with `update-ref <ref> <new> <old>`, so a record that does not fit stops the rebuild and is named. The target must have no refs. A repository whose refs moved outside receive-pack (the web editor, merges) stops a rebuild at the first record whose old value they changed.
62
63 On when the forge has a bucket (`S3_*`) or `FORGE_PACK_STORE=dir` (a directory under the data directory); `FORGE_PACK_STORE=off` turns it off. Not done yet: pushes that skip receive-pack (web editor, merges), refs kept in the database, rebuilding on a missing repository at boot, evicting idle repositories, clearing packs no record names, and the scheduled repack and compaction on the primary.
docs/features/run-logs.md added +21
@@ -0,0 +1,21 @@
1 ---
2 topic: Your apps
3 row: Run logs: a finished run's log is kept in the BlobStore and read back when the local file is gone
4 ---
5 # Run logs
6
7 A run writes its log to a file under the forge's data. Once the run is finished, an hourly sweep copies the log to the BlobStore as `runs/<id>.log` (infrequent class), then removes the local file when nobody has touched it for a day and the store holds the same number of bytes. The store is the bucket when `S3_*` is set, else `<data>/run-archive`.
8
9 ## Read one
10
11 - Page: `/<owner>/<name>/runs/<id>`.
12 - Terminal: open the repository, then the run; the "Run log" screen (`src/tui/screens/runlog.ts`) reads it, `r` reads again.
13 - REST: `GET /api/v1/repos/<owner>/<name>/runs/<id>/log`. MCP: the `run_log` tool. Also the tail on a pull's page and `GET …/check.txt`.
14
15 Every one of these asks first whether the run is in this repository and the viewer may read its log; only then is an evicted log fetched back from the store, so a run id from another repository or a hidden log never reaches the store. A run still in progress is never archived or restored.
16
17 ## When the store is down
18
19 A log that fails to archive stays local and the next sweep tries again. The seven-day prune never removes the log of a finished run the store does not hold, and one sweep runs at a time.
20
21 Code: `src/runs/archive.ts`, `src/actions/runs.ts` (`runLog`), `src/runs/prune.ts`.
src/actions/runs.ts +6 −2
@@ -40,6 +40,7 @@ import { whenEnded } from "../runs/ending.ts";
4040 import { createLog } from "../kernel/log.ts";
4141 import { queueAgentRun, taskOf } from "../crew/dispatch.ts";
4242 import { err, ok, type Result } from "../kernel/result.ts";
43 import { restoreRunLog } from "../runs/archive.ts";
4344 import { readRunLog, readRunLogTail, runLogPath } from "../runs/log.ts";
4445 import { shownStates, type ShownState } from "../runs/state.ts";
4546 import { firstErrorLine } from "../runs/error_line.ts";
@@ -377,16 +378,19 @@ export interface RunLogView {
377378 readonly logHidden: boolean;
378379 }
379380
380 export function runLog(
381 export async function runLog(
381382 app: App,
382383 actor: User | undefined,
383384 repo: Repo,
384385 runId: string,
385386 tail?: number,
386 ): Result<RunLogView, "not_found"> {
387 ): Promise<Result<RunLogView, "not_found">> {
387388 const found = getRepoRun(app, actor, repo, runId);
388389 if (!found.ok) return found;
389390 const logHidden = !mayReadRunLog(app, actor, repo);
391 // The one place a log is brought back from the store: after the run is found here and the
392 // viewer may read it, never for a bare id (#4545).
393 if (!logHidden) await restoreRunLog(app.db, app.config.dataDir, runId);
390394 const { lines, truncated } = logHidden
391395 ? { lines: [], truncated: false }
392396 : tail === undefined
src/apps/preview_view.ts +2 −3
@@ -6,7 +6,7 @@
66 */
77
88 import type { App } from "../app.ts";
9 import { runLog } from "../actions/runs.ts";
9 import { getRepoRun, mayReadRunLog } from "../actions/runs.ts";
1010
1111 import { getPull } from "../core/pulls.ts";
1212 import { checkSummary, workingAgentRuns } from "../core/runs.ts";
@@ -67,8 +67,7 @@ export function previewOf(
6767 state === "ok" ? "green" : state === "failed" ? "red" : state === "running" || state === "queued" ? "running" : null;
6868 if (run !== null) {
6969 if (state === "failed") firstFailure = run.checkDetail?.names[0] ?? (run.summary || null);
70 const log = runLog(app, user, repo, run.id);
71 if (log.ok && !log.value.logHidden) logUrl = `${origin}/${name}/runs/${run.id}`;
70 if (getRepoRun(app, user, repo, run.id).ok && mayReadRunLog(app, user, repo)) logUrl = `${origin}/${name}/runs/${run.id}`;
7271 }
7372 }
7473 const working = new Set<string>();
src/crew/dispatch.ts +22 −2
@@ -50,6 +50,7 @@ import { authorsInRepoPull } from "./authors_pull.ts";
5050 import { closesFromBody, getPull, pullDir, type Pull } from "../core/pulls.ts";
5151 import { claimedClones, sweepIdleDependencies, sweepOrphanClones, sweepStaleClones } from "./orphans.ts";
5252 import { pruneRunFiles } from "../runs/prune.ts";
53 import { sweepRunLogs } from "../runs/archive.ts";
5354 import { crewRoot, isClaimed } from "./workdir.ts";
5455 import { resolveOpen } from "../core/decisions.ts";
5556 import { accountActive } from "../core/accounts.ts";
@@ -354,6 +355,7 @@ export async function startCrew(
354355 }
355356 }, options.tickMs ?? TICK_MS);
356357 // Clones no open issue, pull or run claims fill the volume (#5697).
358 let archiving = false;
357359 const sweepClones = (): void => {
358360 sweepOrphanClones(crewRoot(app.config.dataDir), claimedClones(app.db), isClaimed)
359361 .then((count) => {
@@ -369,8 +371,26 @@ export async function startCrew(
369371 if (kept > 0) log.info("kept idle clones holding unpushed work", { count: kept });
370372 })
371373 .catch((error) => log.warn("clone sweep failed", { error: String(error) }));
372 const pruned = pruneRunFiles(app.config.dataDir);
373 if (pruned > 0) log.info("removed old run logs", { count: pruned });
374 // Finished logs go to the store first, so the prune never removes the only copy (#4545).
375 // One sweep at a time: a slow store must not let two archive and evict the same log.
376 if (archiving) return;
377 archiving = true;
378 sweepRunLogs(app.db, app.config.dataDir)
379 .then(({ archived, evicted, failed, mayPrune }) => {
outdated

Prune runs even when archiving failed, so it can still remove the only copy after 7 days. Prune only logs the store holds, and keep sweeps from overlapping.

380 if (archived + failed > 0) log.info("archived finished run logs", { archived, evicted, failed });
381 return mayPrune;
382 })
383 .catch((error) => {
384 log.warn("run log archive failed", { error: String(error) });
385 return (name: string) => !name.endsWith(".log"); // no log goes while the store is unknown
386 })
387 .then((mayPrune) => {
388 const pruned = pruneRunFiles(app.config.dataDir, Date.now(), undefined, undefined, mayPrune);
389 if (pruned > 0) log.info("removed old run logs", { count: pruned });
390 })
391 .finally(() => {
392 archiving = false;
393 });
374394 };
375395 during("clone-sweep", sweepClones, undefined, app);
376396 const cloneTimer = setInterval(() => !stopped && during("clone-sweep", sweepClones, undefined, app), 60 * 60_000);
src/http/api.ts +4 −4
@@ -3447,13 +3447,13 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
34473447 // The log: text, or a live tail as server-sent events (`?follow=1`, or
34483448 // an `Accept: text/event-stream`). Lines already written come first,
34493449 // then each new one as it lands; `done` carries the finished run.
3450 router.add("GET", "/api/v1/repos/:owner/:name/runs/:id/log", (ctx) => {
3450 router.add("GET", "/api/v1/repos/:owner/:name/runs/:id/log", async (ctx) => {
34513451 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
34523452 const repo = loadRepo(ctx);
34533453 if (!repo) return notFound();
outdated

Restore happens before the run is checked against this repo or the viewer's access. Do it after runLog proves the run is visible here, then re-read.

3454 const found = timePhase(ctx.request, "log", () =>
3455 runLog(ctx.app, ctx.auth.user, repo, ctx.params.id ?? ""),
3456 );
3454 const reading = performance.now();
3455 const found = await runLog(ctx.app, ctx.auth.user, repo, ctx.params.id ?? "");
3456 notePhase(ctx.request, "log", performance.now() - reading);
34573457 if (!found.ok || found.value.logHidden) return notFound();
34583458 const follow =
34593459 ctx.url.searchParams.get("follow") === "1" ||
src/http/check_text.ts +28 −17
@@ -14,6 +14,7 @@
1414 */
1515
1616 import { getRepoRun, runLog } from "../actions/runs.ts";
17 import { restoreRunLog } from "../runs/archive.ts";
1718 import { readRunLogTail } from "../runs/log.ts";
1819 import { checkSummary } from "../core/runs.ts";
1920 import { loadPull } from "./api.ts";
@@ -54,7 +55,7 @@ export async function checkText(ctx: Ctx): Promise<Response> {
5455 const seconds = waitOf(ctx.url);
5556 if (seconds === null)
5657 return apiError("invalid_wait", 400, `wait is a whole number of seconds from ${WAIT_MIN} to ${WAIT_MAX}`);
57 const first = read(ctx);
58 const first = await read(ctx);
5859 if (first instanceof Response || seconds === undefined) return first instanceof Response ? first : first.response;
5960
6061 // Only a contribute token's holds are counted: it is the credential an agent leaves running.
@@ -99,7 +100,7 @@ export async function checkText(ctx: Ctx): Promise<Response> {
99100 } finally {
100101 release();
101102 }
102 const last = read(ctx);
103 const last = await read(ctx);
103104 return last instanceof Response ? last : last.response;
104105 }
105106
@@ -125,12 +126,12 @@ function verdict(ctx: Ctx) {
125126 */
126127 const TAIL_TTL_MS = 5000;
127128 const TAIL_KEPT = 32;
128 type Tail = { at: number; lines: string[] };
129 type Tail = { at: number; lines: Promise<string[]> };
129130 const tailsOf = new WeakMap<object, Map<string, Tail>>();
130131
131 function tailOf(ctx: Ctx, v: Extract<Verdict, { word: string }>): string[] {
132 function tailOf(ctx: Ctx, v: Extract<Verdict, { word: string }>): Promise<string[]> {
132133 const run = v.run;
133 if (!run) return [];
134 if (!run) return Promise.resolve([]);
134135 // A contribute token reaching here is the pull's own author (the gate): its log is its to read.
135136 const own = ctx.auth.contribute !== undefined && ctx.auth.user?.id === v.pull.authorId;
136137 let tails = tailsOf.get(ctx.app);
@@ -139,27 +140,37 @@ function tailOf(ctx: Ctx, v: Extract<Verdict, { word: string }>): string[] {
139140 const hit = tails.get(key);
140141 const now = Date.now();
141142 if (hit && now - hit.at < TAIL_TTL_MS) return hit.lines;
142 let lines: string[];
143 if (own) {
144 lines = getRepoRun(ctx.app, ctx.auth.user, v.repo, run.id).ok
145 ? readRunLogTail(ctx.app.config.dataDir, run.id, TAIL_MAX).lines
146 : [];
147 } else {
148 const log = runLog(ctx.app, ctx.auth.user, v.repo, run.id, TAIL_MAX);
149 lines = log.ok && !log.value.logHidden ? log.value.lines : [];
150 }
151 lines = lines.slice(-TAIL_MAX);
143 // The promise is what is kept, so waiters released together share one read.
144 const lines = tailRead(ctx, v, run, own);
152145 if (tails.size >= TAIL_KEPT) tails.delete(tails.keys().next().value!);
153146 tails.set(key, { at: now, lines });
154147 return lines;
155148 }
156149
157 function read(ctx: Ctx): (Reading & { pullId: string }) | Response {
150 async function tailRead(
151 ctx: Ctx,
152 v: Extract<Verdict, { word: string }>,
153 run: NonNullable<Extract<Verdict, { word: string }>["run"]>,
154 own: boolean,
155 ): Promise<string[]> {
156 let lines: string[];
157 if (own) {
158 const seen = getRepoRun(ctx.app, ctx.auth.user, v.repo, run.id).ok;
159 if (seen) await restoreRunLog(ctx.app.db, ctx.app.config.dataDir, run.id);
160 lines = seen ? readRunLogTail(ctx.app.config.dataDir, run.id, TAIL_MAX).lines : [];
161 } else {
162 const log = await runLog(ctx.app, ctx.auth.user, v.repo, run.id, TAIL_MAX);
163 lines = log.ok && !log.value.logHidden ? log.value.lines : [];
164 }
165 return lines.slice(-TAIL_MAX);
166 }
167
168 async function read(ctx: Ctx): Promise<(Reading & { pullId: string }) | Response> {
158169 const v = verdict(ctx);
159170 if ("error" in v) return v.error;
160171 let body = `${v.word}\nhead: ${v.pull.headOid}\n`;
161172 if (v.word === "red" && v.run) {
162 const lines = tailOf(ctx, v);
173 const lines = await tailOf(ctx, v);
163174 if (lines.length > 0) body += `\n${lines.join("\n")}\n`;
164175 }
165176 return {
src/http/mcp/tools/run_log.ts +2 −2
@@ -20,7 +20,7 @@ export const tool: Tool = {
2020 required: ["repo", "run"],
2121 },
2222 writes: false,
23 run(ctx, user, args) {
23 async run(ctx, user, args) {
2424 const tail = args["tail"];
2525 if (
2626 typeof args["run"] !== "string" ||
@@ -35,7 +35,7 @@ export const tool: Tool = {
3535 return bad("invalid", "`run` is a run id; `tail` is 1 to 2000 lines");
3636 const repo = repoArg(ctx, user, args);
3737 if (isAnswer(repo)) return repo;
38 const found = runLog(ctx.app, user, repo, args["run"]);
38 const found = await runLog(ctx.app, user, repo, args["run"]);
3939 // A hidden log is not found, as on the REST route.
4040 if (!found.ok || found.value.logHidden)
4141 return bad("not_found", "no such run here");
src/runs/archive.ts added +154
@@ -0,0 +1,154 @@
1 /**
2 * Finished run logs on the BlobStore (#4545, step 2 of #4481). A log is one
3 * append-and-tail file (`log.ts`); once its run is finished it is put to the
4 * store under `runs/<id>.log`, streamed from disk, in the infrequent class,
5 * and the local file becomes a cache that a sweep may evict. A read of a
6 * finished log whose file is gone streams it back into place
7 * (`restoreRunLog`); the live tail never touches the store.
8 *
9 * The store is resolved from the data directory on each use: the bucket when the forge
10 * has `S3_*`, otherwise a directory under the data directory. A log that
11 * fails to put stays local and the next sweep tries again; the file is only
12 * ever evicted after the store says it holds as many bytes as the file.
13 */
14
15 import { existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync } from "node:fs";
16 import { dirname, join } from "node:path";
17 import { dirStore, s3FromEnv, s3Store, withRetries, type BlobStore } from "../blob/store.ts";
18 import { getRun, isTerminal } from "../core/runs.ts";
19 import type { Database } from "bun:sqlite";
20 import { flushRunLogs, runLogPath, runsRoot } from "./log.ts";
21
22 /** A local log nobody has touched for this long, and held by the store, is evicted. */
23 export const EVICT_AFTER_MS = 24 * 3_600_000;
24
25 const SAFE_ID = /^[A-Za-z0-9_.-]{1,80}$/;
26 const LOG_NAME = /^([A-Za-z0-9_.-]{1,80})\.log$/;
27
28 export const archiveKey = (runId: string): string => `runs/${runId}.log`;
29
30 /** The run-log store of this data directory; holds no state, so it is made per call. */
31 export function runLogStore(
32 dataDir: string,
33 env: Record<string, string | undefined> = process.env,
34 ): BlobStore {
35 const target = s3FromEnv(env);
36 return withRetries(
37 target !== undefined ? s3Store(target, 2) : dirStore(join(dataDir, "run-archive")),
38 );
39 }
40
41 /** Put one finished run's log to the store; whether the store now holds it. */
42 export async function archiveRunLog(store: BlobStore, dataDir: string, runId: string): Promise<boolean> {
43 if (!SAFE_ID.test(runId)) return false;
44 const path = runLogPath(dataDir, runId);
45 const file = Bun.file(path);
46 if (!(await file.exists())) return false;
47 const size = file.size;
48 try {
49 if ((await store.size(archiveKey(runId))) !== size)
50 await store.put(archiveKey(runId), file, undefined, {
51 storageClass: "infrequent",
52 type: "text/plain",
53 });
54 return (await store.size(archiveKey(runId))) === size;
55 } catch {
56 return false; // stays local; the next sweep tries again
57 }
58 }
59
60 export interface ArchiveSweep {
61 readonly archived: number;
62 readonly evicted: number;
63 readonly failed: number;
64 /**
65 * File names under `runs/` the prune may remove: every one but the log of a finished run the
66 * store does not hold. A sweep that could not even list `runs/` holds none of them.
67 */
68 readonly mayPrune: (name: string) => boolean;
69 }
70
71 /**
72 * Archive every finished run's log under `runs/` (naming those it could not, so the prune leaves
73 * them) and evict the archived ones last written `evictAfterMs` ago or more. A run not finished (or
74 * unknown) is left alone.
75 */
76 export async function sweepRunLogs(
77 db: Database,
78 dataDir: string,
79 store: BlobStore = runLogStore(dataDir),
80 now: number = Date.now(),
81 evictAfterMs: number = EVICT_AFTER_MS,
82 ): Promise<ArchiveSweep> {
83 flushRunLogs();
84 let names: string[];
85 try {
86 names = readdirSync(runsRoot(dataDir));
87 } catch {
88 return { archived: 0, evicted: 0, failed: 0, mayPrune: (name) => !LOG_NAME.test(name) };
89 }
90 const unheld = new Set<string>();
91 let archived = 0;
92 let evicted = 0;
93 let failed = 0;
94 for (const name of names) {
95 const id = LOG_NAME.exec(name)?.[1];
96 if (id === undefined) continue;
97 const run = getRun(db, id);
98 if (run === undefined || !isTerminal(run.state)) continue;
99 unheld.add(name);
100 const path = runLogPath(dataDir, id);
101 let mtime: number;
102 try {
103 mtime = statSync(path).mtimeMs;
104 } catch {
105 unheld.delete(name);
106 continue;
107 }
108 if (!(await archiveRunLog(store, dataDir, id))) {
109 failed++;
110 continue;
111 }
112 archived++;
113 unheld.delete(name);
114 if (now - mtime >= evictAfterMs) {
115 rmSync(path, { force: true });
116 evicted++;
117 }
118 }
119 return { archived, evicted, failed, mayPrune: (name) => !unheld.has(name) };
120 }
121
122 /**
123 * Bring a finished run's log back to its local file when the file is gone and
124 * the store holds it, so every reader of the file sees it. Never for a run
125 * not finished: its file is the live log.
126 */
127 export async function restoreRunLog(
128 db: Database,
129 dataDir: string,
130 runId: string,
131 store: BlobStore = runLogStore(dataDir),
132 ): Promise<boolean> {
133 if (!SAFE_ID.test(runId)) return false;
134 const path = runLogPath(dataDir, runId);
135 if (existsSync(path)) return false;
136 const run = getRun(db, runId);
137 if (run === undefined || !isTerminal(run.state)) return false;
138 try {
139 const stream = await store.getStream(archiveKey(runId));
140 if (stream === undefined) return false;
141 mkdirSync(dirname(path), { recursive: true });
142 const part = `${path}.part-${process.pid}-${Bun.nanoseconds()}`;
143 const sink = Bun.file(part).writer();
144 try {
145 for await (const chunk of stream) sink.write(chunk);
146 } finally {
147 await sink.end();
148 }
149 renameSync(part, path);
150 return true;
151 } catch {
152 return false;
153 }
154 }
src/runs/prune.ts +6 −3
@@ -24,6 +24,8 @@ export function pruneRunFiles(
2424 now: number = Date.now(),
2525 maxAgeMs: number = RUN_FILES_KEEP_MS,
2626 maxBytes: number = RUN_FILES_MAX_BYTES,
27 /** False for a file that must stay: a finished run's log the store does not hold yet (#4545). */
28 mayRemove: (name: string) => boolean = () => true,
2729 ): number {
2830 const root = runsRoot(dataDir);
2931 let removed = 0;
@@ -33,16 +35,16 @@ export function pruneRunFiles(
3335 } catch {
3436 return 0;
3537 }
36 const kept: { path: string; mtime: number; size: number }[] = [];
38 const kept: { path: string; mtime: number; size: number; name: string }[] = [];
3739 for (const name of names) {
3840 const path = join(root, name);
3941 try {
4042 const st = statSync(path);
4143 if (!st.isFile()) continue;
42 if (now - st.mtimeMs > maxAgeMs) {
44 if (now - st.mtimeMs > maxAgeMs && mayRemove(name)) {
4345 rmSync(path, { force: true });
4446 removed++;
45 } else kept.push({ path, mtime: st.mtimeMs, size: st.size });
47 } else kept.push({ path, mtime: st.mtimeMs, size: st.size, name });
4648 } catch {
4749 // gone already, or busy: the next sweep looks again
4850 }
@@ -51,6 +53,7 @@ export function pruneRunFiles(
5153 kept.sort((a, b) => a.mtime - b.mtime);
5254 for (const f of kept) {
5355 if (total <= maxBytes) break;
56 if (!mayRemove(f.name)) continue;
5457 try {
5558 rmSync(f.path, { force: true });
5659 removed++;
src/tui/screens/runlog.ts +7 −8
@@ -45,8 +45,8 @@ export function runLogScreen(
4545 let price = "";
4646 let follow = true;
4747
48 const read = (): void => {
49 const got = runLog(f.app, f.user, repo, runId, LOG_LINES);
48 const read = async (): Promise<void> => {
49 const got = await runLog(f.app, f.user, repo, runId, LOG_LINES);
5050 // A hidden log is "not found", as the REST route says it.
5151 view = got.ok && !got.value.logHidden ? got.value : undefined;
5252 lines = // The tail window can hold a few more than asked for.
@@ -81,8 +81,8 @@ export function runLogScreen(
8181 ...(offer() ? [binding(["a"], "start now on your own account")] : []),
8282 ];
8383 },
84 load(signal) {
85 read();
84 async load(signal) {
85 await read();
8686 // New lines arrive from the log's own listener, never from a reread.
8787 subscribeRunLog(
8888 runId,
@@ -108,10 +108,9 @@ export function runLogScreen(
108108 () => {
109109 // Nothing loaded (hidden, not found) or finished: nothing to follow.
110110 if (view === undefined || !isLive(view.run.state)) return;
111 read();
111 void read();
112112 },
113113 );
114 return Promise.resolve();
115114 },
116115 render(area, s) {
117116 const c = ctx.theme.c;
@@ -209,7 +208,7 @@ export function runLogScreen(
209208 runAsync(ctx, async () => {
210209 const started = await startNowWithOwnToken(f.app, f.user, run, token);
211210 ctx.toast(started.ok ? "Saved as your own account; the build is starting on it." : START_NOW_WORDS[started.error], started.ok ? "success" : "danger");
212 read();
211 await read();
213212 });
214213 return undefined;
215214 },
@@ -222,7 +221,7 @@ export function runLogScreen(
222221 return true;
223222 }
224223 if (e.key === "r" && !e.ctrl && !e.alt) {
225 read();
224 void read();
226225 return true;
227226 }
228227 if (view === undefined) return false;
src/web/pages/runs.ts +1 −1
@@ -393,7 +393,7 @@ export async function runPage(ctx: Ctx): Promise<Response> {
393393 if (!repo) return notFoundPage(ctx);
394394 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
395395 const reading = performance.now();
396 const found = runLog(ctx.app, ctx.auth.user, repo, ctx.params.id ?? "");
396 const found = await runLog(ctx.app, ctx.auth.user, repo, ctx.params.id ?? "");
397397 notePhase(ctx.request, "log", performance.now() - reading);
398398 if (!found.ok) return notFoundPage(ctx);
399399 const { run, lines, truncated, logHidden } = found.value;
src/web/studio/app.ts +2 −1
@@ -67,7 +67,7 @@ import { migrationRegion } from "./migration.ts";
6767 import { adapterCard } from "./adapter.ts";
6868 import { jobsLink } from "./jobs.ts";
6969 import { schedulesCard } from "./schedules.ts";
70 import { appPanels } from "./previews.ts";
70 import { appPanels, warmProductionLog } from "./previews.ts";
7171 import { contributeSteps } from "./contribute_steps.ts";
7272 import { noCrewLine, pausedWords, servingHistory, type WordCtx } from "./words.ts";
7373 import { crewKeyCard, includedCredit } from "./crew_key.ts";
@@ -301,6 +301,7 @@ export async function studioApp(
301301 ctx.auth.user?.id,
302302 ),
303303 );
304 await warmProductionLog(ctx, repo, record);
304305 const { head, previews, deployTailing, fresh, history } = timePhase(req, "panels", () =>
305306 appPanels(ctx, repo, record, openPulls, picture.history),
306307 );
src/web/studio/change.ts +4 −1
@@ -9,6 +9,7 @@
99 * bigger.
1010 */
1111
12 import { restoreRunLog } from "../../runs/archive.ts";
1213 import type { Database } from "bun:sqlite";
1314 import { pausedSentence } from "../../crew/paused_now.ts";
1415 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
@@ -848,8 +849,10 @@ async function changeConversation(
848849 const log = await commitLog(wordCtx.dir, headOid, { limit: Math.min(Math.max(status?.ahead ?? 20, 1), 50) });
849850 return log.ok ? log.value : [];
850851 });
852 const mayTail = check.run !== null && mayReadRunLog(ctx.app, ctx.auth.user, repo);
853 if (mayTail && check.run !== null) await restoreRunLog(ctx.app.db, ctx.app.config.dataDir, check.run.id);
851854 const kept =
852 check.run !== null && mayReadRunLog(ctx.app, ctx.auth.user, repo)
855 check.run !== null && mayTail
853856 ? readRunLogTail(ctx.app.config.dataDir, check.run.id, 60)
854857 : undefined;
855858 const folds = pullFolds({
src/web/studio/now.ts +2 −1
@@ -30,7 +30,7 @@ import { fragment, missingFragment } from "../layout.ts";
3030 import { avatar, badge, btn, disclosure, icon, listCard, row, time } from "../ui.ts";
3131 import { changeHref, tellHref } from "./nouns.ts";
3232 import { LOG_TAIL_CAP, logBox } from "./log.ts";
33 import { appPanels } from "./previews.ts";
33 import { appPanels, warmProductionLog } from "./previews.ts";
3434 import { stopForm } from "./run.ts";
3535 import { tellWords } from "./tell.ts";
3636 import { voiceFor, type Actor } from "./voice.ts";
@@ -370,6 +370,7 @@ export async function appNowFragment(ctx: Ctx): Promise<Response> {
370370 );
371371 // The one fact Now borrows from the head card, decided where the head
372372 // card decides it, so the two never disagree about what is tailing.
373 await warmProductionLog(ctx, repo, record);
373374 const { deployTailing, fresh } = timePhase(req, "panels", () =>
374375 appPanels(ctx, repo, record, openPulls),
375376 );
src/web/studio/previews.ts +13 −1
@@ -7,6 +7,7 @@
77 * deploy event refreshes (`appStateFragment`) share.
88 */
99
10 import { restoreRunLog } from "../../runs/archive.ts";
1011 import { frontPulls } from "./front_pulls.ts";
1112 import { sshOn } from "../../settings/ssh.ts";
1213 import { appCacheSize } from "../../apps/build_cache.ts";
@@ -288,6 +289,16 @@ export function deployFailing(env: EnvStatus | undefined): boolean {
288289 return env?.error !== undefined || env?.failedDeploy !== undefined;
289290 }
290291
292 /**
293 * The finished deploy's log, back from the store when its file was evicted, before
294 * `appPanels` reads the tail of it (#4545); the page is the viewer's to read first.
295 */
296 export async function warmProductionLog(ctx: Ctx, repo: Repo, record: AppRecord): Promise<void> {
297 if (!canSeeOwnerFacts(ctx.app.db, repo, ctx.auth.user)) return;
298 const production = envsFor(ctx.app, ctx.auth.user, record).find((e) => e.env === "production");
299 if (production?.runId !== undefined) await restoreRunLog(ctx.app.db, ctx.app.config.dataDir, production.runId);
300 }
301
291302 export function appPanels(
292303 ctx: Ctx,
293304 repo: Repo,
@@ -398,13 +409,14 @@ function buildCacheLine(ctx: Ctx, repo: Repo, record: AppRecord, base: string):
398409 * serving in its preview shows up without a reload. Authorized exactly as
399410 * the studio page: a viewer who cannot see the app gets the same 404.
400411 */
401 export function appStateFragment(ctx: Ctx): Response {
412 export async function appStateFragment(ctx: Ctx): Promise<Response> {
402413 const req = ctx.request;
403414 notePhase(req, "session", takeSessionTime(req));
404415 const repo = timePhase(req, "repo", () => loadRepo(ctx));
405416 const record = repo && timePhase(req, "record", () => getAppByRepo(ctx.app.db, repo.id));
406417 if (!repo || !record) return missingFragment(req);
407418 const openPulls = timePhase(req, "pulls", () => frontPulls(ctx.app.db, repo, ctx.auth.user));
419 await warmProductionLog(ctx, repo, record);
408420 const { head, previews } = timePhase(req, "panels", () =>
409421 appPanels(ctx, repo, record, openPulls),
410422 );
test/run-log-archive.test.ts added +167
@@ -0,0 +1,167 @@
1 /** Finished run logs archive to the BlobStore, are evicted locally, and still read (#4545). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { existsSync } from "node:fs";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp, type App } from "../src/app.ts";
8 import { createRepo } from "../src/actions/repos.ts";
9 import { createRun, finishRun } from "../src/core/runs.ts";
10 import type { BlobStore } from "../src/blob/store.ts";
11 import { serve, type Servers } from "../src/http/server.ts";
12 import { appendRunLog, runLogPath } from "../src/runs/log.ts";
13 import { pruneRunFiles } from "../src/runs/prune.ts";
14 import { archiveKey, restoreRunLog, runLogStore, sweepRunLogs } from "../src/runs/archive.ts";
15 import { seedAdmin } from "./helpers/admin.ts";
16
17 let dataDir = "";
18 let app: App, servers: Servers, repoId = "", otherId = "", bearer = "";
19 let store: BlobStore;
20
21 beforeAll(async () => {
22 dataDir = await mkdtemp(join(tmpdir(), "forge-runarchive-"));
23 app = createApp({ dataDir, port: 0 });
24 servers = await serve(app);
25 store = runLogStore(dataDir);
26 const admin = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
27 if (!admin.ok) throw new Error(admin.error);
28 const made = await createRepo(app, admin.value, { name: "notes", visibility: "public", description: "" });
29 if (!made.ok) throw new Error(String(made.error));
30 repoId = made.value.id;
31 const other = await createRepo(app, admin.value, { name: "elsewhere", visibility: "public", description: "" });
32 if (!other.ok) throw new Error(String(other.error));
33 otherId = other.value.id;
34 const minted = await fetch(`${servers.url}/api/v1/tokens`, {
35 method: "POST",
36 headers: { "content-type": "application/json" },
37 body: JSON.stringify({ adminConfirm: true, username: "alice", password: "correct-horse-battery", name: "cli", scope: "admin" }),
38 });
39 bearer = ((await minted.json()) as { token: string }).token;
40 });
41
42 afterAll(async () => {
43 servers.stop();
44 app.close();
45 await rm(dataDir, { recursive: true, force: true });
46 });
47
48 const running = (id: string): void => void app.db.query("UPDATE run SET state = 'running' WHERE id = ?1").run(id);
49
50 test("a finished run is archived, evicted, and /runs/<id> still shows the log", async () => {
51 const run = createRun(app.db, { repoId, kind: "check" });
52 appendRunLog(dataDir, run.id, "hello from the archive");
53 running(run.id);
54 finishRun(app.db, run.id, { state: "ok", summary: "fine" });
55 const swept = await sweepRunLogs(app.db, dataDir, store, Date.now() + 1000, 0);
56 expect(swept).toMatchObject({ archived: 1, evicted: 1, failed: 0 });
57 expect(existsSync(runLogPath(dataDir, run.id))).toBe(false);
58 expect(await store.size(archiveKey(run.id))).toBeGreaterThan(0);
59 const page = await fetch(`${servers.url}/alice/notes/runs/${run.id}`, { headers: { authorization: `Bearer ${bearer}` } });
60 expect(page.status).toBe(200);
61 expect(await page.text()).toContain("hello from the archive");
62 expect(existsSync(runLogPath(dataDir, run.id))).toBe(true);
63 const api = await fetch(`${servers.url}/api/v1/repos/alice/notes/runs/${run.id}/log`, {
64 headers: { authorization: `Bearer ${bearer}` },
65 });
66 expect(await api.text()).toContain("hello from the archive");
67 });
68
69 test("a run still in progress is never archived", async () => {
70 const run = createRun(app.db, { repoId, kind: "check" });
71 running(run.id);
72 appendRunLog(dataDir, run.id, "still going");
73 await sweepRunLogs(app.db, dataDir, store, Date.now() + 1000, 0);
74 expect(existsSync(runLogPath(dataDir, run.id))).toBe(true);
75 expect(await store.size(archiveKey(run.id))).toBeUndefined();
76 expect(await restoreRunLog(app.db, dataDir, run.id, store)).toBe(false);
77 });
78
79 test("a log that fails to archive stays local and is retried by the next sweep", async () => {
80 const run = createRun(app.db, { repoId, kind: "check" });
81 appendRunLog(dataDir, run.id, "keep me");
82 running(run.id);
83 finishRun(app.db, run.id, { state: "failed", summary: "x" });
84 let broken = true;
85 const flaky: BlobStore = {
86 ...store,
87 put: (...args) => (broken ? Promise.reject(new Error("down")) : store.put(...args)),
88 };
89 const first = await sweepRunLogs(app.db, dataDir, flaky, Date.now() + 1000, 0);
90 expect(first.failed).toBe(1);
91 expect(first.evicted).toBe(0);
92 expect(existsSync(runLogPath(dataDir, run.id))).toBe(true);
93 broken = false;
94 const second = await sweepRunLogs(app.db, dataDir, flaky, Date.now() + 1000, 0);
95 expect(second.evicted).toBeGreaterThanOrEqual(1);
96 expect(await store.size(archiveKey(run.id))).toBeGreaterThan(0);
97 });
98
99 /** A finished run with a log, written then archived and evicted at once. */
100 async function evicted(repo: string, text: string): Promise<string> {
101 const run = createRun(app.db, { repoId: repo, kind: "check" });
102 appendRunLog(dataDir, run.id, text);
103 running(run.id);
104 finishRun(app.db, run.id, { state: "ok", summary: "fine" });
105 await sweepRunLogs(app.db, dataDir, store, Date.now() + 1000, 0);
106 expect(existsSync(runLogPath(dataDir, run.id))).toBe(false);
107 return run.id;
108 }
109
110 test("a log newer than the eviction age is archived and stays local", async () => {
111 const run = createRun(app.db, { repoId, kind: "check" });
112 appendRunLog(dataDir, run.id, "young");
113 running(run.id);
114 finishRun(app.db, run.id, { state: "ok", summary: "fine" });
115 const swept = await sweepRunLogs(app.db, dataDir, store);
116 expect(swept.failed).toBe(0);
117 expect(existsSync(runLogPath(dataDir, run.id))).toBe(true);
118 expect(await store.size(archiveKey(run.id))).toBeGreaterThan(0);
119 });
120
121 test("a run id from another repository is not restored by this one's routes", async () => {
122 const id = await evicted(otherId, "belongs to elsewhere");
123 const page = await fetch(`${servers.url}/alice/notes/runs/${id}`, { headers: { authorization: `Bearer ${bearer}` } });
124 expect(page.status).toBe(404);
125 const api = await fetch(`${servers.url}/api/v1/repos/alice/notes/runs/${id}/log`, {
126 headers: { authorization: `Bearer ${bearer}` },
127 });
128 expect(api.status).toBe(404);
129 expect(existsSync(runLogPath(dataDir, id))).toBe(false);
130 });
131
132 test("the MCP run_log tool brings an evicted log back", async () => {
133 const id = await evicted(repoId, "read over mcp");
134 const res = await fetch(`${servers.url}/mcp`, {
135 method: "POST",
136 headers: {
137 "content-type": "application/json",
138 accept: "application/json, text/event-stream",
139 authorization: `Bearer ${bearer}`,
140 },
141 body: JSON.stringify({
142 jsonrpc: "2.0",
143 id: 1,
144 method: "tools/call",
145 params: { name: "run_log", arguments: { repo: "alice/notes", run: id } },
146 }),
147 });
148 const body = (await res.json()) as { result: { content: { text: string }[] } };
149 expect(JSON.parse(body.result.content[0]!.text).lines).toEqual(["read over mcp"]);
150 });
151
152 test("the prune keeps the log of a finished run the store does not hold, and removes it once held", async () => {
153 const run = createRun(app.db, { repoId, kind: "check" });
154 appendRunLog(dataDir, run.id, "only copy");
155 running(run.id);
156 finishRun(app.db, run.id, { state: "ok", summary: "fine" });
157 const down: BlobStore = { ...store, put: () => Promise.reject(new Error("down")) };
158 const old = Date.now() + 30 * 86_400_000;
159 const failed = await sweepRunLogs(app.db, dataDir, down, old, 365 * 86_400_000);
160 expect(failed.failed).toBeGreaterThanOrEqual(1);
161 pruneRunFiles(dataDir, old, undefined, undefined, failed.mayPrune);
162 expect(existsSync(runLogPath(dataDir, run.id))).toBe(true);
163 const held = await sweepRunLogs(app.db, dataDir, store, old, 365 * 86_400_000);
164 pruneRunFiles(dataDir, old, undefined, undefined, held.mayPrune);
165 expect(existsSync(runLogPath(dataDir, run.id))).toBe(false);
166 expect(await store.size(archiveKey(run.id))).toBeGreaterThan(0);
167 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs