# Session DAG design

1. **ROOT**
2. `predecessor`
3. **user 1 → reply 1 → user 2 → reply 2** A retry of user 2 shares predecessor reply 1: a fork.
4. `caller`
5. **tool → model call** Nesting under reply 2

Arrows point at the edge's target. One node per user message, model call, function or tool call. Transcript and call tree are two views of this per-session, append-only record; any past call re-renders as the model saw it.

| Item | Detail |
| --- | --- |
| Graph owner | Each Agent execution ([ownership](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/dag/persistence-observability.html)) |
| Ordinary helpers | No durable nodes; semantic operations are still recorded completely |
| Permission, cancellation, file checkpoints | Originating execution, whoever owns the graph |
| Inherited Context | Does not turn computation into history |

## Model selection

| Model | Useful for | Boundary |
| --- | --- | --- |
| Flat logs | Append-only, simple collection | Nesting, ancestry and reads need extra relationships |
| Span tree | Identity, parent-child calls, timing, status, attributes | Parentage describes calls, not the conversation predecessor; cannot name alternative continuations |
| Timed nested intervals | Performance views (Chrome Trace, Perfetto) | Timing cannot say which branch a reply follows |
| **Session DAG (selected)** | Calls, branches and reads in one record | Needs edge validation, indexes, explicit rendering rules |

One record must hold nested calls, branches and the exact nodes each LLM call read.

**Adopted and rejected choices**

