Skip to content

feat(positron): slice 2D-1 — per-kind watch::Sender broadcast primitive - #1603

Closed
joelteply wants to merge 5 commits into
feat/continuum-positron-substratefrom
feat/continuum-positron-session-2d-broadcast
Closed

joelteply wants to merge 5 commits into
feat/continuum-positron-substratefrom
feat/continuum-positron-session-2d-broadcast

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

Substrate-side live-broadcast primitive for positron's snapshot-then-live contract. Broadcast holds one tokio::sync::watch::Sender<Arc<StateEnvelope>> per kind, lazy-initialized on first send.

Stacked on #1602 (slices 2B+2C). Stack: #1600 → #1601 → #1602 → #1603.

Joint workstream with Fable (@2a183194). Her design call on the airc grid: watch (not broadcast) because StateEnvelopes are complete snapshots → latest-wins coalescing IS the protocol; broadcast would buffer needless intermediates + bolt on a Lagged error path watch structurally avoids.

The send_replace load-bearing call

Broadcast::send uses watch::Sender::send_replace, NOT send. send no-ops when there are no receivers; send_replace always updates the watched value.

This matters because the substrate produces state before any session attaches, and the next attaching session MUST see the latest value, not the original watch::channel(initial) value. Pinned by send_with_no_subscribers_is_not_an_error and dropped_receivers_dont_break_subsequent_sends.

Lazy per-kind init

watch::channel(initial) requires an initial value, so we don't pre-allocate senders for kinds that may never produce state. First send() for a kind creates that kind's sender. subscribe() returns None if no envelope has ever been sent — honest per [[no-fallbacks-ever]]. Callers pair subscribe with the snapshot-then-live flow.

Doctrines pinned

  • [[no-fallbacks-ever]] — subscribe() returns None for no-state-yet kinds; the substrate is honest about "nothing to attach to yet".
  • [[shared-decode-per-persona-perspective]] — broadcasts Arc<StateEnvelope>; every attached receiver sees the same allocation.

What this slice does NOT ship (slice 2D-2)

  • Per-connection session task — owns one ClientMessage/ServerMessage stream, routes incoming variants through apply_subscribe / apply_observe / apply_command, attaches watch::Receivers per the new Subscription, forwards live frames to its outbound sink, emits CommandFailed sender-only.
  • Substrate coordinator wrapping cache + broadcast — substrate code currently pushes to BOTH (cache.store + broadcast.send); slice 2D-2 wraps the pair.
  • Per-observer budget_hz quantization — the observer side-channel that quantizes envelopes per observer's declared budget.

Test plan

  • cargo test -p continuum-positron — 42/42 green (37 lib + 5 integration)
  • cargo check -p continuum-positron — clean
  • send_replace semantics pinned by two tests
  • Per-kind independence + multi-subscriber fan-out pinned
  • CI workspace build when stack lands on canary

@joelteply

Copy link
Copy Markdown
Contributor Author

SENTINEL VERDICT: BLOCK — the watch primitive is right, but the lazy-init design has a cold-start hole that reintroduces the exact bug class this stack exists to kill.

The blocker: Broadcast::subscribe(kind) returns None for a never-stored kind, and there is no wake-up path when that kind's first state arrives. The module docs normalize it:

If both return None, the connection silently waits — … and a future resubscribe catches up via the snapshot path.

That contradicts the normative live phase in positron-core session.rs: "then stream live updates from that moment forward." A renderer that subscribes to "chat" before the substrate produces its first chat state receives nothing — not the first state, not any subsequent one — until it happens to reconnect. "UI dead until reconnect" is the #793/#794 symptom class, reintroduced for the cold-start window. The 2D-3 session task cannot be made conformant on this API without polling or an out-of-band "kind appeared" signal — neither exists.

Two clean fixes (either is fine):

  1. Option-initial: watch::channel::<Option<Arc<StateEnvelope>>>(None), create the channel on subscribe as well as on send. subscribe always returns a receiver; consumers skip None. Lazy allocation is preserved for kinds nobody asks about.
  2. subscribe_or_create / Broadcast::ensure(kind) keeping Arc<StateEnvelope> as the value, with the first send doing send_replace into the pre-created channel.

What's verified and conformant (37 unit + 5 integration green against v0.1.1):

  • send_replace, not send — correctly chosen and documented so updates in the zero-receiver window aren't dropped (send_with_no_subscribers_is_not_an_error pins it: fresh subscriber sees latest, no history replay).
  • Latest-wins coalescing IS the spec — envelopes are complete snapshots; watch over broadcast is the right call (no Lagged path, no buffered intermediates).
  • Arc<StateEnvelope> no-copy fan-out — one allocation per substrate event across all receivers.
  • Snapshot-then-live mechanics (borrow_and_update + changed), per-kind stream isolation, sender persistence across receiver drops — all test-pinned.

Close the cold-start hole and this is an approve.

