mirror of
https://github.com/storytold/autocraft.git
synced 2026-11-29 09:33:55 +01:00
Job logs: the runner copies the end of each job's log into the database
The runner copies the new whole lines of a running job's log file into job_log_chunks every 5 seconds and once at its end (one INSERT per copy, one DELETE of the oldest chunks once a job passes 256 KiB plus slack), and command-line runs do the same. The job page reads the log file when it is on its disk and the stored chunks otherwise, so a dashboard that does not share the runner's volume shows job logs. pruneJobs deletes the chunks with the job.
This commit is contained in:
1 parent
0a39282973
commit
824e8a10e4
10 files changed
+227
-10
No files matched your search
+2
-2
@@ -523,7 +523,7 @@ It reads the same variables as the CLI (`AUTOCRAFT_DB` and the rest), plus:
|
||||
|
||||
| Variable | Meaning |
|
||||
|---|---|
|
||||
| `AUTOCRAFT_RUNNER_LOGS` | Directory of the per-job log files. Default `~/.cache/autocraft-logs/jobs`. The dashboard reads each job's log from the path recorded in its row, so it must run as a user who can read this directory. |
|
||||
| `AUTOCRAFT_RUNNER_LOGS` | Directory of the per-job log files. Default `~/.cache/autocraft-logs/jobs`. The runner also copies the last 256 KiB of each job's log into the database (`job_log_chunks`, every 5 seconds while the job runs and once at its end). The dashboard reads a job's log from the path recorded in its row when it can, and otherwise from the database, so a dashboard on another disk shows logs up to 5 seconds behind. |
|
||||
| `AUTOCRAFT_RUNNER_JOBS` | Most jobs running at once. Default 32. A job whose step calls Claude also waits for a free account slot before it starts. Jobs of one step run together only for different repos, within the `step_parallel` setting (`autocraft-server pipeline parallel [N|none]`, default 1). |
|
||||
| `AUTOCRAFT_RUNNER_POLL_MS` | Poll interval. Default 2000. |
|
||||
| `AUTOCRAFT_CALL_IDLE_MIN` | Minutes a Claude call may produce no output (no assistant text, tool use, tool result or progress line) before its process group is stopped (SIGTERM, then SIGKILL after 10 s) and the call fails with `no output for <n> min; stopped`. Default 15. Time spent inside a pending build-tool call (it waits on a worker, up to 45 minutes in all) does not count. |
|
||||
@@ -845,7 +845,7 @@ Every path is set by an environment variable. When a variable is unset, the code
|
||||
|
||||
### Logs
|
||||
|
||||
The dashboard, the runner, sync and backup write to stdout and stderr. The runner also writes one file per job under `AUTOCRAFT_RUNNER_LOGS`.
|
||||
The dashboard, the runner, sync and backup write to stdout and stderr. The runner also writes one file per job under `AUTOCRAFT_RUNNER_LOGS`, and keeps the end of each in the database.
|
||||
|
||||
### Health endpoints
|
||||
|
||||
|
||||
@@ -1051,6 +1051,13 @@ export interface JobItems {
|
||||
ref: string | null;
|
||||
}
|
||||
|
||||
export interface JobLogChunks {
|
||||
job_id: number;
|
||||
seq: number;
|
||||
start: number;
|
||||
chunk: string;
|
||||
}
|
||||
|
||||
export interface Jobs {
|
||||
id: Generated<number>;
|
||||
step: string;
|
||||
@@ -2272,6 +2279,7 @@ export interface DB {
|
||||
item_stage: ItemStage;
|
||||
items: Items;
|
||||
job_items: JobItems;
|
||||
job_log_chunks: JobLogChunks;
|
||||
jobs: Jobs;
|
||||
lane_next: LaneNext;
|
||||
liveness_items: LivenessItems;
|
||||
@@ -2450,6 +2458,7 @@ export interface DB {
|
||||
"main.item_stage": ItemStage;
|
||||
"main.items": Items;
|
||||
"main.job_items": JobItems;
|
||||
"main.job_log_chunks": JobLogChunks;
|
||||
"main.jobs": Jobs;
|
||||
"main.lane_next": LaneNext;
|
||||
"main.liveness_items": LivenessItems;
|
||||
@@ -2632,6 +2641,7 @@ export const COLUMNS = {
|
||||
item_stage: ["repo", "number", "stage", "at", "reviewed"],
|
||||
items: ["repo", "number", "kind", "state", "title", "body", "url", "author", "author_type", "author_association", "created_at", "updated_at", "closed_at", "merged_at", "merged_by", "state_reason", "is_draft", "labels", "assignees", "comments_count", "reactions_count", "additions", "deletions", "changed_files", "head_ref", "head_oid", "head_repo", "base_ref", "maintainer_can_modify", "mergeable", "review_decision", "ci_state", "closing_issues", "detail_level", "embed_hash", "class_hash", "class_scheme", "text_refs", "author_id"],
|
||||
job_items: ["id", "job_id", "repo", "number", "outcome", "at", "ref"],
|
||||
job_log_chunks: ["job_id", "seq", "start", "chunk"],
|
||||
jobs: ["id", "step", "params", "requested_by", "requested_at", "state", "started_at", "ended_at", "progress", "summary", "error", "usage", "log_path", "pid", "cancel_requested_at", "cancel_requested_by", "repo", "items", "acted", "resumes", "lease_skips", "lease_skip_keys"],
|
||||
lane_next: ["lane", "total", "items", "at"],
|
||||
liveness_items: ["repo", "number", "kind", "verdict", "cause", "state", "wait", "phase", "since", "checked_at"],
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// (requested by `cli`, so counted toward the limits and visible on the Pipeline page), and the runner's exec child, whose
|
||||
// output is shown here. The writer is an operator (CLI_BY): the guard skips the global switch, the approvals still apply.
|
||||
// Commands not listed in CLI_STEPS, and runs with options a step has no parameter for, keep their own direct path.
|
||||
import { JOB_LOG_FLUSH_MS, JobLogCopy } from "./job-log.ts";
|
||||
import { spawn } from "node:child_process";
|
||||
import { closeSync, createWriteStream, mkdirSync, openSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
@@ -75,6 +76,8 @@ export async function runCliJob(db: Db, req: CliRequest): Promise<number> {
|
||||
closeSync(openSync(logPath, "a"));
|
||||
await db.run(db.k.updateTable("jobs").set({ log_path: logPath }).where("id", "=", job));
|
||||
const log = createWriteStream(logPath, { flags: "a" });
|
||||
const logCopy = await JobLogCopy.open(db, job, logPath);
|
||||
const copying = setInterval(() => void logCopy.flush().catch(() => { /* the next copy retries */ }), JOB_LOG_FLUSH_MS);
|
||||
const child = spawn(process.execPath, [fileURLToPath(new URL("../cli.ts", import.meta.url)), "runner", "exec", String(job)], {
|
||||
stdio: ["ignore", "pipe", "pipe"], env: dbEnv(dbTarget()),
|
||||
});
|
||||
@@ -85,8 +88,10 @@ export async function runCliJob(db: Db, req: CliRequest): Promise<number> {
|
||||
let spawnError: string | null = null;
|
||||
child.on("error", (e) => (spawnError = e.message));
|
||||
const [code, signal] = await new Promise<[number | null, NodeJS.Signals | null]>((resolve) => child.on("close", (c, s) => resolve([c, s])));
|
||||
log.end();
|
||||
clearInterval(copying);
|
||||
await new Promise<void>((resolve) => log.end(resolve));
|
||||
const r = await endJob(db, job, code, signal, spawnError);
|
||||
await logCopy.flush(true).catch((e: Error) => console.error(`job ${job}: log not stored: ${e.message}`));
|
||||
console.error(`job ${job}: ${r?.state ?? "ended"}${r?.error ? `: ${r.error}` : ""}`);
|
||||
return r?.state === "done" ? 0 : 1;
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// Job logs in the database. A job's process writes its log file on the runner's disk; the runner copies the new whole
|
||||
// lines into job_log_chunks every FLUSH_MS while the job runs and once more when it ends, so a dashboard without that
|
||||
// disk can show the log. Each copy is one INSERT (and, past the cap, one DELETE of the oldest chunks), never a
|
||||
// transaction held across file reads. Only the last JOB_LOG_KEEP_BYTES of a job are kept; the file keeps everything.
|
||||
import { closeSync, fstatSync, openSync, readSync } from "node:fs";
|
||||
import type { Db } from "../db/index.ts";
|
||||
|
||||
export const JOB_LOG_KEEP_BYTES = 256 * 1024;
|
||||
/** Chunks are dropped once the kept text passes the cap by this much, so the DELETE runs once per this many bytes, not per copy. */
|
||||
const DROP_SLACK_BYTES = 64 * 1024;
|
||||
export const JOB_LOG_FLUSH_MS = 5_000;
|
||||
|
||||
/** The bytes of `path` from `from` (an offset, or one computed from the size) to its end; null when the file cannot be read. */
|
||||
function readRange(path: string, from: number | ((size: number) => number)): { buf: Buffer; start: number; size: number } | null {
|
||||
let fd: number;
|
||||
try {
|
||||
fd = openSync(path, "r");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const size = fstatSync(fd).size;
|
||||
const start = typeof from === "function" ? from(size) : from;
|
||||
const buf = Buffer.alloc(Math.max(0, size - start));
|
||||
if (buf.length) readSync(fd, buf, 0, buf.length, start);
|
||||
return { buf, start, size };
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
/** Copies one job's log file into job_log_chunks. One per running job, in the process that started it. */
|
||||
export class JobLogCopy {
|
||||
#db: Db;
|
||||
#job: number;
|
||||
#path: string;
|
||||
#offset: number;
|
||||
#seq: number;
|
||||
#kept: { seq: number; bytes: number }[];
|
||||
#lastAt = 0;
|
||||
#busy: Promise<void> | null = null;
|
||||
|
||||
private constructor(db: Db, job: number, path: string, offset: number, kept: { seq: number; bytes: number }[]) {
|
||||
this.#db = db;
|
||||
this.#job = job;
|
||||
this.#path = path;
|
||||
this.#offset = offset;
|
||||
this.#kept = kept;
|
||||
this.#seq = kept.at(-1)?.seq ?? 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts after what an earlier run of the job (a resumed job) already copied, when the file still holds it; a file shorter
|
||||
* than that is another file (a new disk), copied from its start.
|
||||
*/
|
||||
static async open(db: Db, job: number, path: string): Promise<JobLogCopy> {
|
||||
const rows = await db.all(db.k.selectFrom("job_log_chunks").select(["seq", "start", "chunk"]).where("job_id", "=", job).orderBy("seq"));
|
||||
const kept = rows.map((r) => ({ seq: Number(r.seq), bytes: Buffer.byteLength(r.chunk) }));
|
||||
const last = rows.at(-1);
|
||||
const end = last ? Number(last.start) + kept.at(-1)!.bytes : 0;
|
||||
const size = readRange(path, (s) => s)?.size ?? 0;
|
||||
return new JobLogCopy(db, job, path, end <= size ? end : 0, kept);
|
||||
}
|
||||
|
||||
/** Copies the new whole lines, at most once per JOB_LOG_FLUSH_MS; `final` copies everything at once, a last partial line too. */
|
||||
async flush(final = false): Promise<void> {
|
||||
if (this.#busy) await this.#busy;
|
||||
if (!final && Date.now() - this.#lastAt < JOB_LOG_FLUSH_MS) return;
|
||||
this.#lastAt = Date.now();
|
||||
this.#busy = this.#copy(final).finally(() => { this.#busy = null; });
|
||||
await this.#busy;
|
||||
}
|
||||
|
||||
async #copy(final: boolean): Promise<void> {
|
||||
// More new text than the cap keeps: only its end is read.
|
||||
const r = readRange(this.#path, (size) => Math.max(this.#offset, size - JOB_LOG_KEEP_BYTES));
|
||||
if (!r || !r.buf.length) return;
|
||||
let buf = r.buf;
|
||||
if (r.start > this.#offset) buf = buf.subarray(buf.indexOf(10) + 1);
|
||||
const skipped = r.buf.length - buf.length;
|
||||
if (!final) {
|
||||
const nl = buf.lastIndexOf(10);
|
||||
if (nl < 0) return;
|
||||
buf = buf.subarray(0, nl + 1);
|
||||
}
|
||||
if (!buf.length) return;
|
||||
const start = r.start + skipped;
|
||||
const seq = this.#seq + 1;
|
||||
await this.#db.run(this.#db.k.insertInto("job_log_chunks").values({ job_id: this.#job, seq, start, chunk: buf.toString("utf8") }));
|
||||
this.#seq = seq;
|
||||
this.#offset = start + buf.length;
|
||||
this.#kept.push({ seq, bytes: buf.length });
|
||||
let total = this.#kept.reduce((a, c) => a + c.bytes, 0);
|
||||
if (total <= JOB_LOG_KEEP_BYTES + DROP_SLACK_BYTES) return;
|
||||
let upTo = 0;
|
||||
while (this.#kept.length > 1 && total > JOB_LOG_KEEP_BYTES) {
|
||||
const c = this.#kept.shift()!;
|
||||
total -= c.bytes;
|
||||
upTo = c.seq;
|
||||
}
|
||||
if (upTo) await this.#db.run(this.#db.k.deleteFrom("job_log_chunks").where("job_id", "=", this.#job).where("seq", "<=", upTo));
|
||||
}
|
||||
}
|
||||
|
||||
/** The last `bytes` of a job's stored log, from whole lines; truncated when earlier text is not shown. */
|
||||
export async function storedLogTail(db: Db, job: number, bytes: number): Promise<{ log: string; logTruncated: boolean } | null> {
|
||||
const parts: string[] = [];
|
||||
let size = 0;
|
||||
let first: number | null = null;
|
||||
for (const c of await db.all(db.k.selectFrom("job_log_chunks").select(["chunk", "start"]).where("job_id", "=", job).orderBy("seq", "desc"))) {
|
||||
parts.push(c.chunk);
|
||||
size += Buffer.byteLength(c.chunk);
|
||||
first = Number(c.start);
|
||||
if (size >= bytes) break;
|
||||
}
|
||||
if (first === null) return null;
|
||||
const joined = parts.reverse().join("");
|
||||
if (size <= bytes) return { log: joined, logTruncated: first > 0 };
|
||||
const cut = Buffer.from(joined).subarray(-bytes).toString("utf8");
|
||||
return { log: cut.slice(cut.indexOf("\n") + 1), logTruncated: true };
|
||||
}
|
||||
+15
-4
@@ -168,6 +168,7 @@ export async function pruneJobs(db: Db, nowMs: number = Date.now()): Promise<num
|
||||
}
|
||||
}
|
||||
await db.run(db.k.deleteFrom("job_items").where("job_id", "=", r.id));
|
||||
await db.run(db.k.deleteFrom("job_log_chunks").where("job_id", "=", r.id));
|
||||
await db.run(db.k.deleteFrom("jobs").where("id", "=", r.id));
|
||||
n++;
|
||||
}
|
||||
@@ -183,16 +184,26 @@ import type { Db } from "../db/index.ts";
|
||||
import type { DB } from "../db/types.ts";
|
||||
import type { SelectQueryBuilder } from "kysely";
|
||||
import { cols, like } from "../db/kx.ts";
|
||||
import { storedLogTail } from "./job-log.ts";
|
||||
|
||||
export const LOG_TAIL_BYTES = 48 * 1024;
|
||||
|
||||
export function logTail(path: string | null, bytes = LOG_TAIL_BYTES): { log: string; logTruncated: boolean } {
|
||||
if (!path) return { log: "", logTruncated: false };
|
||||
/** The end of a job's log: from its log file when this process can read it (it shares the runner's disk), else as the runner stored it. */
|
||||
export async function jobLogTail(db: Db, id: number, path: string | null, bytes = LOG_TAIL_BYTES): Promise<{ log: string; logTruncated: boolean }> {
|
||||
const local = logTail(path, bytes);
|
||||
if (local) return local;
|
||||
const stored = await storedLogTail(db, id, bytes);
|
||||
return stored ? { log: scrub(stored.log), logTruncated: stored.logTruncated } : { log: "", logTruncated: false };
|
||||
}
|
||||
|
||||
/** The end of a log file; null when there is none to read here. */
|
||||
export function logTail(path: string | null, bytes = LOG_TAIL_BYTES): { log: string; logTruncated: boolean } | null {
|
||||
if (!path) return null;
|
||||
let fd: number;
|
||||
try {
|
||||
fd = openSync(path, "r");
|
||||
} catch {
|
||||
return { log: "", logTruncated: false };
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const size = fstatSync(fd).size;
|
||||
@@ -220,7 +231,7 @@ export async function jobDetail(db: Db, id: number, view: { hidden?: HiddenRepos
|
||||
const items = await mapSeq((await db.all(db.k.selectFrom("job_items").select(["repo", "number", "outcome", "ref"]).where("job_id", "=", id).orderBy("id")))
|
||||
.filter((i) => !isHiddenRepo(hidden, i.repo)), async (i) => ({ repo: i.repo, number: i.number, ...await shown(i.repo, i.number), outcome: i.outcome, decision: i.ref }));
|
||||
if (view.logs === false) return { ...(await toJobs(db, [r]))[0]!, items, log: null, logTruncated: false };
|
||||
const tail = logTail(r.log_path);
|
||||
const tail = await jobLogTail(db, id, r.log_path);
|
||||
return { ...(await toJobs(db, [r]))[0]!, items, ...tail, log: tail.log && hidden.length ? tail.log.split("\n").filter((l) => !l || blankIfHidden(l, hidden)).join("\n") : tail.log };
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// stops jobs whose cancel was requested, runs the autopilot (queues jobs while the
|
||||
// pipeline switch is on) and puts jobs that a stop or an earlier runner left
|
||||
// unfinished back in the queue to resume (src/runner/resuming.ts).
|
||||
import { JobLogCopy } from "./job-log.ts";
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { appendFileSync, statSync, closeSync, mkdirSync, openSync, readFileSync, utimesSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
@@ -79,7 +80,7 @@ export type RunnerOptions = {
|
||||
graceMs?: number;
|
||||
};
|
||||
|
||||
type Running = { child: ChildProcess; termAt: number | null; exited: Promise<void>; startedAt: number; deadlineMin: number; logPath: string; /** When the job was told to finish its current item and stop. */ flaggedAt: number | null; noProgressMin: number; /** Why it was told to stop. */ stopMsg: string | null; /** Time in which a user-local call of the job waited for a helper, summed over the checks that saw one waiting. */ remoteWaitMs: number; remoteSeen: { at: number; queued: boolean } | null };
|
||||
type Running = { child: ChildProcess; termAt: number | null; exited: Promise<void>; startedAt: number; deadlineMin: number; logPath: string; logCopy: JobLogCopy; /** When the job was told to finish its current item and stop. */ flaggedAt: number | null; noProgressMin: number; /** Why it was told to stop. */ stopMsg: string | null; /** Time in which a user-local call of the job waited for a helper, summed over the checks that saw one waiting. */ remoteWaitMs: number; remoteSeen: { at: number; queued: boolean } | null };
|
||||
|
||||
/** The error of a job the runner stopped for running past its step's limit. */
|
||||
export const deadlineError = (min: number): string => `stopped: ran past ${min} min`;
|
||||
@@ -425,6 +426,7 @@ export class Runner {
|
||||
// Progress is a new line in the job's log (the job's own output: progress lines, check-tool notes, results); reading its mtime costs one stat.
|
||||
let lastLine = Math.max(r.startedAt, waiting ? nowMs : remote.lastLeaseAt ?? 0);
|
||||
try { lastLine = Math.max(lastLine, statSync(r.logPath).mtimeMs); } catch { /* no log yet */ }
|
||||
await r.logCopy.flush().catch((e: Error) => this.o.log(`job ${id}: log not stored: ${e.message}`));
|
||||
const idle = r.flaggedAt === null && Date.now() - lastLine >= r.noProgressMin * 60_000;
|
||||
// Past its deadline a job is first asked to stop: the failure is recorded, which the job reads at its item boundaries (ctx.cancelled)
|
||||
// and finishes the writes of its current item. Only after the grace does the process get the signals a cancel gets.
|
||||
@@ -525,6 +527,7 @@ export class Runner {
|
||||
: (await this.db.run(this.db.k.updateTable("jobs").set({ state: "running", started_at: now(), log_path: logPath }).where("id", "=", id).where("state", "=", "queued"))).changes);
|
||||
if (!claimed) return false;
|
||||
const fd = openSync(logPath, "a");
|
||||
const logCopy = await JobLogCopy.open(this.db, id, logPath);
|
||||
let child: ChildProcess;
|
||||
try {
|
||||
child = spawn(process.execPath, [CLI, "runner", "exec", String(id)], {
|
||||
@@ -542,6 +545,7 @@ export class Runner {
|
||||
const exited = new Promise<void>((resolve) => {
|
||||
child.on("close", (code, signal) => {
|
||||
void this.finish(id, code, signal, spawnError)
|
||||
.then(() => logCopy.flush(true).catch((e: Error) => this.o.log(`job ${id}: log not stored: ${e.message}`)))
|
||||
.catch((e) => {
|
||||
this.unrecorded.set(id, { code, signal, spawnError });
|
||||
this.o.log(`job ${id}: end not recorded: ${(e as Error).message}`);
|
||||
@@ -552,7 +556,7 @@ export class Runner {
|
||||
});
|
||||
});
|
||||
});
|
||||
this.running.set(id, { child, termAt: null, exited, startedAt: Date.now(), deadlineMin: this.maxMin(stepName, await this.limitOf(id)), logPath, flaggedAt: null, noProgressMin: this.noProgressMin(stepName), stopMsg: null, remoteWaitMs: 0, remoteSeen: null });
|
||||
this.running.set(id, { child, termAt: null, exited, startedAt: Date.now(), deadlineMin: this.maxMin(stepName, await this.limitOf(id)), logPath, logCopy, flaggedAt: null, noProgressMin: this.noProgressMin(stepName), stopMsg: null, remoteWaitMs: 0, remoteSeen: null });
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
+8
-1
@@ -1,5 +1,5 @@
|
||||
-- Generated by scripts/gen-pg-schema.ts from src/schema.sql and the added columns and indexes in src/db.ts. Do not edit.
|
||||
-- dialect: postgres; stamp: 538a82de573691a0
|
||||
-- dialect: postgres; stamp: 0b64a1c4bda5c1bf
|
||||
-- Identity columns start at 1: after a data copy, each identity sequence is set past the copied keys (setval).
|
||||
-- Compat functions: SQLite built-ins the queries use, with SQLite's results.
|
||||
-- char() has no equivalent: CHAR is a Postgres keyword, so no function can be called char(...); queries use a dialect helper.
|
||||
@@ -522,6 +522,13 @@ CREATE TABLE IF NOT EXISTS jobs (
|
||||
resumes bigint NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS jobs_state ON jobs (state, id);
|
||||
CREATE TABLE IF NOT EXISTS job_log_chunks (
|
||||
job_id bigint NOT NULL,
|
||||
seq bigint NOT NULL,
|
||||
start bigint NOT NULL,
|
||||
chunk text COLLATE "C" NOT NULL,
|
||||
PRIMARY KEY (job_id, seq)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS jobs_step ON jobs (step, id);
|
||||
CREATE INDEX IF NOT EXISTS jobs_step_started ON jobs (step, started_at);
|
||||
CREATE INDEX IF NOT EXISTS jobs_user_ended ON jobs (requested_by, ended_at);
|
||||
|
||||
@@ -534,6 +534,15 @@ CREATE TABLE IF NOT EXISTS jobs (
|
||||
resumes INTEGER NOT NULL DEFAULT 0 -- times a runner stop or restart put the running job back in the queue (src/runner/resuming.ts)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS jobs_state ON jobs(state, id);
|
||||
-- The end of each job's log, copied by the runner from the job's log file in chunks of whole lines (src/runner/job-log.ts),
|
||||
-- for a dashboard that does not share the runner's disk. Only the last 256 KiB of a job are kept; pruneJobs deletes them with the job.
|
||||
CREATE TABLE IF NOT EXISTS job_log_chunks (
|
||||
job_id INTEGER NOT NULL,
|
||||
seq INTEGER NOT NULL,
|
||||
start INTEGER NOT NULL, -- byte offset of the chunk in the log file; the first kept chunk's > 0: earlier text was dropped
|
||||
chunk TEXT NOT NULL,
|
||||
PRIMARY KEY (job_id, seq)
|
||||
) WITHOUT ROWID;
|
||||
CREATE INDEX IF NOT EXISTS jobs_step ON jobs(step, id);
|
||||
CREATE INDEX IF NOT EXISTS jobs_step_started ON jobs(step, started_at);
|
||||
CREATE INDEX IF NOT EXISTS jobs_user_ended ON jobs(requested_by, ended_at);
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
// Job logs stored in the database: the copy keeps the end of a long log within the cap, and the job page reads it when
|
||||
// the log file is not on this disk (a dashboard that does not share the runner's).
|
||||
import assert from "node:assert/strict";
|
||||
import { appendFileSync, mkdtempSync, rmSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { test } from "node:test";
|
||||
import { SCRATCH } from "./scratch.ts";
|
||||
import { connectDb } from "../src/db/open.ts";
|
||||
import { JOB_LOG_KEEP_BYTES, JobLogCopy } from "../src/runner/job-log.ts";
|
||||
import { jobDetail } from "../src/runner/jobs.ts";
|
||||
|
||||
test("a long job log keeps its end within the cap, and the job page reads it without the file", async () => {
|
||||
const dir = mkdtempSync(join(SCRATCH, "job-log-"));
|
||||
const db = await connectDb(join(dir, "jobs.db"));
|
||||
try {
|
||||
const path = join(dir, "job.log");
|
||||
const t = new Date().toISOString();
|
||||
const id = Number((await db.get(db.k.insertInto("jobs").values({ step: "test-echo", params: "{}", requested_by: "boss", requested_at: t, state: "running", started_at: t, log_path: path })
|
||||
.returning("id")))!.id);
|
||||
const copy = await JobLogCopy.open(db, id, path);
|
||||
const line = (i: number) => `line ${i} ${"x".repeat(1000)}\n`;
|
||||
let n = 0;
|
||||
for (let batch = 0; batch < 20; batch++) {
|
||||
for (let i = 0; i < 30; i++) appendFileSync(path, line(n++));
|
||||
await copy.flush(true);
|
||||
}
|
||||
appendFileSync(path, "the last line, unfinished");
|
||||
await copy.flush(true);
|
||||
|
||||
const chunks = await db.all(db.k.selectFrom("job_log_chunks").select("chunk").where("job_id", "=", id));
|
||||
const stored = chunks.reduce((a, c) => a + Buffer.byteLength(c.chunk), 0);
|
||||
assert.ok(n * 1000 > 2 * JOB_LOG_KEEP_BYTES, "the log is longer than the cap");
|
||||
assert.ok(stored < 2 * JOB_LOG_KEEP_BYTES, `kept ${stored} bytes`);
|
||||
|
||||
rmSync(path);
|
||||
const j = await jobDetail(db, id);
|
||||
assert.ok(j.log!.endsWith("the last line, unfinished"), j.log!.slice(-80));
|
||||
assert.ok(j.log!.includes(`line ${n - 1} `));
|
||||
assert.match(j.log!, /^line \d+ /, "the shown text starts at a whole line");
|
||||
assert.equal(j.logTruncated, true);
|
||||
} finally {
|
||||
await db.close();
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -65,6 +65,11 @@ describe("runner", () => {
|
||||
assert.ok(j.log!.includes("token in the log: [hidden]"), j.log!);
|
||||
assert.ok(!j.log!.includes(FAKE_TOKEN));
|
||||
assert.equal((await getJob(db, bad.id)).error, "echo failed on purpose");
|
||||
// The runner stored the log too: without the file (another disk) the job page shows the same scrubbed text.
|
||||
await until(async () => !!await db.get(db.k.selectFrom("job_log_chunks").select("seq").where("job_id", "=", ok.id)));
|
||||
rmSync((await db.get(db.k.selectFrom("jobs").select("log_path").where("id", "=", ok.id)))!.log_path!);
|
||||
const stored = (await jobDetail(db, ok.id)).log!;
|
||||
assert.ok(stored.includes("token in the log: [hidden]") && !stored.includes(FAKE_TOKEN), stored);
|
||||
});
|
||||
|
||||
test("with AUTOCRAFT_DB_URL set, a job process opens that Postgres database, not a SQLite file", async () => {
|
||||
|
||||
Reference in new issue
Block a user