| Item | Detail |
| --- | --- |
| Uniform operation record | Adopted: all nodes share `Call`; role and metadata differ |
| Parent-child call relationship | Adopted as `caller` |
| Time order instead of the conversation edge | Rejected: `seq` cannot identify branch ancestry |
| Context reads only as tracing events | Rejected: `reads` lists node IDs; telemetry export is a separate mapping |
| `caused_by` | Not part of the schema |
| OTel SDK for persistence | Rejected: storage and context reconstruction stay in OpenProgram |
| GenAI attribute conventions | Reference for model and usage metadata ([conventions](https://github.com/open-telemetry/semantic-conventions-genai)); no exporter is implied |
| Span structure | [OpenTelemetry trace model](https://opentelemetry.io/docs/concepts/signals/traces/) |
| Studied, storage not copied | Datadog, New Relic, Honeycomb, Lightstep, Pixie, Cilium, Langfuse, Arize Phoenix/OpenInference, LangSmith, OpenLLMetry, W&B Weave, Braintrust |
| Optional diagnostics | Kept separate |
| Validation | Call tree and conversation chain independently |
| Token, cost, evaluation metadata | Need explicit definitions; never inferred from timing |

## Data model

| Item | Detail |
| --- | --- |
| `id` | Unique identifier |
| `seq` | Monotonic; the only sort key |
| `created_at` | Wall clock, for humans |
| `role` | `user`, `llm` or `code`; decides rendering, not essence |
| `name` | Model id, function name or user name |
| `input` | Prompt, function args or `None` |
| `output` | Reply, return value or user text |
| `caller` | Sub-call parent |
| `predecessor` | Conversation parent |
| `reads` | Nodes this LLM call read; not structure |
| `metadata` | Token usage, model, source, expose, `tool_call_id`…; LLM leaf fields align with `gen_ai.*` |
| `metadata.status` | `running`, `completed`, `error`, `cancelled` on every path. Error nodes carry structured type and trace; a user cancel writes `cancelled` |

| Scenario | role | caller | predecessor |
| --- | --- | --- | --- |
| ROOT (`display=root`) | user | empty | empty |
| User message | user | ROOT | previous reply; `"ROOT"` on the session's first node |
| LLM reply | llm | this turn's user, or the enclosing code node | this turn's user |
| LLM calls a tool | code | that llm node | — |
| User calls a function | code | empty | branch head, or `"ROOT"` |
| Agent requests a model or direct tool | llm / code | owning operation in this graph | — |

Loops are not nodes: their model and tool operations are.

## Edges and invariants

| Item | Detail |
| --- | --- |
| Both edges | Directed, acyclic, orthogonal |
| `caller` | Connects top-level nodes to ROOT |
| `predecessor` | Chat order and forks, which `caller` plus `seq` cannot give. Only this top-level field; no metadata mirror or legacy read |
| Write (`session_store/shared.py`) | A mislinked branch is unrepairable, so a ROOT-level user or llm node with no real caller needs a `predecessor`, else `PredecessorMissingError` |
| Legal exceptions | First node and explicit root forks (sentinel `"ROOT"`) · ROOT itself · spawn roots (`predecessor=None`, `caller` = spawner) · `ask_user` answers (user node with non-None `input`) · summary nodes covering from the session start ([§8](#s8)) |
| Read | `get_branch` and `list_branches` walk edges only. A missing `predecessor` must be a spawn root, ROOT, the first node, a code node opening a run branch or such a summary, else `BrokenPredecessorChainError` with the node id |

## Branches and spawn

| Fork | Replaced | New | Shared edge |
| --- | --- | --- | --- |
| Resend a message | user2 (P=llm1) | user2′ (P=llm1) | predecessor |
| LLM retry | llm1 (P=user1) | llm1′ (P=user1) | predecessor |
| Tool retry | code (C=llm1) | code′ (C=llm1) | caller |

### Failure

| Item | Detail |
| --- | --- |
| Error | Terminal: `status=error`, turn committed, head stops |
| Cancel | Likewise, `cancelled` |
| Retry | An ordinary fork. The failed line stays reachable, off the active branch, so out of the retry's context; nothing filters by status |

| Finalization on error | Runs |
| --- | --- |
| Git, project and shadow-git commits, snapshot eviction | Yes: no timeline hole, a retry has a committed predecessor |
| Context-commit backfill, usage feedback, auto-titling | No: they presuppose a reply |

### Spawn

1. **spawn turn → notice₁ → answer₁ → notice₂ → answer₂** Completions chain on HEAD.
2. `caller`
3. **spawn root** Clean: predecessor=None. Context stops here both ways.
4. **Inherited** First user node's predecessor is the requested node: an exact fork.

| Item | Detail |
| --- | --- |
| `SessionStore.spawn_branch(session_id, caller_node_id, *, source, name=…, register_head=True)` | The only way to open a clean spawn root. Called by `TurnWriter` for `branch_from=None` with `spawn_caller`, which Job runner, collaboration messages and background agents set |
| Root node | User node with `caller`, `metadata.source`, `metadata.spawn_branch_root=True` |
| Head | Registered, unless `register_head=False` (same-session sub-agents) |
| Context | `get_branch` stops at the root; rendering from the parent does not descend through `caller` ([Context rendering](#s6)) |

**Cross-session exact fork**

| Item | Detail |
| --- | --- |
| Source session S | Keeps the attach card beside initiating node A. A is `spawn_out`; the card points at `attach.session_id=T` and the target head |
| Target T | New user node: `predecessor=M`, `caller=A`, `metadata.spawned_from_session=S`. The graph cannot draw into another session, so T's projection places the caller at ROOT and marks the node `spawn_remote` |
| HEADs | Neither moves. The result is registered as a branch tip; a later reply-back advances the source HEAD as an ordinary turn |

### Completion notification

| Written back | Anchored at | Because |
| --- | --- | --- |
| Attach pointer | The caller turn | A record of a call |
| Notification turn (`source="job_followup"`) | Current HEAD, advancing it | A new turn: N sub-agents form one chain, not N answers to one message |

The runner leaves `TurnRequest.branch_from` at `INHERIT_PARENT` and never rewinds head. `JobRunner._followup_lock`, one per delivery session, serialises simultaneous finishes.

## Head and branches

| Item | Detail |
| --- | --- |
| `head_id` | Active branch tip. Conversation writes advance it to a real node, never a placeholder or summary; a dangling head renders empty. Caller-tagged nodes leave it |
| `get_branch(session_id, head_id)` | Predecessor chain from head to terminus |
| `list_branches(session_id)` | Visible conversation tips plus retained branch references. Rewind hides withdrawn suffixes while preserving sibling references, including references at a shared ancestor or ROOT. Branch identity distinguishes references at the same head. Internal execution rows do not create conversation tips, and neither does a turn's message written under a recorded branch's head in the moment before the head and the record move onto it |
| Branch names | Session metadata: branch-reference labels own each branch name; `branches` keeps the selected-head compatibility projection |

## Context rendering

**A node renders if and only if its nearest ROOT-level ancestor (up `caller`) lies on the predecessor chain of `head_id`, and the frame and expose rules admit it.**

| Item | Detail |
| --- | --- |
| `seq` | Only orders |
| Engine | Resolves head, calls `render_context`, hands the result to `render_dag_messages`; filters nothing itself |
| Read path | Writes nothing |
| ROOT | Never expanded: its caller-subtree would re-admit every sibling branch |
| Spawn root (`metadata.spawn_branch_root`) | Not entered via `caller`: a Goal working agent cannot read its judge. Seen through the spine from inside the branch |
| Top-level chat (frame −1) | Every spine turn is fully visible |
| Inside a function (frame = its seq) | Pre-frame history, own progress; others' internals per `expose` (default `io`) |
| Code node with `metadata.tool_call_id` | A real ToolCall/ToolResult pair inside its llm node's assistant message |
| Code node without one | Text pair |
| Chat stream | Top-level user and llm by seq, nesting folded |
| Call tree | Expanded along `caller`, loop siblings folded ×N |

## Context assembly

| Item | Detail |
| --- | --- |
| One assembler | `build_system_prompt(agent, *, channel, tools, additional_working_dirs, plan_mode)`, for every model call: identity, project memory, unified tool list, skills |
| Budget | Counts the string that ships |
| Variation | Constant by default, for KV-cache hits and one background across chat and functions. A slim prompt is an explicit call-site choice that accepts the miss |
| Wrong tool use in a function | User-turn guidance plus a depth cap, never another tool list ([self-recursion](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/agent/agentic-self-recursion.html)) |
| Recording | On a hash change (start, toolset change, plan-mode toggle): a `role=code` node `name="context/system_prompt"`, `caller=ROOT`, output = full text. Rendering pins the latest on the spine |
| `context/*` names | Reserved and hidden from chat, except `context/summary`, which is real conversation content |
| Memory prefetch | Prefix block in the user node's wire message, stored as the `memory_prefetch` entry of its `turn_context` metadata ([Composition](https://fzkuji.github.io/OpenProgram/docs/reference/design/context/composition.html#l2)). System and tools stay byte-stable |
| Images and files | By reference; bodies in the attachments directory, loaded by render |

## Compaction

1. **P → a → b → c → d → e** e is HEAD and stays.
2. **S** predecessor = P, covers_ids = a, b, c. No edge rewritten.
3. **Rendered** A chain holding all of a–c: [S, d, e]. Any other: raw.

| Item | Detail |
| --- | --- |
| `metadata.covers_ids` | Ids, because sibling branches interleave seqs. The WebUI payload adds covered turns' caller subtrees ([rendering §9](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/dag/rendering.html#s9)) |
| Next summary | Absorbs the one in effect, which `nodes.active_summary_for_chain` picks for the chain; the graph builder folds each branch with the same pick |
| Full spec | [Compaction](https://fzkuji.github.io/OpenProgram/docs/reference/design/context/compaction.html) |
| Old tool results | Never aged: each renders as its turn sent it until compaction covers its turn, so the cache prefix only grows between compactions |
| Replay | Rendering reads only stored nodes, so a graph renders the same bytes on any day; a `render_manifest` written by an earlier version is ignored |
| Spill | When recorded, once and deterministically, never when rendered |
| One pipeline | The DAG render is the only context path; if it raises, the turn fails visibly |

## Storage

| Item | Detail |
| --- | --- |
| `SessionLog` | One append-only log per session under `<state>/projects/<project_id>/chats/<id>/` |
| `SessionMemoryIndex` | Per session, lazy; node-by-id and children-by-predecessor |
| `head_id`, branch names | Session fields |
| Store scope | Raw nodes and meta; context commits belong to the commit subsystem |
| `Agent` method body | Runs in a spawned subprocess (a fork would crash on the first BLAS call once PyTorch/libomp is loaded), so stop can SIGKILL the process group |
| Its code subtree | Written by the subprocess's own SessionStore; the parent then invalidates its cache. The one truth for a function call: WebSocket frame and refresh load give the same card |

## Implementation status

[Data model](#s2) through [Compaction](#s8) and graph ownership are in code with regression coverage.

**Ablation switches**

| Variable | Moves | Read |
| --- | --- | --- |
| `OPENPROGRAM_NODE_RENDER_CAP` | Spill size for a new node that is neither a tool result nor a message (a summary, a program's return value); an existing node keeps the limit it was recorded under | At import |
| `OPENPROGRAM_NODE_SPILL` | Large-node spill | At import |
| `OPENPROGRAM_EXPOSE_DEFAULT` | What an unspecified `expose=` means; an explicit one wins | At call |

**Code map**

| File | Holds |
| --- | --- |
| `openprogram/state/store/session/nodes.py` | `Call`, `Graph`, role constants |
| `openprogram/state/store/session/session_store/` | Append invariant, `get_branch`, `spawn_branch`, `list_branches` |
| `openprogram/state/store/session/files/spill.py` | Write-path spill |
| `openprogram/runtime/context/session_dag/nodes.py` | `render_context`, segment substitution |
| `openprogram/runtime/context/session_dag/render.py` | `render_dag_messages` |
| `openprogram/runtime/context/prompt_assembly/components.py` | The system-prompt assembler |
| `openprogram/runtime/context/prompt_assembly/system_prompt_node.py` | `context/system_prompt` recording, `context/*` hiding |
| `openprogram/runtime/context/compaction/persistence.py` | Summary nodes |
| `openprogram/runtime/conversation/turn_runtime/__init__.py` | Chat entry |
| `openprogram/runtime/agent/runtime/` | Function-body model calls |

[Rendering specification](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/dag/rendering.html) · [Layout scenes](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/dag/layout.html)
