# Web runtime reliability

Out of scope: Agent reasoning, DAG storage semantics, provider protocols, permission models, multi-user identity. Topic pages keep their own detail; this page holds the shared contracts.

1. **Persist first** chat final, Job terminal, error, question, permission
2. **Connection queue** 256 frames or 4 MiB; 64 frames, 1 MiB reserved
   
   No room for a critical frame: close, state_recovery_required
3. **One sender** only caller of ws.send_text
4. **Browser** Reconnect restores from the manifest, UserErrorStore, pending questions, the Job store and request results

## Error contract

Every failure that affects a request, durable state, a background task or a recoverable operation produces an observable record. Not every internal retry is a Toast, and no traceback, file content or credential reaches a browser.

```
{
  "type": "operation_error",
  "data": {
    "error_id": "err_opaque_unique_id",
    "request_id": "client_request_id_or_null",
    "scope": "session | job | settings | channel | agent | transport | system",
    "code": "stable_machine_code",
    "message": "safe user-facing summary",
    "action": "safe_action_or_null",
    "session_id": "session_id_or_null",
    "operation_id": "action_job_execution_id_or_null",
    "retryable": false,
    "severity": "info | warning | error | fatal",
    "correlation_id": "opaque log lookup id",
    "occurred_at": "ISO-8601 UTC"
  }
}
```

Nullable fields are `null`, never omitted.

| Item | Meaning |
| --- | --- |
| `request_id` | Client-generated correlation value, not an authorization or idempotency credential. Success and failure echo it and end pending. Echoed only when nonempty, without controls, at most 128 characters; otherwise `null`. `session_id` with the same `action` likewise. |
| `error_id` | Unique per failure. Toast key is `scope + code + session_id + operation_id`: once per key in 5 seconds; every record kept. |
| `code` | `unknown_action`: protocol or version mismatch, nonretryable. `handler_error`: command failed, conservatively nonretryable. Later actions use registered codes. Unknown codes show generic text, never wire `message` or `error`. |
| `UserErrorStore` | Keyed append-only record log in the current profile (`user_errors.py`), isolated by authenticated principal: 7 days, 1,000 records per principal. Newest-first strict pagination by `occurred_at`, `error_id`. Acknowledgement closes idempotently by principal and exact ID. Send only after commit; a persistence failure sends no falsely durable frame and closes with `state_recovery_required`. |
| `severity` | `info`: diagnostics only. `warning`: local degraded state. `error`: card and one Toast. `fatal`: persistent blocking state, automatic retries stop. |
| Lifecycle | `acknowledge_user_error` answers on the requesting connection, same `request_id`: `user_error_acknowledged`, then `operation_recovered` with explicit `error_ids`, `scope`, `operation_id`, `occurred_at`. Other windows of the principal receive the same recovery; no cross-connection order, and a failed requester blocks no one. Repeats resend exact-ID recovery. Only acknowledgement or entity deletion closes; a later unrelated success never does. |
| Job failure | `job_status(status=errored)` is the only wire event; no second `operation_error`. That frame is only for a failed Job action request. |
| Compatibility | New clients read `operation_error` and legacy `action_error`; the server sends no duplicates. Web assets and worker are one release unit. `actionErrorNotice` and the `consumeActionError` alias stay normalized to one notice. |

| Failure | Display | Kept in | Excludes |
| --- | --- | --- | --- |
| Current-session request | Near the card or control; one Toast | Session error records, visible after refresh | Traceback, environment, unfiltered provider body |
| Background Job | Session-list marker; AttachCard and Jobs show summary and retryability | The Job | Full subprocess stdout, file bodies |
| Settings or management | Last known state plus the failure; never an empty list | Error center, until acknowledged | Credentials, tokens, secret paths |
| Recoverable degradation | No Toast; degraded state on the surface | Structured logs and metrics | Repeated notices |
| Disconnection | Connection state, no repeated errors while recovering | Error center after the recovery budget or with unacknowledged operations | A Toast per attempt |

- **Server**: One safe payload builder; WS actions, channels and system wrap it, JobRunner embeds it in `job_status`
- **Frontend**: `use-ws` forwards to one error store; cards, markers and Toasts derive from one record. Compatibility branches go as each backend path migrates.
- **Requests**: Success and failure both end pending; no button loads forever

## Session loading

Initial cost follows visible content, not history. SessionDB and the DAG are the only durable authority; the wire carries projections.

### Bounded session history

| Aspect | Rule |
| --- | --- |
| Page | Whole turns: a prompt and everything it owns, caller descendants included. First page 6 turns and 128 KiB target; later pages 25 turns and 512 KiB (`transcript/reader.py`). One larger turn is sent alone. |
| Cursor | Captured branch head plus a stable cursor; any message id on the branch finds its turn. An unavailable cursor gives an explicit retryable error, not a reconnect loop. |
| Side effects | None: paging never edits history or model context, or changes focus, live head, execution state or question replay |
| Fragments | History and graph responses over the frame budget go as ordered, awaited fragments, reassembled before dispatch and ordered with later live notifications. Per connection: 64 Mi UTF-16 code units, 8 incomplete transfers, 1,024 logical responses (`history-fragments.ts`). Buffers die with the connection. |
| Wire size | Duplicate promoted fields are dropped from `extra`. Tool previews keep authorized full-output expansion. |
| Client | Prepends older rows by identity without replacing newer content. Requests capture the load generation and are ignored after a reload, branch switch or socket replacement. Scroll stays anchored. |
| Reconnect | Loads a fresh recent page; existing execution recovery continues |
| Long sessions | Graph depth: memoized parent-chain classification, then iterative preorder; no Python recursion. Nodes whose parent path enters a cycle stay independent roots. Forks, retries, spawned branches and call children keep order and offsets. Follow-up normalization indexes replies once; lane placement keeps per-lane widths and the largest column instead of rescanning. |
| Threads | Message aggregation, page preparation and Graph build run off the event loop; awaited sends stay on it. Snapshot and event order are unchanged. The in-memory session index remains authoritative; no persistent cache or migration. |
| Limits | The full Graph stays for branch and compaction controls. Projection scans the captured session; initial Graph and store memory grow with session size. Storage indexing and lazy graph rendering are separate work. |

**Acceptance and comparison**

| Area | Must hold |
| --- | --- |
| Opening | The failing session opens without queue overflow |
| Pages | Exact content and caller ownership; cursor exhaustion loses and duplicates nothing |
| Frames | Bounded, including Unicode and one oversized row |
| Concurrency | Stale responses cannot overwrite newer state; disconnection releases buffers |
| Features | Branch, compaction, tool expansion and execution recovery work |
| Large transcript | 10,000 nodes load a bounded recent page with no recursion failure |
| Layout | Small-graph output matches existing layout contracts; long chains, wide forks and invalid cycles are covered |