@joelteply
joelteply force-pushed the feat/continuum-positron-session-2bc branch from 60372e4 to 5d21ec8 Compare June 10, 2026 23:23
@joelteply
joelteply force-pushed the feat/continuum-positron-session-2d-broadcast branch from 8f62eba to 69e10f0 Compare June 10, 2026 23:27
joelteply added a commit that referenced this pull request Jun 10, 2026
Sentinel BLOCK on #1603: a renderer that called subscribe(kind)
BEFORE the substrate had ever produced state for that kind got
None back, with no path to ever wake up when state arrived. The
session-task layer above would either crash on the None or wait
forever — exactly the kind of timing-dependent silent stall the
snapshot-then-live contract exists to prevent.

Flip the watched type from Arc<StateEnvelope> to
Option<Arc<StateEnvelope>>, and lazy-init the per-kind watch::Sender
from EITHER side:

- First send(envelope) → channel(Some(envelope)) (same as before).
- First subscribe(kind) on an unknown kind → channel(None), return
  the receiver pinned to None.
- A subsequent send transitions None → Some(env), which IS a
  watch::changed() notification — the early subscriber wakes
  exactly when state finally arrives.

Session tasks consume the stream by filtering the cold-start
placeholder:

  while rx.changed().await.is_ok() {
      if let Some(env) = rx.borrow_and_update().clone() {
          // forward Some(env) as ServerMessage::State
      }
  }

The cache + broadcast stay independent — apply_subscribe still uses
the cache for snapshot frames; broadcast handles the live edge.

New regression tests:
  - subscribe_before_any_send_yields_none_then_wakes_on_first_send
    covers the exact cold-start path.
  - cold_start_subscribers_for_different_kinds_wake_independently
    proves lazy-init per kind doesn't coalesce streams.

Existing tests updated for the Option wrapper.

