In Watch a Trace Unfold, one question left six spans in today’s file. That’s fine for one hiker. Over a summer, every question the assistant answers leaves a trace with the hiker’s words in it, and nobody will read most of those traces.
In this lesson, you’ll decide which traces to keep and for how long, given this assistant’s traffic and its risks. Then you’ll measure what share of a day’s traces your rule keeps. Start with the traces you can’t afford to lose.
Keep the Traces You’ll Need
You’ll always want the traces of requests that failed and of answers your checks flagged. An answer is flagged when its checks span lists a broken rule in failed. You sample the remaining traces at random, at a sample rate you choose. That rule fits in one function in trace.js:
trace.js
export const SAMPLE_RATE = 0.1;
export const RETENTION_DAYS = 30;
function shouldKeep(spans) {
if (spans.some((s) => s.error)) return true;
const checks = spans.find((s) => s.name === "checks");
const flagged = checks?.failed?.length > 0;
return flagged || Math.random() < SAMPLE_RATE;
}
The checks span ends last, so the decision waits until the request ends. Deciding with the whole trace in hand is called tail sampling. The rest is plumbing that you can copy from the block below. Here’s what each function does:
endSpan()holds each span in aMapunder its trace ID instead of writing it.finishTrace(traceId, failure)runs in the/askhandler’sfinallyblock. It records any failure passed to it as arequestspan, then writes the trace ifshouldKeep()returnstrue.sweepTraces()deletes the daily files older thanRETENTION_DAYSat startup and once a day.
Deciding at the end has a price, though. If the server crashes mid-request, it loses the spans held in memory.
In trace.js, add readdir and unlink to the node:fs/promises import, then replace endSpan() and add the new functions below shouldKeep():
trace.js
const pending = new Map();
async function endSpan(s, err) {
s.durationMs = Date.now() - Date.parse(s.start);
if (err) s.error = errorFields(err);
if (!s.traceId) return;
if (!pending.has(s.traceId)) pending.set(s.traceId, []);
pending.get(s.traceId).push(s);
}
export async function finishTrace(traceId, failure) {
const spans = pending.get(traceId) ?? [];
pending.delete(traceId);
if (failure) {
const start = new Date().toISOString();
const error = errorFields(failure);
spans.push({ traceId, name: "request", start, error });
}
if (spans.length === 0 || !shouldKeep(spans)) return;
const day = spans[0].start.slice(0, 10);
const lines = spans.map((s) => JSON.stringify(s) + "\n");
try {
await mkdir("traces", { recursive: true });
await appendFile(`traces/${day}.jsonl`, lines.join(""));
} catch (writeErr) {
const failed = writeErr.code ?? writeErr.name;
console.error(JSON.stringify({ traceId, failed }));
}
}
const DAY_FILE = /^\d{4}-\d{2}-\d{2}\.jsonl$/;
const DAY_MS = 86_400_000;
export async function sweepTraces(now = Date.now()) {
const cutoff = now - RETENTION_DAYS * DAY_MS;
let entries;
try {
entries = await readdir("traces", { withFileTypes: true });
} catch (err) {
if (err.code === "ENOENT") return;
throw err;
}
for (const entry of entries) {
if (!entry.isFile() || !DAY_FILE.test(entry.name)) continue;
const dayEnds = Date.parse(entry.name.slice(0, 10)) + DAY_MS;
if (dayEnds <= cutoff) await unlink(`traces/${entry.name}`);
}
}
The sweep deletes only files named like 2026-11-02.jsonl, and only after at least RETENTION_DAYS have passed since the end of that day. So a trace lives 30 to 31 days, plus up to a day until the next sweep runs. In server.js, import the new functions and wrap the /ask handler’s body so a failure reaches finishTrace(). A failing sweep is logged instead of stopping the server:
server.js
import { span, finishTrace, sweepTraces } from "./trace.js";
app.post("/ask", promptVersion("v2"), async (req, res) => {
const id = res.locals.requestId;
let failure;
try {
// Retrieval, the answer and the checks, as before
} catch (err) {
failure = err;
throw err;
} finally {
await finishTrace(id, failure);
}
});
function sweep() {
return sweepTraces().catch((err) => {
const failed = err.code ?? err.name;
console.error(JSON.stringify({ sweep: "traces", failed }));
});
}
await sweep();
setInterval(sweep, 86_400_000);