Skip to content

Event Sync

root edited this page Dec 4, 2026 · 4 revisions

Event Synchronization

🌐 English · 简体中文

This page explains how Trizano propagates state changes from a Node's Session actor through the Hub's single aggregated stream to the web and Android clients, including incremental merging, delta batching, lazy timeline loading, and scoped resyncs. It is aimed at developers reading or modifying the synchronization pipeline.

Three-Tier Sequence Numbers and Replay Windows

Synchronization state is partitioned into three scopes: each Session protects timeline continuity with a monotonic rev, each Node maintains a host-local {boot, seq} replay window, and the Hub's replay window holds only Entry-level events without buffering or re-ordering Node events.

Tier Single owner Sequence / cursor Replay window Events covered
Session timeline Session actor goroutine (server/node/session/session.go) Per-session monotonic rev (persisted in Session.rev) No in-memory window; gaps resync via GetSessionView ItemsChanged, ItemDelta
Node event stream Node eventlog.Log (server/node/node.go) {boot, seq} (in-process node_seq) 16 MiB or 1 hour Workspaces, Sessions, timelines, tasks, terminals, browser tabs, review, rate limits, settings, agent catalogs, Roster changes
Entry event stream Hub eventlog.Log (server/hub/hub.go) {boot, seq} 4 MiB or 1 hour NodeChanged, NodeRemoved, PairingsChanged, NodeEnrollmentsChanged, RosterChanged
  • Session actor and rev: Every Session on a Node is owned exclusively by one Session.run() goroutine. Callers send closures via do (which loads the timeline if sleeping) or look (lightweight metadata reads). Every item upsert or streaming flush increments s.data.Rev by exactly 1 and emits an ItemsChanged or ItemDelta carrying that rev (defined in proto/trizano/node/v1/event.proto).
  • Node boot and replay window: server/internal/eventlog/log.go generates a random boot token via rand.Text() on log creation and seeds seq from the process start timestamp in microseconds (time.Now().UnixMicro()). Subscribers pass {since, boot}; Sub.Resumed is true with pending events populated in Backlog only if boot matches and all events after since remain in the window. Otherwise the log sets Resumed = false and subscribes from the current Head. Each subscriber channel buffers 1024 events; a slow consumer that overflows terminates with ErrOverflow, forcing reconnect from its last applied cursor.
  • Hub buffers Entry events only: The eventlog.Log created in server/hub/hub.go (4 MiB / 1 hour) records only Node state/removal, device pairings, Node enrollments, and Roster changes. Node events bypass the Hub buffer—when forwarded, the outer hubv1.Event.seq is always 0 while the inner Node event keeps its own seq. As a result, when a Hub restarts or a client fails over to another Entry, every Node stream resumes cleanly as long as the Node itself did not restart and remains within its replay window.

Single-Stream Fan-Out and Per-Node Forwarding

A client holds a single long-lived trizano.hub.v1.EventService/Watch stream carrying its Entry cursor and a map of per-Node {boot, seq} cursors. Inside that stream, the Hub opens one Node Watch per online Node and multiplexes all events back to the client.

eventService.Watch in server/hub/events.go runs the following lifecycle:

  1. Subscribes to the Hub's own eventlog.Log with req.Entry, immediately sends the Entry Hello{resumed, boot} (seq is the resume point or current Head), and flushes any Entry backlog in order.
  2. Creates a followers manager scoped to this Watch stream and seeds its per-Node cursor map from req.Nodes. For every Node already online—and whenever an Entry event later reports NODE_STATE_ONLINE—it spawns a follower goroutine calling trizano.node.v1.EventService/Watch{since, boot}.
  3. Wraps every Node event (including the Node's initial Hello) in NodeEvent{node, event} on the outer stream. Each follower advances only its own cursor; ordering is strictly preserved within a Node, with no global ordering across Nodes.
  4. If a Node stream ends unexpectedly while the Node is still online, the follower reconnects automatically—immediately if the previous stream had already received the Node's Hello, or with 1 s to 30 s exponential backoff otherwise. When a Node goes offline, the follower exits and returns its latest cursor to followers.cursors so it can resume once the Node comes back. On NodeRemoved, the follower is canceled and its cursor is deleted.
  5. While idle, the Hub emits a Heartbeat every 10 seconds (seq = 0, neither buffered nor cursor-advancing). Clients treat 25 seconds without any event (STALL_TIMEOUT_MS = 25_000 on web; 25-second OkHttp streaming read timeout on Android) as a dead stream and reconnect.

The Hub's Node registry (server/hub/nodes/node.go) also opens a separate internal Watch starting from head on each online Node to monitor liveness and trigger deferred build replacements when the last active Turn finishes. That internal stream is never forwarded to clients (see Node Internals).

sequenceDiagram
    participant C as Client
    participant H as Hub
    participant NA as Node A
    participant NB as Node B

    C->>H: Watch(entry={bootH, seqH}, nodes={A: cA, B: cB})
    H-->>C: Hello(resumed, bootH) + Entry backlog
    par Hub opens one follower stream per online Node
        H->>NA: Watch(since=cA.seq, boot=cA.boot)
        NA-->>H: Hello(resumed=true, bootA) + Backlog
        H-->>C: NodeEvent(A, Hello) + live events
    and
        H->>NB: Watch(since=cB.seq, boot=cB.boot)
        NB-->>H: Hello(resumed=false, bootB')
        H-->>C: NodeEvent(B, Hello(resumed=false))
        C->>H: Resync Node B metadata and visible timelines
    end
    Note over C,H: A Session rev gap triggers GetSessionView for that Session only
Loading

Three-Level Resync

Each tier recovers independently so a missed cursor or transient error on one Node or Session never stalls the rest of the stream:

  1. Level 1: Entry Resync
    • Trigger: Entry Hello arrives with resumed == false (first connect, Hub restart with a new boot, or offline longer than the Hub's 1 hour / 4 MiB window).
    • Action: Concurrently fetches ListNodes, ListPairings, and ListNodeEnrollments, updates Entry state, and prunes any removed Nodes from local nodeCursors. Individual Node data is not fetched here; each Node's subsequent Hello decides whether that Node needs a resync.
    • Web-only behavior: If the Entry boot changed from the previous value, web calls checkWebBuild() (web/src/lib/webBuild.ts) to check whether static web assets were updated on the server.
  2. Level 2: Node Resync
    • Trigger: NodeEvent(Hello) arrives for a Node with resumed == false, or that Node failed a previous resync and remains in the behind set.
    • Action: Concurrently refetches metadata for that Node only (agent catalog, Workspaces, Session list, tasks, rate limits; web also fetches terminals, browser tabs, Node settings, project scripts, and review state).
    • Timeline handling: Web only refetches timelines currently mounted in the UI (tracked via showTimeline reference counts) and drops cached timelines for hidden Sessions so they reload on demand when reopened. Android refetches Sessions currently present in timelines. If a Node resync fails, that Node stays in behind while all other Nodes continue receiving events normally; the next Hello from that Node retries the resync.
    • Catch-up on clean resume: Even when resumed == true and the Node is not in behind, web calls loadMissing(nodeId) to retry any visible timelines or review states that previously failed to load; Android increments NodeData.hellos so active screens can fill in missing data.
  3. Level 3: Session Resync
    • Trigger: When applying ItemsChanged or ItemDelta, the client compares local timeline.rev against ev.rev:
      • ev.rev <= timeline.rev: stale (already included in snapshot), ignored.
      • ev.rev == timeline.rev + 1: applied normally, advancing rev to ev.rev.
      • ev.rev > timeline.rev + 1: gap detected; triggers GetSessionView for that Session only without blocking events for other Sessions.
    • In-flight protection (web/src/state/sync.ts): At most one GetSessionView request is in flight per Session (tracked in the fetching map). Any ItemsChanged / ItemDelta arriving while the fetch is running is buffered in flight.missed and replayed in order once the snapshot returns. If replay hits another gap, the client retries automatically; more than MAX_GAP_RETRIES = 3 consecutive gaps surfaces an error asking the user to retry.

Delta Batching and Lazy Timeline Loading

Streaming output and long Sessions dominate sync overhead. Nodes and clients bound CPU, bandwidth, and memory with batching and lazy loading.

Streaming Delta Batching

  • Node-side 50 ms batching (server/node/session/session.go): Agents often emit a few characters at a time. Instead of bumping rev on every chunk, Session.delta() accumulates text per item in s.streamed and arms a streamWindow = 50ms timer. When the timer fires—or earlier upon any external command (cmds), non-driver.Delta event, agent exit, or Session close—flushStreamed() appends the buffered text to the in-memory item (marked unsaved, avoiding per-chunk SQLite writes), increments s.data.Rev, and emits one ItemDelta per item. Because View() always flushes first, snapshots and subsequent stream events always agree on rev.
  • Web per-task render coalescing (web/src/state/store.ts): oncePerTask() wraps the zustand store with a MessageChannel. When dozens of events arrive in a burst, React subscribers re-render at most once per event-loop task, while non-UI listeners subscribed directly to the raw store (such as the notification coordinator) still observe every update immediately.

Lazy Timeline Loading

  • Node in-memory lazy load and eviction (server/node/session/session.go): At startup, a Node loads only Session metadata rows; timelines stay in SQLite (items and index remain nil). Listing, pinning, archiving, and renaming go through look without touching disk; operations that need timeline items go through do, which calls wake(). When no agent process is attached, a Session idles for timelineIdle = 5 minutes before sleep() flushes unsaved items and frees timeline memory. When an agent process is alive but idle (State != RUNNING and no background tasks), agentIdle = 30 minutes closes the agent process and puts the timeline to sleep.
  • Client tail loading: Both web (web/src/state/sync.ts) and Android (android/app/src/main/kotlin/top/onemolchuan/code/state/Store.kt) pass lastTurns = 2 (TAIL_TURNS = 2) when first opening a Session. Session.View() truncates earlier Turns and returns earlier_turns (omitted Turn count) plus earlier_changes (aggregated file changes from omitted Turns so the web composer can display file-change totals without loading full history).
  • Expanding full history on demand: Clicking the "show earlier N turns" button at the top of the timeline—or opening timeline search (SessionView.tsx) or the context breakdown (ContextPopover.tsx) on web—fetches with lastTurns = 0. On web, if a full-history request arrives while a tail fetch is still in flight, it sets flight.upgrade = true rather than issuing a duplicate request, immediately following up with the full fetch when the tail fetch completes.
  • Filtering late events from unloaded Turns: In applyItems (web/src/state/timeline.ts and Android Timeline.kt), when earlier > 0 and an incoming item does not exist locally and has a create_time older than the first loaded item (typically a late update from an earlier Turn's subagent), the client drops it so it is never mis-inserted at the bottom of the timeline.

Two Client Implementations: Web and Android

Web and Android maintain parallel, structurally equivalent synchronizers with matching state machines and rev-merging rules. Any change to the sync protocol or resync policy must be applied to both.

Responsibility Web implementation Android implementation
Watch loop, cursor management, three-level resync, timeline fetches web/src/state/sync.ts android/app/src/main/kotlin/top/onemolchuan/code/state/Store.kt
ItemsChanged / ItemDelta rev validation, merging, newerSession check web/src/state/timeline.ts android/app/src/main/kotlin/top/onemolchuan/code/state/Timeline.kt
Global state store and derived views web/src/state/store.ts (zustand + oncePerTask) android/app/src/main/kotlin/top/onemolchuan/code/state/Store.kt (MutableStateFlow)
Multi-Entry failover and Hello racing Handled by desktop proxy in desktop-go/internal/proxy/upstream.go; browser uses a single Entry android/app/src/main/kotlin/top/onemolchuan/code/state/Failover.kt and net/Hub.kt
Unit tests web/src/state/sync.test.ts, sync.nodes.test.ts, sync.isolation.test.ts, timeline.test.ts android/app/src/test/kotlin/top/onemolchuan/code/TimelineTest.kt, FailoverTest.kt, HubContractTest.kt

Intentional platform-specific differences:

  • Web: Uses oncePerTask render coalescing, buffers in-flight updates in fetching.missed, evicts hidden timelines via showTimeline ref-counts, and consumes terminal, managed-browser tab, and review (ReviewChanged) events.
  • Android: Ignores BROWSER_TAB, BROWSER_TAB_REMOVED, and REVIEW events (Android previews via local port forwarding and does not host the streamed browser or IDE review pane). The stream is driven by the foreground ConnectionService (see Client Internals); on disconnect, Failover and raceEntries switch across Entries automatically while preserving all cursors (see Multi-Entry & Failover).

Whenever you modify proto/trizano/hub/v1/event.proto, proto/trizano/node/v1/event.proto, GetSessionView semantics, or either client's resync rules, update both sets of files above and keep their unit tests in sync.

Clone this wiki locally