Closes BLOCK on #1603.
joelteply added a commit that referenced this pull request Jun 10, 2026
… machine (task #252)

Composes the snapshot-then-live primitives into substrate-side state
that one positron client session can occupy.

Ships:

- `Substrate` — coordinator wrapping cache + broadcast. `store(env)`
  hits BOTH seams via the SAME `Arc<StateEnvelope>` allocation per
  `[[shared-decode-per-persona-perspective]]`. Substrate code that
  produces state can no longer accidentally hit one seam and not
  the other (the silent-bug class where new state shows up at
  subscribe-time but never as a live update, or vice versa).

  `SubstrateStateCache::store_arc` added to support the shared-
  allocation path — cache.store_arc(arc) instead of cache.store(env)
  then cache wrapping it in another Arc. Old cache.store stays as
  a one-line wrapper for callers that build StateEnvelope directly.

- `Connection` — one client session's substrate-recorded state:
  `subscription: Subscription` + `observers: HashMap<String,
  ObserverRegistration>`. Mutated in place as ClientMessages
  arrive. Single dispatch point: `Connection::handle(msg, substrate,
  dispatcher) -> Vec<ServerMessage>` matches the variant
  exhaustively (no [[no-fallbacks-ever]] hole) and delegates to
  the existing apply_subscribe / apply_observe / apply_command
  primitives.

- Three doctrine pins at the connection layer:
  - `resubscribe_replaces_not_merges` — the §"Subscribe is
    declarative (replace, not merge)" doctrine carried up from
    Subscription::replace to the connection's subscription field.
  - `reobserve_under_same_id_replaces_not_adds` — same doctrine
    for observers, scoped per `observer_id` so distinct observers
    coexist while same-id re-Observe replaces.
  - `command_success_emits_no_protocol_frame_in_connection_too` /
    `command_failure_emits_command_failed_at_connection_layer` —
    the §"loud failures + no success-ack" asymmetry must survive
    the wrapping. Multi-layer wrappers are exactly the surface where
    "I'll just add a success ack here for convenience" sneaks in.

What this slice does NOT ship (slice 2D-3):

- Async session task — long-running future that reads ClientMessage
  from the transport's inbound stream, drives Connection::handle,
  attaches watch::Receivers for the new Subscription's kinds, fans
  live envelopes through ServerMessage::State to the transport's
  outbound sink, and quantizes per-observer `budget_hz`.

The Connection state machine in this slice is the building block
that the async task composes. Keeping it sync + pure-mutation
makes the async loop's logic narrow (just plumbing) and lets every
state transition be unit-tested without spawning tasks.

54/54 tests green (49 lib + 5 integration). +12 new tests for
this slice (3 substrate + 9 connection).

Stacks on PR #1603 (slice 2D-1: broadcast primitive).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Jun 10, 2026
…cast shapes

Rebasing the Substrate coordinator + Connection state machine onto
the new #1602 (CommandDispatch takes whole envelope) and #1603
(Broadcast::subscribe always returns Receiver<Option<...>>) requires
two mechanical follow-throughs that this commit makes:

- connection.rs ScriptedDispatcher takes `envelope: CommandEnvelope`
  instead of `(command: String, params: Value)` and records
  `Vec<CommandEnvelope>`. The unused `Value` import goes too.
- substrate.rs tests unwrap the new Option layer at the borrow:
  `rx.borrow().clone().expect("broadcast populated")`. Direct
  Option-unwrap calls on the Receiver (`.expect()`, `.unwrap()`) no
  longer compile because subscribe() always returns a Receiver, not
  an Option<Receiver>.

No behavioral change beyond the trait/type cascade. The
provenance-preserving dispatch + cold-start-safe broadcast continue
to compose through the Connection state machine and Substrate
coordinator unchanged.
@joelteply

Copy link
Copy Markdown
Contributor Author

SENTINEL VERDICT (round 2): APPROVE — head 69e10f00d closes the cold-start hole with exactly fix shape 1 from the round-1 verdict. 39 unit + 5 integration green against positron-core v0.1.1.

Fix verified by walking the exact sequence:

  • Watched type is Option<Arc<StateEnvelope>>; lazy-init is symmetric: first send creates the channel with Some(env), first subscribe on a never-sent kind creates it with None. subscribe(kind) now ALWAYS returns a Receiver (signature change — the Option<Receiver> is gone, so the dead-until-reconnect path is unrepresentable).
  • Cold-start walk: subscribe-before-any-store → borrow_and_update() is None → changed() pends → send() does send_replace(Some(env)) on the SAME pre-created sender (both arms lock the one Mutex<HashMap>, so no subscribe/send TOCTOU race can create two senders) → changed() resolves with Some(rev 1). Pinned by subscribe_before_any_send_yields_none_then_wakes_on_first_send.
  • Per-kind independence of the cold-start wake: cold_start_subscribers_for_different_kinds_wake_independently — chat's first send wakes chat's cold subscriber; user-list's stays pending at None (timeout-asserted negative).
  • No unwrap-on-None holes: production code in the crate never borrows a receiver (session-task consumption is 2D-3); every test unwrap()/expect() on the Option follows a send that guarantees Some. The doc example for 2D-3 consumers filters None explicitly.
  • send_replace semantics, latest-wins coalescing, sender persistence across receiver drops: all unchanged from round 1 and still test-pinned. Feature commit is patch-identical to round 1; only the fix commit is new.

Risk note (non-blocking, for 2D-3): subscribe lazy-inits a map entry for ANY kind string a client names, so a hostile/buggy client subscribing to junk kinds grows the map unboundedly. Cheap to bound when connections get authenticated; flagging so it doesn't get forgotten.

joelteply and others added 3 commits June 10, 2026 18:41
…h CommandFailed asymmetry (task #252)

Substrate-side handlers for positron v0.1.1's session protocol —
the remaining ClientMessage variants now have substrate-side
counterparts.

Ships:

- `ObserverRegistration { observer_id, budget_hz, kinds, layers }`
  + `apply_observe(cache, msg) -> (ObserverRegistration,
  Vec<ServerMessage>)` — mirror of apply_subscribe for ObserverSpec.
  Same exact-equality skip rule via `session::should_skip` (made
  pub(crate) and shared with apply_observe, since positron protocol
  §"Observers resync identically" says one resync contract for
  humans AND AIs). Declarative replace per `observer_id`: re-observe
  REPLACES that observer's prior registration, no merge method
  exists. `budget_hz` is captured but not yet enforced — enforcement
  is a broadcast-time concern in slice 2D.

- `CommandDispatch` trait + `apply_command(dispatcher, msg) ->
  Vec<ServerMessage>` — bridge CommandEnvelope through continuum's
  command surface. Intentionally asymmetric per v0.1.1 protocol:
  - Success → empty Vec (state change carries the implicit ack;
    unidirectional model stands)
  - Failure → ONE ServerMessage::CommandFailed { correlation_id,
    error } targeting only the failing connection (transport-level
    per-connection routing is the session-task's job; this pure
    handler just emits the frame)

- `CommandDispatch` is a trait, not a function pointer, so the
  substrate-side seam to continuum-core's CommandExecutor stays
  typed and extensible. Tests inject ScriptedDispatcher mocks
  rather than half-implementing the real executor.

Architectural correctness:

- positron protocol §"loud failures" doctrine pinned by
  `failure_emits_command_failed_with_echoed_correlation_id` —
  silent failure is forbidden, the substrate ALWAYS emits a
  CommandFailed frame on Err with the client's echoed correlation_id.

- positron protocol §"no success-ack" pinned by
  `success_emits_no_protocol_frame` — adding a synthetic success
  frame here would create a second correlate-able event that breaks
  the unidirectional model.

- Single resync contract pinned by
  `higher_last_seen_does_NOT_skip_for_observers_either` — the
  observer skip rule MUST behave identically to the subscriber skip
  rule. A divergent observer rule would re-introduce Fable's round-2
  catch (stale-forever) on the AI-perception path.

What this slice does NOT ship (intentional follow-up, slice 2D):

- Live broadcast plumbing — Fable's design call (in airc): `watch`
  per kind, not `broadcast`. StateEnvelopes are complete snapshots
  → latest-wins coalescing IS the spec; broadcast would buffer
  needless copies + bolt on a Lagged error path watch structurally
  avoids. Slice 2D ships the per-kind `watch::Sender<Arc<
  StateEnvelope>>` fan-out + per-observer `budget_hz` quantization.

- Per-connection session task — the agent that owns one
  ClientMessage/ServerMessage stream, routes incoming variants
  through the three apply_* handlers, owns the new Subscription /
  ObserverRegistration values, and forwards CommandFailed to ONLY
  the failing connection per protocol §"Delivery scope". Slice 2D.

- Event-bridging from continuum's bus → cache.store. The
  StateBuilder seam is ready; the bus wire-up lands in slice 2E.

31/31 tests green (23 from prior slices + 4 observer + 4 dispatch).
Stacks on PR #1601 (slice 2A).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…nd-trip through the whole chain

Five integration tests in `core/continuum-positron/tests/session_roundtrip.rs` exercise the substrate → wire → consumer chain that unit tests can't catch on their own:

- `typed_payload_round_trips_through_subscribe_snapshot` — substrate builds ChatViewState → StateBuilder frames → cache stores → apply_subscribe retrieves → serde_json round-trip → renderer deserializes back as typed ChatViewState. Pins the "continuum-positron and positron-lit speak the same typed shape" contract.

- `skip_rule_works_end_to_end_on_resubscribe` — first subscribe gets snapshot, immediate resubscribe with last_seen=current gets no frame. §6 reconnect-tolerance in miniature.

- `substrate_restart_resync_works_end_to_end` — stale-renderer-vs-fresh-substrate (client@500 vs substrate@1) MUST get the snapshot, never silently skip. The load-bearing invariant Fable's round-2 review caught, now pinned end-to-end (not just at the unit-test apply_subscribe seam). The renderer also sees the current substrate truth in the snapshot payload — not just a "we sent something" guarantee.

- `two_subscribers_share_envelope_bytes_per_doctrine` — two renderers subscribing in the same tick get byte-identical snapshots. Pins `[[shared-decode-per-persona-perspective]]` — cache stores Arc, doesn't re-decode per subscriber.

- `three_kinds_independently_partitioned` — multi-kind subscribe with selective skip (one kind matched, two didn't). Pins independent per-kind partitioning.

No new substrate code; pure integration coverage. Catches the class of bug where two modules each pass their own unit tests but compose incorrectly.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ance

Sentinel BLOCK on #1602: the trait signature
`dispatch(command: String, params: Value)` decomposed CommandEnvelope
at the substrate seam, silently erasing `source` (Human vs
Observer { observer_id }) and `kind` before the dispatcher ever saw
them. The positron wire doctrine says commands are "first-class but
never anonymous" precisely so substrate-side authorization + audit
can scope authority by who and what — that line was doing real work
and the seam was breaking it.

Change `CommandDispatch::dispatch(envelope: CommandEnvelope)` to
hand the full typed value across the seam, per
[[strong-typing-across-boundaries]]. `apply_command` no longer
destructures; tests record `Vec<CommandEnvelope>` instead of
`Vec<(String, Value)>`. New regression test
`dispatcher_receives_envelope_source_and_kind_intact` builds an
Observer-sourced command and asserts both `kind` and the
`observer_id` payload round-trip through the seam — locks the
provenance contract structurally.

The cascade through Connection::handle_command + the integration
roundtrip tests lands on #1604's branch when this rebases up.

Closes BLOCK on #1602.
@joelteply
joelteply force-pushed the feat/continuum-positron-session-2bc branch from 5d21ec8 to 93784ed Compare June 10, 2026 23:42
joelteply and others added 2 commits June 10, 2026 18:44
…ve (task #252)

The substrate-side live-broadcast primitive for positron's snapshot-
then-live contract. `Broadcast` holds one
`tokio::sync::watch::Sender<Arc<StateEnvelope>>` per kind, lazy-
initialized on first send.

Per Fable's design call on the airc grid: watch (not broadcast).
StateEnvelopes are complete snapshots → latest-wins coalescing IS
the protocol; an intermediate envelope a receiver never saw is dead
weight, not data loss. broadcast would buffer N intermediates nobody
should render + bolt on a Lagged error path watch structurally
avoids.

Implementation notes:

- `send_replace` (not `send`) so the latest value persists across
  no-receivers windows. This is the load-bearing fix for the
  substrate-start-before-first-session-attach case: if substrate
  produces state before any session subscribes, the next session
  that attaches must see the latest value, not the original
  initial. `send` would silently no-op when there are no receivers,
  losing that update. `send_replace` always updates the watched
  value. Pinned by `send_with_no_subscribers_is_not_an_error` and
  `dropped_receivers_dont_break_subsequent_sends`.

- Lazy per-kind init. `watch::channel(initial)` requires an initial
  value, so we don't pre-allocate senders for kinds that may never
  produce state. First `send()` for a kind creates that kind's
  sender. `subscribe()` returns `None` if no envelope has ever been
  sent — honest `[[no-fallbacks-ever]]` answer; callers pair with
  the snapshot-then-live flow.

- Sessions / kinds are independent streams. Pinned by
  `kinds_are_independent_streams` — a send on one kind MUST NOT
  wake another kind's receivers.

What this slice does NOT ship (slice 2D-2):

- Per-connection session task — the agent that owns one
  ClientMessage/ServerMessage stream, routes incoming variants
  through apply_subscribe / apply_observe / apply_command, attaches
  watch::Receivers per the new Subscription, forwards live frames
  to its outbound sink, and emits CommandFailed sender-only.

- `Substrate` coordinator wrapping cache + broadcast. Substrate
  code that produces state pushes to BOTH today (cache.store +
  broadcast.send). Slice 2D-2 wraps the pair.

- Per-observer `budget_hz` quantization — the observer broadcast
  side-channel that quantizes envelopes per observer's declared
  budget. Slice 2D-2 wires this into the per-connection task.

6 broadcast tests cover the contract surface; 5 integration tests
from the prior commit still green. 37/37 lib + 5/5 integration =
42/42 total.

Stacks on PR #1602 (slices 2B+2C).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Sentinel BLOCK on #1603: a renderer that called subscribe(kind)
BEFORE the substrate had ever produced state for that kind got
None back, with no path to ever wake up when state arrived. The
session-task layer above would either crash on the None or wait
forever — exactly the kind of timing-dependent silent stall the
snapshot-then-live contract exists to prevent.

Flip the watched type from Arc<StateEnvelope> to
Option<Arc<StateEnvelope>>, and lazy-init the per-kind watch::Sender
from EITHER side:

- First send(envelope) → channel(Some(envelope)) (same as before).
- First subscribe(kind) on an unknown kind → channel(None), return
  the receiver pinned to None.
- A subsequent send transitions None → Some(env), which IS a
  watch::changed() notification — the early subscriber wakes
  exactly when state finally arrives.

Session tasks consume the stream by filtering the cold-start
placeholder:

  while rx.changed().await.is_ok() {
      if let Some(env) = rx.borrow_and_update().clone() {
          // forward Some(env) as ServerMessage::State
      }
  }

The cache + broadcast stay independent — apply_subscribe still uses
the cache for snapshot frames; broadcast handles the live edge.

New regression tests:
  - subscribe_before_any_send_yields_none_then_wakes_on_first_send
    covers the exact cold-start path.
  - cold_start_subscribers_for_different_kinds_wake_independently
    proves lazy-init per kind doesn't coalesce streams.

Existing tests updated for the Option wrapper.

Closes BLOCK on #1603.
@joelteply
joelteply force-pushed the feat/continuum-positron-session-2d-broadcast branch from 69e10f0 to 8767e2a Compare June 10, 2026 23:45
joelteply added a commit that referenced this pull request Jun 10, 2026
… machine (task #252)

Composes the snapshot-then-live primitives into substrate-side state
that one positron client session can occupy.

Ships:

- `Substrate` — coordinator wrapping cache + broadcast. `store(env)`
  hits BOTH seams via the SAME `Arc<StateEnvelope>` allocation per
  `[[shared-decode-per-persona-perspective]]`. Substrate code that
  produces state can no longer accidentally hit one seam and not
  the other (the silent-bug class where new state shows up at
  subscribe-time but never as a live update, or vice versa).

  `SubstrateStateCache::store_arc` added to support the shared-
  allocation path — cache.store_arc(arc) instead of cache.store(env)
  then cache wrapping it in another Arc. Old cache.store stays as
  a one-line wrapper for callers that build StateEnvelope directly.

- `Connection` — one client session's substrate-recorded state:
  `subscription: Subscription` + `observers: HashMap<String,
  ObserverRegistration>`. Mutated in place as ClientMessages
  arrive. Single dispatch point: `Connection::handle(msg, substrate,
  dispatcher) -> Vec<ServerMessage>` matches the variant
  exhaustively (no [[no-fallbacks-ever]] hole) and delegates to
  the existing apply_subscribe / apply_observe / apply_command
  primitives.

- Three doctrine pins at the connection layer:
  - `resubscribe_replaces_not_merges` — the §"Subscribe is
    declarative (replace, not merge)" doctrine carried up from
    Subscription::replace to the connection's subscription field.
  - `reobserve_under_same_id_replaces_not_adds` — same doctrine
    for observers, scoped per `observer_id` so distinct observers
    coexist while same-id re-Observe replaces.
  - `command_success_emits_no_protocol_frame_in_connection_too` /
    `command_failure_emits_command_failed_at_connection_layer` —
    the §"loud failures + no success-ack" asymmetry must survive
    the wrapping. Multi-layer wrappers are exactly the surface where
    "I'll just add a success ack here for convenience" sneaks in.

What this slice does NOT ship (slice 2D-3):

- Async session task — long-running future that reads ClientMessage
  from the transport's inbound stream, drives Connection::handle,
  attaches watch::Receivers for the new Subscription's kinds, fans
  live envelopes through ServerMessage::State to the transport's
  outbound sink, and quantizes per-observer `budget_hz`.

The Connection state machine in this slice is the building block
that the async task composes. Keeping it sync + pure-mutation
makes the async loop's logic narrow (just plumbing) and lets every
state transition be unit-tested without spawning tasks.

54/54 tests green (49 lib + 5 integration). +12 new tests for
this slice (3 substrate + 9 connection).

Stacks on PR #1603 (slice 2D-1: broadcast primitive).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Jun 10, 2026
…cast shapes

Rebasing the Substrate coordinator + Connection state machine onto
the new #1602 (CommandDispatch takes whole envelope) and #1603
(Broadcast::subscribe always returns Receiver<Option<...>>) requires
two mechanical follow-throughs that this commit makes:

- connection.rs ScriptedDispatcher takes `envelope: CommandEnvelope`
  instead of `(command: String, params: Value)` and records
  `Vec<CommandEnvelope>`. The unused `Value` import goes too.
- substrate.rs tests unwrap the new Option layer at the borrow:
  `rx.borrow().clone().expect("broadcast populated")`. Direct
  Option-unwrap calls on the Receiver (`.expect()`, `.unwrap()`) no
  longer compile because subscribe() always returns a Receiver, not
  an Option<Receiver>.

No behavioral change beyond the trait/type cascade. The
provenance-preserving dispatch + cold-start-safe broadcast continue
to compose through the Connection state machine and Substrate
coordinator unchanged.
@joelteply
joelteply deleted the branch feat/continuum-positron-substrate June 10, 2026 23:46
Base automatically changed from feat/continuum-positron-session-2bc to feat/continuum-positron-substrate June 10, 2026 23:46
@joelteply joelteply closed this Jun 10, 2026
joelteply added a commit that referenced this pull request Jun 10, 2026
Sentinel BLOCK on #1603: a renderer that called subscribe(kind)
BEFORE the substrate had ever produced state for that kind got
None back, with no path to ever wake up when state arrived. The
session-task layer above would either crash on the None or wait
forever — exactly the kind of timing-dependent silent stall the
snapshot-then-live contract exists to prevent.

Flip the watched type from Arc<StateEnvelope> to
Option<Arc<StateEnvelope>>, and lazy-init the per-kind watch::Sender
from EITHER side:

- First send(envelope) → channel(Some(envelope)) (same as before).
- First subscribe(kind) on an unknown kind → channel(None), return
  the receiver pinned to None.
- A subsequent send transitions None → Some(env), which IS a
  watch::changed() notification — the early subscriber wakes
  exactly when state finally arrives.

Session tasks consume the stream by filtering the cold-start
placeholder:

  while rx.changed().await.is_ok() {
      if let Some(env) = rx.borrow_and_update().clone() {
          // forward Some(env) as ServerMessage::State
      }
  }

The cache + broadcast stay independent — apply_subscribe still uses
the cache for snapshot frames; broadcast handles the live edge.

New regression tests:
  - subscribe_before_any_send_yields_none_then_wakes_on_first_send
    covers the exact cold-start path.
  - cold_start_subscribers_for_different_kinds_wake_independently
    proves lazy-init per kind doesn't coalesce streams.

Existing tests updated for the Option wrapper.

Closes BLOCK on #1603.
joelteply added a commit that referenced this pull request Jun 10, 2026
Sentinel BLOCK on #1603: a renderer that called subscribe(kind)
BEFORE the substrate had ever produced state for that kind got
None back, with no path to ever wake up when state arrived. The
session-task layer above would either crash on the None or wait
forever — exactly the kind of timing-dependent silent stall the
snapshot-then-live contract exists to prevent.

Flip the watched type from Arc<StateEnvelope> to
Option<Arc<StateEnvelope>>, and lazy-init the per-kind watch::Sender
from EITHER side:

- First send(envelope) → channel(Some(envelope)) (same as before).
- First subscribe(kind) on an unknown kind → channel(None), return
  the receiver pinned to None.
- A subsequent send transitions None → Some(env), which IS a
  watch::changed() notification — the early subscriber wakes
  exactly when state finally arrives.

Session tasks consume the stream by filtering the cold-start
placeholder:

  while rx.changed().await.is_ok() {
      if let Some(env) = rx.borrow_and_update().clone() {
          // forward Some(env) as ServerMessage::State
      }
  }

The cache + broadcast stay independent — apply_subscribe still uses
the cache for snapshot frames; broadcast handles the live edge.

New regression tests:
  - subscribe_before_any_send_yields_none_then_wakes_on_first_send
    covers the exact cold-start path.
  - cold_start_subscribers_for_different_kinds_wake_independently
    proves lazy-init per kind doesn't coalesce streams.

Existing tests updated for the Option wrapper.

Closes BLOCK on #1603.
joelteply added a commit that referenced this pull request Jun 10, 2026
… machine (task #252)

Composes the snapshot-then-live primitives into substrate-side state
that one positron client session can occupy.

Ships:

- `Substrate` — coordinator wrapping cache + broadcast. `store(env)`
  hits BOTH seams via the SAME `Arc<StateEnvelope>` allocation per
  `[[shared-decode-per-persona-perspective]]`. Substrate code that
  produces state can no longer accidentally hit one seam and not
  the other (the silent-bug class where new state shows up at
  subscribe-time but never as a live update, or vice versa).

  `SubstrateStateCache::store_arc` added to support the shared-
  allocation path — cache.store_arc(arc) instead of cache.store(env)
  then cache wrapping it in another Arc. Old cache.store stays as
  a one-line wrapper for callers that build StateEnvelope directly.

- `Connection` — one client session's substrate-recorded state:
  `subscription: Subscription` + `observers: HashMap<String,
  ObserverRegistration>`. Mutated in place as ClientMessages
  arrive. Single dispatch point: `Connection::handle(msg, substrate,
  dispatcher) -> Vec<ServerMessage>` matches the variant
  exhaustively (no [[no-fallbacks-ever]] hole) and delegates to
  the existing apply_subscribe / apply_observe / apply_command
  primitives.

- Three doctrine pins at the connection layer:
  - `resubscribe_replaces_not_merges` — the §"Subscribe is
    declarative (replace, not merge)" doctrine carried up from
    Subscription::replace to the connection's subscription field.
  - `reobserve_under_same_id_replaces_not_adds` — same doctrine
    for observers, scoped per `observer_id` so distinct observers
    coexist while same-id re-Observe replaces.
  - `command_success_emits_no_protocol_frame_in_connection_too` /
    `command_failure_emits_command_failed_at_connection_layer` —
    the §"loud failures + no success-ack" asymmetry must survive
    the wrapping. Multi-layer wrappers are exactly the surface where
    "I'll just add a success ack here for convenience" sneaks in.

What this slice does NOT ship (slice 2D-3):

- Async session task — long-running future that reads ClientMessage
  from the transport's inbound stream, drives Connection::handle,
  attaches watch::Receivers for the new Subscription's kinds, fans
  live envelopes through ServerMessage::State to the transport's
  outbound sink, and quantizes per-observer `budget_hz`.

The Connection state machine in this slice is the building block
that the async task composes. Keeping it sync + pure-mutation
makes the async loop's logic narrow (just plumbing) and lets every
state transition be unit-tested without spawning tasks.

54/54 tests green (49 lib + 5 integration). +12 new tests for
this slice (3 substrate + 9 connection).

Stacks on PR #1603 (slice 2D-1: broadcast primitive).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Jun 10, 2026
…cast shapes

Rebasing the Substrate coordinator + Connection state machine onto
the new #1602 (CommandDispatch takes whole envelope) and #1603
(Broadcast::subscribe always returns Receiver<Option<...>>) requires
two mechanical follow-throughs that this commit makes:

- connection.rs ScriptedDispatcher takes `envelope: CommandEnvelope`
  instead of `(command: String, params: Value)` and records
  `Vec<CommandEnvelope>`. The unused `Value` import goes too.
- substrate.rs tests unwrap the new Option layer at the borrow:
  `rx.borrow().clone().expect("broadcast populated")`. Direct
  Option-unwrap calls on the Receiver (`.expect()`, `.unwrap()`) no
  longer compile because subscribe() always returns a Receiver, not
  an Option<Receiver>.

No behavioral change beyond the trait/type cascade. The
provenance-preserving dispatch + cold-start-safe broadcast continue
to compose through the Connection state machine and Substrate
coordinator unchanged.
joelteply added a commit that referenced this pull request Jun 10, 2026
… machine (#1604)

* feat(positron): slice 2D-1 — per-kind watch::Sender broadcast primitive (task #252)

The substrate-side live-broadcast primitive for positron's snapshot-
then-live contract. `Broadcast` holds one
`tokio::sync::watch::Sender<Arc<StateEnvelope>>` per kind, lazy-
initialized on first send.

Per Fable's design call on the airc grid: watch (not broadcast).
StateEnvelopes are complete snapshots → latest-wins coalescing IS
the protocol; an intermediate envelope a receiver never saw is dead
weight, not data loss. broadcast would buffer N intermediates nobody
should render + bolt on a Lagged error path watch structurally
avoids.

Implementation notes:

- `send_replace` (not `send`) so the latest value persists across
  no-receivers windows. This is the load-bearing fix for the
  substrate-start-before-first-session-attach case: if substrate
  produces state before any session subscribes, the next session
  that attaches must see the latest value, not the original
  initial. `send` would silently no-op when there are no receivers,
  losing that update. `send_replace` always updates the watched
  value. Pinned by `send_with_no_subscribers_is_not_an_error` and
  `dropped_receivers_dont_break_subsequent_sends`.

- Lazy per-kind init. `watch::channel(initial)` requires an initial
  value, so we don't pre-allocate senders for kinds that may never
  produce state. First `send()` for a kind creates that kind's
  sender. `subscribe()` returns `None` if no envelope has ever been
  sent — honest `[[no-fallbacks-ever]]` answer; callers pair with
  the snapshot-then-live flow.

- Sessions / kinds are independent streams. Pinned by
  `kinds_are_independent_streams` — a send on one kind MUST NOT
  wake another kind's receivers.

What this slice does NOT ship (slice 2D-2):

- Per-connection session task — the agent that owns one
  ClientMessage/ServerMessage stream, routes incoming variants
  through apply_subscribe / apply_observe / apply_command, attaches
  watch::Receivers per the new Subscription, forwards live frames
  to its outbound sink, and emits CommandFailed sender-only.

- `Substrate` coordinator wrapping cache + broadcast. Substrate
  code that produces state pushes to BOTH today (cache.store +
  broadcast.send). Slice 2D-2 wraps the pair.

- Per-observer `budget_hz` quantization — the observer broadcast
  side-channel that quantizes envelopes per observer's declared
  budget. Slice 2D-2 wires this into the per-connection task.

6 broadcast tests cover the contract surface; 5 integration tests
from the prior commit still green. 37/37 lib + 5/5 integration =
42/42 total.

Stacks on PR #1602 (slices 2B+2C).

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* fix(positron): Broadcast cold-start hole — lazy-init from subscribe()

Sentinel BLOCK on #1603: a renderer that called subscribe(kind)
BEFORE the substrate had ever produced state for that kind got
None back, with no path to ever wake up when state arrived. The
session-task layer above would either crash on the None or wait
forever — exactly the kind of timing-dependent silent stall the
snapshot-then-live contract exists to prevent.

Flip the watched type from Arc<StateEnvelope> to
Option<Arc<StateEnvelope>>, and lazy-init the per-kind watch::Sender
from EITHER side:

- First send(envelope) → channel(Some(envelope)) (same as before).
- First subscribe(kind) on an unknown kind → channel(None), return
  the receiver pinned to None.
- A subsequent send transitions None → Some(env), which IS a
  watch::changed() notification — the early subscriber wakes
  exactly when state finally arrives.

Session tasks consume the stream by filtering the cold-start
placeholder:

  while rx.changed().await.is_ok() {
      if let Some(env) = rx.borrow_and_update().clone() {
          // forward Some(env) as ServerMessage::State
      }
  }

The cache + broadcast stay independent — apply_subscribe still uses
the cache for snapshot frames; broadcast handles the live edge.

New regression tests:
  - subscribe_before_any_send_yields_none_then_wakes_on_first_send
    covers the exact cold-start path.
  - cold_start_subscribers_for_different_kinds_wake_independently
    proves lazy-init per kind doesn't coalesce streams.

Existing tests updated for the Option wrapper.

Closes BLOCK on #1603.

* feat(positron): slice 2D-2 — Substrate coordinator + Connection state machine (task #252)

Composes the snapshot-then-live primitives into substrate-side state
that one positron client session can occupy.

Ships:

- `Substrate` — coordinator wrapping cache + broadcast. `store(env)`
  hits BOTH seams via the SAME `Arc<StateEnvelope>` allocation per
  `[[shared-decode-per-persona-perspective]]`. Substrate code that
  produces state can no longer accidentally hit one seam and not
  the other (the silent-bug class where new state shows up at
  subscribe-time but never as a live update, or vice versa).

  `SubstrateStateCache::store_arc` added to support the shared-
  allocation path — cache.store_arc(arc) instead of cache.store(env)
  then cache wrapping it in another Arc. Old cache.store stays as
  a one-line wrapper for callers that build StateEnvelope directly.

- `Connection` — one client session's substrate-recorded state:
  `subscription: Subscription` + `observers: HashMap<String,
  ObserverRegistration>`. Mutated in place as ClientMessages
  arrive. Single dispatch point: `Connection::handle(msg, substrate,
  dispatcher) -> Vec<ServerMessage>` matches the variant
  exhaustively (no [[no-fallbacks-ever]] hole) and delegates to
  the existing apply_subscribe / apply_observe / apply_command
  primitives.

- Three doctrine pins at the connection layer:
  - `resubscribe_replaces_not_merges` — the §"Subscribe is
    declarative (replace, not merge)" doctrine carried up from
    Subscription::replace to the connection's subscription field.
  - `reobserve_under_same_id_replaces_not_adds` — same doctrine
    for observers, scoped per `observer_id` so distinct observers
    coexist while same-id re-Observe replaces.
  - `command_success_emits_no_protocol_frame_in_connection_too` /
    `command_failure_emits_command_failed_at_connection_layer` —
    the §"loud failures + no success-ack" asymmetry must survive
    the wrapping. Multi-layer wrappers are exactly the surface where
    "I'll just add a success ack here for convenience" sneaks in.

What this slice does NOT ship (slice 2D-3):

- Async session task — long-running future that reads ClientMessage
  from the transport's inbound stream, drives Connection::handle,
  attaches watch::Receivers for the new Subscription's kinds, fans
  live envelopes through ServerMessage::State to the transport's
  outbound sink, and quantizes per-observer `budget_hz`.

The Connection state machine in this slice is the building block
that the async task composes. Keeping it sync + pure-mutation
makes the async loop's logic narrow (just plumbing) and lets every
state transition be unit-tested without spawning tasks.

54/54 tests green (49 lib + 5 integration). +12 new tests for
this slice (3 substrate + 9 connection).

Stacks on PR #1603 (slice 2D-1: broadcast primitive).

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* fix(positron): cascade Substrate + Connection to new dispatch + broadcast shapes

Rebasing the Substrate coordinator + Connection state machine onto
the new #1602 (CommandDispatch takes whole envelope) and #1603
(Broadcast::subscribe always returns Receiver<Option<...>>) requires
two mechanical follow-throughs that this commit makes:

- connection.rs ScriptedDispatcher takes `envelope: CommandEnvelope`
  instead of `(command: String, params: Value)` and records
  `Vec<CommandEnvelope>`. The unused `Value` import goes too.
- substrate.rs tests unwrap the new Option layer at the borrow:
  `rx.borrow().clone().expect("broadcast populated")`. Direct
  Option-unwrap calls on the Receiver (`.expect()`, `.unwrap()`) no
  longer compile because subscribe() always returns a Receiver, not
  an Option<Receiver>.

No behavioral change beyond the trait/type cascade. The
provenance-preserving dispatch + cold-start-safe broadcast continue
to compose through the Connection state machine and Substrate
coordinator unchanged.

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant