OpenProgram Docs

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.

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

    No room for a critical frame: close, state_recovery_required

  3. One senderonly caller of ws.send_text
  4. BrowserReconnect 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.

ItemMeaning
request_idClient-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_idUnique per failure. Toast key is scope + code + session_id + operation_id: once per key in 5 seconds; every record kept.
codeunknown_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.
UserErrorStoreKeyed 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.
severityinfo: diagnostics only. warning: local degraded state. error: card and one Toast. fatal: persistent blocking state, automatic retries stop.
Lifecycleacknowledge_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 failurejob_status(status=errored) is the only wire event; no second operation_error. That frame is only for a failed Job action request.
CompatibilityNew 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.
FailureDisplayKept inExcludes
Current-session requestNear the card or control; one ToastSession error records, visible after refreshTraceback, environment, unfiltered provider body
Background JobSession-list marker; AttachCard and Jobs show summary and retryabilityThe JobFull subprocess stdout, file bodies
Settings or managementLast known state plus the failure; never an empty listError center, until acknowledgedCredentials, tokens, secret paths
Recoverable degradationNo Toast; degraded state on the surfaceStructured logs and metricsRepeated notices
DisconnectionConnection state, no repeated errors while recoveringError center after the recovery budget or with unacknowledged operationsA 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

AspectRule
PageWhole 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.
CursorCaptured 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 effectsNone: paging never edits history or model context, or changes focus, live head, execution state or question replay
FragmentsHistory 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 sizeDuplicate promoted fields are dropped from extra. Tool previews keep authorized full-output expansion.
ClientPrepends 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.
ReconnectLoads a fresh recent page; existing execution recovery continues
Long sessionsGraph 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.
ThreadsMessage 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.
LimitsThe 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
AreaMust hold
OpeningThe failing session opens without queue overflow
PagesExact content and caller ownership; cursor exhaustion loses and duplicates nothing
FramesBounded, including Unicode and one oversized row
ConcurrencyStale responses cannot overwrite newer state; disconnection releases buffers
FeaturesBranch, compaction, tool expansion and execution recovery work
Large transcript10,000 nodes load a bounded recent page with no recursion failure
LayoutSmall-graph output matches existing layout contracts; long chains, wide forks and invalid cycles are covered

Codex separates thread metadata, turns and items through paginated history APIs. DeepSeek Harness 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

PhaseReturnsTriggerCache key
ManifestTitle, status, head, revision, current-chain IDs, counts, feature state, open error IDsSession switch, no valid manifestsession_id + revision
Graph summaryNode IDs, edges, roles, states, minimal labels; no bodiesDAG or branch panel openssession_id + graph_revision
Node detailNode context, full tool output, runtime tree, attachment detailsExpand or navigatesession_id + node_id + content_revision
Reconnect deltaCommits after the known revision; events after each known seqReconnect, deltas contiguousknown_session_revision, known_stream_seqs: {entity_id: seq}
Full recoveryNew manifest and a bounded page, never full historyIncompatible revision, evicted delta, invalid client stateResets the local projection
QuantityDefinitionRetention and fallback
session_revisionMonotonic per session, +1 per atomic commit; on manifest, headers, Graph summary, durable errorsPermanent. A client value above the server's, or an incompatible schema, gets a new manifest.
stream_seqMonotonic per running message or job; uncommitted changes only256 deltas or 15 minutes per entity in the worker. Restart persists unfinished entities as error or aborted, then manifest recovery.
Delta journalfrom_revision → to_revision projection changes, no body copies512 commits or 15 minutes in memory. Larger gaps: manifest and a bounded page.
Detail cursorAt most 1 MiB uncompressed per read; chunked at UTF-8 boundariesReauthorized 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), and client bufferedAmount cannot replace a server queue. Producer threads only enqueue, through event-loop-safe scheduling (asyncio.Queue).