[Codex](https://github.com/openai/codex/blob/main/codex-rs/app-server/src/request_processors/thread_processor.rs) separates thread metadata, turns and items through paginated history APIs. [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness/blob/main/packages/api/session-controller/src/history.ts) exposes message-aligned pages and sequence cursors. Adopted: stable branch snapshots, backward paging, incremental live updates. Kept: our branch graph and execution recovery; no other session store; model compaction unchanged.

### Target projection

| Phase | Returns | Trigger | Cache key |
| --- | --- | --- | --- |
| Manifest | Title, status, head, revision, current-chain IDs, counts, feature state, open error IDs | Session switch, no valid manifest | `session_id + revision` |
| Graph summary | Node IDs, edges, roles, states, minimal labels; no bodies | DAG or branch panel opens | `session_id + graph_revision` |
| Node detail | Node context, full tool output, runtime tree, attachment details | Expand or navigate | `session_id + node_id + content_revision` |
| Reconnect delta | Commits after the known revision; events after each known seq | Reconnect, deltas contiguous | `known_session_revision`, `known_stream_seqs: {entity_id: seq}` |
| Full recovery | New manifest and a bounded page, never full history | Incompatible revision, evicted delta, invalid client state | Resets the local projection |

| Quantity | Definition | Retention and fallback |
| --- | --- | --- |
| `session_revision` | Monotonic per session, +1 per atomic commit; on manifest, headers, Graph summary, durable errors | Permanent. A client value above the server's, or an incompatible schema, gets a new manifest. |
| `stream_seq` | Monotonic per running message or job; uncommitted changes only | 256 deltas or 15 minutes per entity in the worker. Restart persists unfinished entities as error or aborted, then manifest recovery. |
| Delta journal | `from_revision → to_revision` projection changes, no body copies | 512 commits or 15 minutes in memory. Larger gaps: manifest and a bounded page. |
| Detail cursor | At most 1 MiB uncompressed per read; chunked at UTF-8 boundaries | Reauthorized on every read; cannot cross nodes or sessions |

- A thread reads an immutable snapshot and returns plain objects. The async handler rechecks revision before sending; a concurrent write yields manifest-plus-delta or a new snapshot. Threads never touch WebSockets.
- Prebuild `id → insertion_index`, group siblings once by predecessor, read the session row once per request, serialize Graph summary apart from bodies.
- Extend on-demand reads to context trees, runtime blocks, Graph-node content and attachment metadata. Legacy clients get upgrade guidance from payload caps, not unbounded frames.
- Capture existing frame order first, then replace layers; never move a whole async handler into `to_thread`.

## WebSocket delivery

`openprogram/interfaces/server/ws_delivery.py`. Browser WebSockets have no automatic backpressure ([MDN](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)), and client [`bufferedAmount`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/bufferedAmount) cannot replace a server queue. Producer threads only enqueue, through event-loop-safe scheduling ([asyncio.Queue](https://docs.python.org/3/library/asyncio-queue.html)).

| Frame | Example | Queue rule | Overflow |
| --- | --- | --- | --- |
| Terminal, never dropped | error, question, chat final, Job terminal, ack, permission result | Order kept; no overwriting or merging | Close and require state recovery |
| Coalescible delta | text and thinking delta, tree update, progress, context stats | By `session + entity + type`: newest state, or merge adjacent text | Superseded deltas removed and counted |
| Snapshot | sessions list, branches, settings, graph summary | Newest unsent per key | Replaced; terminal frames untouched |
| Control | pong, auth, status, reload required | Own small budget, so large messages cannot starve it | Auth and protocol errors close; stale pongs may drop |

- **Capacity**: Queued plus in-flight. Before a critical enqueue, coalescible deltas are removed.
- **Disconnect**: Cancel the sender, free the queue, unregister focus; no other thread holds WebSocket Futures
- **Chat ack**: Follows durable user-message storage; other acks are queryable or replayable by `request_id`
- **Client close**: Derives transport state from close or timeout, not from a server frame
- **Metrics**: `queue_frames`, `queue_bytes`, `oldest_age`, `coalesced`, `send_failures`, `disconnect_reason`, `recovery_mode`; no frame bodies
- **Target reconnect**: Backoff with jitter; page visibility or explicit retry may go earlier; protocol state restored before session projection

## EventBus

|  | Gate | Notify (target) |
| --- | --- | --- |
| Purpose | Allow or reject before an action | Record, update UI, trigger nonblocking work |
| Runs on | Emitter thread; target total budget `events.gate_timeout_ms=50` | EventBus-owned loop; synchronous consumers on a thread pool |
| Failure | Fail-open with structured warnings and results | Consumers isolated; retries are their policy; never skipped silently |
| Order | Registration | Strict FIFO per `session_id + entity_id`, else session, else `type + origin`; concurrent across keys |
| Backpressure | No queue; budget expiry skips the rest and records it | Ordinary 4,096 events; critical 512 (operation error and recovered, question, Job terminal, turn end, critical `ws.frame`) |
| Full queue |  | Coalesce or drop keyed telemetry with metrics. Critical full: durable state remains the authority; write a loss marker and tell Web connections to recover. Stderr alone is not delivery. |
| Shutdown |  | Drain up to 2 seconds, then shutdown loss markers. Critical state persists before emit and recovers from store scans; EventBus is not a durable queue. |
| Logging | Event and verdict in one record | Async batches; large payloads as size, digest, controlled preview |

- Permission, authentication, sandbox and credential checks do not use EventBus gates, which carry plugin and workflow decisions only.
- Session or global log by session presence, never both; one row per event ID per file. `tool.after.result_text` logs byte count, error status, hash, bounded preview; full results stay in SessionDB and tool-result storage.
- Tests parse `emit_safe` and `make_event` AST, including multiline calls. Dynamic names need explicit exceptions and consumers.
- The EventBus-to-Web adapter forwards registered user-relevant envelopes only.
- Plugin-hook signatures stay public and unchanged.

## Frontend and static assets

| Area | Rule | Verification |
| --- | --- | --- |
| Streaming | Coalesce per animation frame, per-message selector. Target: flush matching deltas before terminal state; update error record and reply state atomically. | At most one store update per frame; complete terminal content |
| Long lists | `MessageRow` memo, row recycling, stable ID arrays. Target: Graph panels no longer force full Graph bodies into chat stores. | DOM and commits at 1,000+ nodes do not grow linearly |
| Error UI | Existing Toast and unread state. Target: error store, durable cards, background markers, deduplication. | Current session, background session, after refresh |
| marked, KaTeX | Bundled locally; no CDN loader or WS wait ([`script-src 'self'`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy/script-src), no `unsafe-inline` or `unsafe-eval`) | Zero CSP violations; works offline |
| Static responses | Same-origin export, cache headers, [Starlette gzip](https://starlette.dev/middleware/) with MIME-aware exclusions and case-insensitive q-weights preferring explicit gzip over `*`. No recompression; no SSE compression; small responses left alone. | Negotiation, MIME and existing-encoding regressions |
| Code splitting | Non-initial center-tab surfaces import on demand with a pending state | `apps/web/scripts/runtime/check-static-resource-budget.mjs`: 2 MiB transfer, 650 KiB initial script, 350 KiB per chunk, named caps for prebuilt on-demand libraries |
| Browser home | Local text icons; no automatic favicon requests | `check-local-runtime-assets.mjs` |

## Metrics and capacity

Counts, durations, bytes and correlation IDs only; no prompts, responses, tool output or credentials.

| Area | Recorded |
| --- | --- |
| WebSocket | Connections, queue bytes, send latency and failures, coalesced count, reconnects, recovery mode, full-recovery reasons |
| Session load | Manifest, message and graph bytes; DB read, projection, serialization, send durations; viewport hits, detail fetches, delta fallbacks |
| EventBus | Enqueue and handler duration, depth, failures, retries, drop reasons, gate time, budget overruns |
| Storage | Sessions, logs, Chrome cache, models, IndexedDB. Target and impact shown before user-triggered cleanup. |

Browser profiles are user state and are never deleted by a timer or startup hook. Rebuildable cache and models are listed apart from identity, extensions and IndexedDB, and need explicit confirmation per category.

## Remaining work

| Task | Depends on | Bounds |
| --- | --- | --- |
| Frontend error state and remaining error paths | None | Generic action errors only, not Job states |
| Job error display | The error store | `job_status` alone carries the terminal state; safe summaries, tracebacks stay in logs. `openprogram/runtime/jobs/runner/`, `ws-events.ts`, `attach-card.tsx`. |
| Session projection and incremental recovery | WebSocket delivery | SessionDB and DAG only; measure payloads and fix protocol contracts first. `session/load.py`, `messages.py`, `use-ws.ts`. |
| EventBus notify and logs | Error envelope, delivery | Sole owner of `events/bus.py`, `registry.py`, `event_log.py` |
| Capacity diagnostics | None | Read-only first; deletion needs its own design and confirmation |

## Acceptance

| Entry and scenario | Criterion | Evidence |
| --- | --- | --- |
| Any registered WS action raises | Same socket gets safe `operation_error`; connection survives; UI within 250 ms; correlation ID finds logs | Receive-loop test, reducer and UI test |
| list, delete, settings, channel storage failure | No normal empty result or silent success | Per-action contract tests |
| JobRunner, refresh after failure | Job, AttachCard and marker show one safe reason; `retryable` agrees | Persistence, WS, React integration |
| Largest known session, no cache | First uncompressed projection ≤ 1 MiB; event-loop occupancy ≤ 50 ms | Fixed-session fixture |
| Reconnect, ≤ 64 missing deltas | No full history; recovery ≤ 256 KiB; terminals, errors, questions kept | Disconnect and recovery protocol tests |
| Slow client, continuous stream | Queue within limits; terminals never lost; unrecoverable overflow closes | Controlled slow-sender test |
| Notify, slow plugin and async subscriber | Enqueue p99 ≤ 1 ms; async subscribers not skipped; failures block no peers | Concurrency benchmark, behaviour tests |
| One gated `tool.before` | One target log, one row with verdict, no large bodies | Event-file assertions |
| First load, no cache, gzip | Zero CSP violations and CDN requests; ≤ 2 MiB; largest JS ≤ 350 KiB | Default-App trace, HTTP headers |
| Profile over warning size | Right categories; nothing deleted unconfirmed; report lists recoverability | Temporary-profile tests |

**Measurement definitions**

| Metric | Definition | Sample | Why this threshold |
| --- | --- | --- | --- |
| Session wire bytes | UTF-8 of backend `json.dumps`; fixed anonymized fixture, cold stats off | 5 runs; median, max, breakdown | 1 MiB is the first-stage cap from 11.66 MB |
| Event-loop occupancy | Handler entry to first awaited send, loop thread only | 20 runs; p50, p95, max | 50 ms budgets interactivity, not page completion |
| Error UI latency | Frame received to card in DOM | 20 runs; p95 | 250 ms, well under the 2-second reconnect interval |
| Notify enqueue | `emit` entry to enqueue | 10,000 calls, 1 and 8 workers | p99 ≤ 1 ms keeps notify off tool and turn time |
| Static transfer | Default App, no cache or extensions; sum `encodedBodySize` | 5 cold loads | 2 MiB from 3.42 MB; 350 KiB keeps lazy surfaces out of the first bundle |
| CSP | Violations from our origin only | Cold load, math message, Settings, DAG | Zero is a security contract |
| Capacity categories | Allocated and logical bytes; symlinks stay inside the state root | Fixed tree and real read-only run | Sum within 1% or 1 MiB of the root |

**Measured baseline**

One audit before this work, without committed fixtures; observational only. Formal comparisons use the fixtures above.

| Measure | Value |
| --- | --- |
| Largest `session_loaded` | 11.66 MB: messages about 9.75 MB, Graph 1.91 MB; 112 visible of 1,790 graph rows |
| Hydration | About 313 ms in `handle_load_session` |
| Cold static transfer | 3.42 MB, 66 resources, 43 scripts, uncompressed. After local assets and gzip: about 1.22 MB, largest script about 187 KiB, 65 local requests. |
| Cold navigation | About 123 ms; DOMContentLoaded about 39 ms |
| Worker memory | About 437 MB; short CPU samples 4.1% to 0.3% |
| State directory | 6.3 GB: `chrome-profile` about 6.1 GB (on-device model, Default profile, model store), sessions about 8.5 MB |
| Slow client | Peak concurrent `send_text` 400 before the sender, 1 after |
| Gated `tool.before` ×1,000 | Log rows 2,000 to 1,000; synchronous logging median 105 ms to 58 ms |
| Sibling navigation | 2,000 messages, 100 visible: 134 ms to 1.4 ms |
| Largest observed history frame | 51,564 bytes |

## Choices

| Choice |  | Reason |
| --- | --- | --- |
| Standard WebSocket with bounded queues | Selected | Stable browsers; the server still owns queue, coalescing and recovery |
| Unified `operation_error` | Selected | Stable codes and safe text; temporary adapters for old frames |
| Dedicated notify execution | Selected | Nonblocking observation; gates stay synchronous |
| Bundled marked and KaTeX | Selected | Strict CSP, offline, reproducible builds |
| Relaxing CSP for CDNs | Rejected | Adds remote trust without solving first-connection waits |
| WebSocketStream or WebTransport | Rejected | Browser support and scope; replaces neither recovery nor error contracts |
| Global React store rewrite | Rejected | Existing coalescing and recycling are not proven bottlenecks |
| Automatic Chrome-profile deletion | Rejected | Can remove logins, IndexedDB, extensions |

Session-protocol changes affect refresh order, branch switches, running cards, question replay and send queues.

## Implementation status

| Capability | State | Remaining |
| --- | --- | --- |
| Public dispatcher, agent, channel, settings failures | Done on the server: `operation_error`, persisted before send, list, acknowledge, recover | Validation codes; runtime, session, project and channel QR paths |
| Frontend error store | Open. Web and TUI consume `operation_error` and `action_error` as one low-sensitivity notice; Web does not call `list_user_errors`. | Current-session cards, background markers, Toast deduplication, reconnect hydration |
| Job errors | Open. `job_status` carries `error`; `attach-card.tsx` and the branches view show only `errored`. | Job-stored safe summary, retryability, correlation ID; shown after refresh |
| Session paging | Done. See [Bounded session history](#bounded-session-history). | Manifest, Graph summary, node detail, reconnect deltas. `session_loaded` still sends the complete Graph. |
| Off-loop session work | Partial. Reads, paging and Graph build run in threads; sibling navigation uses request-local indexes. | One session-row snapshot; event-loop budget |
| WebSocket backpressure | Done. `ws_delivery.py`, one sender per connection. |  |
| Reconnect timing | Open. Fixed 2-second retry in `use-ws.ts`, then a fresh recent page. | Exponential backoff with jitter; known revision and seq |
| EventBus notify | Open. `_call` runs handlers in the emitter thread; async handlers are skipped with no running loop. | Dedicated queue |
| Event log | Partial. One record per gated event; duplicate `tool.before` rows are gone. | Async batched writes, large-field summaries, AST registry check that sees multiline emits |
| Local assets and compression | Done. No product CDN resources, no automatic Google favicons, self-only CSP. | Remote-deployment browser traces |
| Capacity diagnostics | Open. Inspectable only through the filesystem. | Read-only categories, then explicit cleanup |
| Existing, kept | Chat reply error bubbles; 32 KiB tool-result markers with `get_full_tool_output`; rAF stream coalescing; `MessageRow` subscriptions and row recycling | Link chat errors to the error center without duplicate Toasts; extend on-demand reads to the other large fields |

[Error handling](https://fzkuji.github.io/OpenProgram/docs/reference/design/repository/error-handling.html) · [Event layer](https://fzkuji.github.io/OpenProgram/docs/reference/design/proactive/event-layer.html) · [Framework signal routing](https://fzkuji.github.io/OpenProgram/docs/reference/design/proactive/framework-evolution.html) · [UI invariants](https://fzkuji.github.io/OpenProgram/docs/reference/design/ui/invariants.html) · [Interaction feedback](https://fzkuji.github.io/OpenProgram/docs/reference/design/ui/interaction-feedback.html) · [WebSocket command lifecycle](https://fzkuji.github.io/OpenProgram/docs/reference/design/ui/turn-lifecycle/websocket-command-lifecycle.html) · [Streaming resume](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/operations/streaming-resume.html) · [Async task lifecycle](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/execution/async-job-lifecycle.html) · [Session subsystem](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/session/README.html)
