Durable runs
One trajectory for a run that a durable runtime executes many times, across threads, processes and episodes over days.
On a durable runtime (DBOS, Temporal, LangGraph checkpoints) one logical run is many executions: a worker thread, a
replay that skips completed steps, a recovery in another process after a crash, and episodes days apart. A plain
trace() sees one of them. @viewportai/core/store / viewportai.core.store records every execution as a
segment of one trajectory in a store, and stitches them back into one trajectory with no duplicates.
// Episode 1: quote, then wait for the owner's approval (a suspend the stitched view shows as a gap).
await durableTrace(
async () => {
say("A cut is $40. Shall I book it?");
emit({ type: "suspend", wait_id: "apr_7", wait_for: "approval" });
},
{ ...run, episodeId: "ep_1", input: "book a haircut" },
);
clock.advance(6 * 3_600_000); // the owner approves six hours later
// Episode 2, first execution: killed while charging (its span opened, nothing closed).
const killed = storeSink(store, { trajectoryId: "trj_booking_42", episodeId: "ep_2", tenant: "acme", clock });
killed.start?.({ type: "tool_call", id: "evt_charge_try", tool_name: "charge_card", started_at: new Date(clock.now()).toISOString() });
clock.advance(30_000);
// Episode 2, recovery in a fresh process: the same code runs again; each step is seeded by its execution identity.
await durableTrace(
async () => {
emit({ type: "resume", wait_id: "apr_7" });
await durableStep("wf_42:charge", () => span({ type: "tool_call", tool_name: "charge_card" }, async () => "ch_1"));
say("Booked for Friday at 3pm.");
return "booked";
},
{ ...run, episodeId: "ep_2" },
);# Episode 1: quote, then wait for the owner's approval (a suspend the stitched view shows as a gap).
async with durable_trace(**run, episode_id="ep_1", input="book a haircut"):
say("A cut is $40. Shall I book it?")
emit(SuspendEvent(wait_id="apr_7", wait_for="approval"))
clock.advance(6 * 3_600_000) # the owner approves six hours later
# Episode 2, first execution: killed while charging (its span opened, nothing closed).
killed = store_sink(store, trajectory_id="trj_booking_42", episode_id="ep_2", tenant="acme", clock=clock)
killed.start(ToolCallEvent(id="evt_charge_try", tool_name="charge_card"))
clock.advance(30_000)
# Episode 2, recovery in a fresh process: the same code runs again; each step is seeded by its execution identity.
async with durable_trace(**run, episode_id="ep_2") as t:
emit(ResumeEvent(wait_id="apr_7"))
async with durable_step("wf_42:charge"), span(ToolCallEvent(tool_name="charge_card")):
pass
say("Booked for Friday at 3pm.")
t.output = "booked"The three rules
- Open
durableTrace/durable_traceinside the workflow body. The same code runs on first execution and on recovery; each execution appends a segment. The body is seeded from tenant, trajectory and episode, so a deterministic body (which durable runtimes already require) emits the same ids every time. - Wrap each durable step in
durableStep(key)/durable_step(key), with the runtime's execution identity as the key (workflow_id:step_id). A step that re-executes emits the same ids, and its records are flushed to the store before the step returns, so they are durable before the runtime checkpoints it. - Read with
readTrajectory/read_trajectory. It dedupes by id: an identical re-run keeps its first place, a retry with a different outcome wins at its own place (attributes.attempts), and the same id for a different event is kept twice and reported ascore.id_conflict.
const t = await readTrajectory(store, "trj_booking_42", { tenant: "acme" });
const attrs = t.attributes as { status: string; episodes: Array<{ id: string; status: string; segments: Array<{ status: string }> }> };
console.log(`status: ${attrs.status}, output: ${stableJson(t.output)}`);
for (const ep of attrs.episodes) console.log(`${ep.id}: ${ep.status} (${ep.segments.map((s) => s.status).join(", ")})`);
for (const e of t.events) {
const label = (e as { tool_name?: string }).tool_name ?? (e as { content?: string }).content ?? (e as { wait_id?: string }).wait_id;
const extra =
e.type === "resume"
? ` waited ${(e as { waited_ms?: number }).waited_ms} ms`
: (e as { error?: { type: string } }).error
? ` ${(e as { error: { type: string } }).error.type}`
: "";
console.log(`${e.episode_id} ${e.type} ${label}${extra}`);
}trajectory = read_trajectory(store, "trj_booking_42", tenant="acme")
attrs = trajectory.to_dict()["attributes"]
print(f"status: {attrs['status']}, output: {stable_json(trajectory.output)}")
for ep in attrs["episodes"]:
print(f"{ep['id']}: {ep['status']} ({', '.join(s['status'] for s in ep['segments'])})")
for e in trajectory.to_dict()["events"]:
label = e.get("tool_name") or e.get("content") or e.get("wait_id")
if e["type"] == "resume":
extra = f" waited {stable_json(e.get('waited_ms'))} ms"
elif e.get("error"):
extra = f" {e['error']['type']}"
else:
extra = ""
print(f"{e['episode_id']} {e['type']} {label}{extra}")The stitched trajectory
attributes.status is running, suspended (a suspend without its resume), completed, failed or
interrupted. attributes.episodes lists each episode with its segments (ended, interrupted or open, with
recovery_of for a recovery), and every event carries episode_id, so a viewer can draw episodes as bands and the
waits between them as gaps. latency_ms is wall time from the first record to the last; attributes.active_ms
sums the time segments actually ran. A span that started and never finished is open while its segment is the
newest of its episode, else it gets error.type: core.interrupted.
Stores
memory() for tests and jsonl(dir) for one machine: one append-only file per segment
(<dir>/<tenant>/<trajectory_id>/<segment_id>.records.jsonl), so every file has one writer, even when a recovery
overlaps a slow old process. A crash mid-write leaves a torn last line, which readers ignore. Any database can
implement TrajectoryStore (append, read with a cursor, list, delete); append must be idempotent per
(segment_id, seq), which makes at-least-once writes harmless. redact on the sink runs before every write.
Segment attributes use pinned keys for where an episode ran, so stored runs, daemon sessions and eval runs read the
same in every viewer: host.name, process.pid, viewport.durable.workflow_id, viewport.durable.step_id and
viewport.durable.recovery (SEGMENT_ATTRIBUTES in @viewportai/core/store and viewportai.core.store).
durableTrace sets viewport.durable.recovery: true on a segment that re-executes an episode already recorded; the
host or runtime adapter sets the others, since only it knows them.
Threads and tenants
The ambient scope is a ContextVar / AsyncLocalStorage: a worker thread (a DBOS queue) does not see a caller's
trace(). Open the durable trace inside the workflow, or carry the scope into a thread you start with
contextvars.copy_context().run. Every trajectory and event can carry a tenant; a trace for another tenant inside
a tenant raises core.tenant_mismatch, a store sink never writes another tenant's event, and store keys are
tenant-qualified so two tenants' trajectories never stitch together.