FrameExampleQueue ruleOverflow
Terminal, never droppederror, question, chat final, Job terminal, ack, permission resultOrder kept; no overwriting or mergingClose and require state recovery
Coalescible deltatext and thinking delta, tree update, progress, context statsBy session + entity + type: newest state, or merge adjacent textSuperseded deltas removed and counted
Snapshotsessions list, branches, settings, graph summaryNewest unsent per keyReplaced; terminal frames untouched
Controlpong, auth, status, reload requiredOwn small budget, so large messages cannot starve itAuth 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

GateNotify (target)
PurposeAllow or reject before an actionRecord, update UI, trigger nonblocking work
Runs onEmitter thread; target total budget events.gate_timeout_ms=50EventBus-owned loop; synchronous consumers on a thread pool
FailureFail-open with structured warnings and resultsConsumers isolated; retries are their policy; never skipped silently
OrderRegistrationStrict FIFO per session_id + entity_id, else session, else type + origin; concurrent across keys
BackpressureNo queue; budget expiry skips the rest and records itOrdinary 4,096 events; critical 512 (operation error and recovered, question, Job terminal, turn end, critical ws.frame)
Full queueCoalesce 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.
ShutdownDrain up to 2 seconds, then shutdown loss markers. Critical state persists before emit and recovers from store scans; EventBus is not a durable queue.
LoggingEvent and verdict in one recordAsync 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

AreaRuleVerification
StreamingCoalesce 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 listsMessageRow 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 UIExisting Toast and unread state. Target: error store, durable cards, background markers, deduplication.Current session, background session, after refresh
marked, KaTeXBundled locally; no CDN loader or WS wait (script-src 'self', no unsafe-inline or unsafe-eval)Zero CSP violations; works offline
Static responsesSame-origin export, cache headers, Starlette gzip 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 splittingNon-initial center-tab surfaces import on demand with a pending stateapps/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 homeLocal text icons; no automatic favicon requestscheck-local-runtime-assets.mjs

Metrics and capacity

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

AreaRecorded
WebSocketConnections, queue bytes, send latency and failures, coalesced count, reconnects, recovery mode, full-recovery reasons
Session loadManifest, message and graph bytes; DB read, projection, serialization, send durations; viewport hits, detail fetches, delta fallbacks
EventBusEnqueue and handler duration, depth, failures, retries, drop reasons, gate time, budget overruns
StorageSessions, 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

TaskDepends onBounds
Frontend error state and remaining error pathsNoneGeneric action errors only, not Job states
Job error displayThe error storejob_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 recoveryWebSocket deliverySessionDB and DAG only; measure payloads and fix protocol contracts first. session/load.py, messages.py, use-ws.ts.
EventBus notify and logsError envelope, deliverySole owner of events/bus.py, registry.py, event_log.py
Capacity diagnosticsNoneRead-only first; deletion needs its own design and confirmation

Acceptance

Entry and scenarioCriterionEvidence
Any registered WS action raisesSame socket gets safe operation_error; connection survives; UI within 250 ms; correlation ID finds logsReceive-loop test, reducer and UI test
list, delete, settings, channel storage failureNo normal empty result or silent successPer-action contract tests
JobRunner, refresh after failureJob, AttachCard and marker show one safe reason; retryable agreesPersistence, WS, React integration
Largest known session, no cacheFirst uncompressed projection ≤ 1 MiB; event-loop occupancy ≤ 50 msFixed-session fixture
Reconnect, ≤ 64 missing deltasNo full history; recovery ≤ 256 KiB; terminals, errors, questions keptDisconnect and recovery protocol tests
Slow client, continuous streamQueue within limits; terminals never lost; unrecoverable overflow closesControlled slow-sender test
Notify, slow plugin and async subscriberEnqueue p99 ≤ 1 ms; async subscribers not skipped; failures block no peersConcurrency benchmark, behaviour tests
One gated tool.beforeOne target log, one row with verdict, no large bodiesEvent-file assertions
First load, no cache, gzipZero CSP violations and CDN requests; ≤ 2 MiB; largest JS ≤ 350 KiBDefault-App trace, HTTP headers
Profile over warning sizeRight categories; nothing deleted unconfirmed; report lists recoverabilityTemporary-profile tests
Measurement definitions
MetricDefinitionSampleWhy this threshold
Session wire bytesUTF-8 of backend json.dumps; fixed anonymized fixture, cold stats off5 runs; median, max, breakdown1 MiB is the first-stage cap from 11.66 MB
Event-loop occupancyHandler entry to first awaited send, loop thread only20 runs; p50, p95, max50 ms budgets interactivity, not page completion
Error UI latencyFrame received to card in DOM20 runs; p95250 ms, well under the 2-second reconnect interval
Notify enqueueemit entry to enqueue10,000 calls, 1 and 8 workersp99 ≤ 1 ms keeps notify off tool and turn time
Static transferDefault App, no cache or extensions; sum encodedBodySize5 cold loads2 MiB from 3.42 MB; 350 KiB keeps lazy surfaces out of the first bundle
CSPViolations from our origin onlyCold load, math message, Settings, DAGZero is a security contract
Capacity categoriesAllocated and logical bytes; symlinks stay inside the state rootFixed tree and real read-only runSum 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.

MeasureValue
Largest session_loaded11.66 MB: messages about 9.75 MB, Graph 1.91 MB; 112 visible of 1,790 graph rows
HydrationAbout 313 ms in handle_load_session
Cold static transfer3.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 navigationAbout 123 ms; DOMContentLoaded about 39 ms
Worker memoryAbout 437 MB; short CPU samples 4.1% to 0.3%
State directory6.3 GB: chrome-profile about 6.1 GB (on-device model, Default profile, model store), sessions about 8.5 MB
Slow clientPeak concurrent send_text 400 before the sender, 1 after
Gated tool.before ×1,000Log rows 2,000 to 1,000; synchronous logging median 105 ms to 58 ms
Sibling navigation2,000 messages, 100 visible: 134 ms to 1.4 ms
Largest observed history frame51,564 bytes

Choices

ChoiceReason
Standard WebSocket with bounded queuesSelectedStable browsers; the server still owns queue, coalescing and recovery
Unified operation_errorSelectedStable codes and safe text; temporary adapters for old frames
Dedicated notify executionSelectedNonblocking observation; gates stay synchronous
Bundled marked and KaTeXSelectedStrict CSP, offline, reproducible builds
Relaxing CSP for CDNsRejectedAdds remote trust without solving first-connection waits
WebSocketStream or WebTransportRejectedBrowser support and scope; replaces neither recovery nor error contracts
Global React store rewriteRejectedExisting coalescing and recycling are not proven bottlenecks
Automatic Chrome-profile deletionRejectedCan remove logins, IndexedDB, extensions

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

Implementation status

CapabilityStateRemaining
Public dispatcher, agent, channel, settings failuresDone on the server: operation_error, persisted before send, list, acknowledge, recoverValidation codes; runtime, session, project and channel QR paths
Frontend error storeOpen. 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 errorsOpen. 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 pagingDone. See Bounded session history.Manifest, Graph summary, node detail, reconnect deltas. session_loaded still sends the complete Graph.
Off-loop session workPartial. Reads, paging and Graph build run in threads; sibling navigation uses request-local indexes.One session-row snapshot; event-loop budget
WebSocket backpressureDone. ws_delivery.py, one sender per connection.
Reconnect timingOpen. Fixed 2-second retry in use-ws.ts, then a fresh recent page.Exponential backoff with jitter; known revision and seq
EventBus notifyOpen. _call runs handlers in the emitter thread; async handlers are skipped with no running loop.Dedicated queue
Event logPartial. 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 compressionDone. No product CDN resources, no automatic Google favicons, self-only CSP.Remote-deployment browser traces
Capacity diagnosticsOpen. Inspectable only through the filesystem.Read-only categories, then explicit cleanup
Existing, keptChat reply error bubbles; 32 KiB tool-result markers with get_full_tool_output; rAF stream coalescing; MessageRow subscriptions and row recyclingLink chat errors to the error center without duplicate Toasts; extend on-demand reads to the other large fields

Error handling · Event layer · Framework signal routing · UI invariants · Interaction feedback · WebSocket command lifecycle · Streaming resume · Async task lifecycle · Session subsystem

Last updated · 2026-11-25