~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/stream

jetstream v2 in zig · mirror of https://tangled.org/zat.dev/stream

0
0
204 lines · 11.5 KB Raw History
# Upstream failover investigation

Investigated 2026-11-05 against Stream c5674ea, Zat v0.6.3, Jetstream
289b032, and its Atmos v0.3.6 dependency. This is research, not an implemented
or admitted behavior change. Production configuration was not changed.

## Decision

Do not configure east, west, and bsky.network as interchangeable hosts.
Live replay demonstrates different events at the same sequence on east and
west. No equivalent alternate for the currently configured east endpoint was
established. Automatic rotation using Zat's existing shared cursor would be
unsafe for these endpoints.

Health-based failover remains useful for explicitly configured endpoints of
one logical stream. Independent-relay redundancy requires a separate design
for merging events, ordering, and recovery; a list of host-specific cursors
is not sufficient.

## Prior work and implementation boundaries

- Stream 952857e (August 16) records a manual bsky.network-to-east cutover.
  It called the switch gapless because requesting cursor 32793755551 returned
  that sequence. That observation does not establish event identity or shared
  sequencing. Today's counterexample invalidates the proof technique, not a
  claim that we have reconstructed what those hosts served in August.
- Stream 785d00c (October 1) adds slow-connection reconnection to the same host.
- Zat e6cadb0 (February 25) adds host rotation to firehose and Jetstream clients.
  In v0.6.3, `src/internal/streaming/firehose.zig:784` rotates on reconnect;
  `:858` sends its one `last_seq` to the next host; `:969` advances that value
  after raw-frame handler acceptance. There is no equivalence check there.
  Host changes also reset backoff, which needs reconsideration for a pool
  whose members are all unhealthy.
- Jetstream `internal/ingest/live/consumer.go:421` constructs Atmos with one
  URL and a loaded cursor. Atmos v0.3.6 `streaming/client.go` exposes one URL
  in Options and reconnects it. Equivalent-endpoint failover would be a
  deliberate Stream divergence, not an upstream behavior we forgot to port.
- Stream `src/internal/ingest/ingest.zig:145` passes a singleton host list.
  `src/internal/ingest/cursor.zig:7` stores one `relay/cursor`, with no source
  identity. `ingest.zig:565` and `:584` tie cursor persistence to archive
  durability. The transport's accepted cursor and the durable cursor are
  different boundaries; neither can be casually substituted for the other.
- `src/main.zig:964` and `:1029` also use `relay_http` for retry/repair.
  Switching WebSocket transport does not automatically fail over these APIs.

## Bounded live observations

All subscriptions ran on the existing relay-eval server, not the workstation
or Stream's production consumer. Used installed atmoq v0.1.1, a five-second
process timeout, a two-second idle limit, and 128-event limits. Raw CBOR
frames were captured; decoded bodies and raw bytes were compared locally.
This is a sample-based equivalence investigation, not a completeness or uptime
test. No production service was restarted.

At approximately 06:29 UTC, requested east-derived cursor **35212335733**:

| Endpoint | Returned sequences | Comparison |
| --- | --- | --- |
| relay1.us-east.bsky.network | 35212335733–35212335860 | 128 events |
| bsky.network | 35212335733–35212335860 | All 128 decoded events differ from east |
| relay1.us-west.bsky.network | 35212335733–35212335860 | All 128 raw frames identical to bsky.network |

At the first sequence, east returned repository
`did:plc:nwsfa65spkzrtbn4ak4ous3i`, revision `3mzkain5kes27`, time
`2026-11-05T06:29:12.964Z`. Front/west returned repository
`did:plc:u2lr73yy6tb6wc5sjzn4pgr7`, revision `3mzk6xgwjh72n`, time
`2026-11-05T06:01:42.266Z`. Commit CIDs and record operations also differ:
this is not merely different CBOR encoding or relay timestamps.
Repeating the same 128-event request against east returned an identical capture,
providing a same-host replay positive control.

At approximately 06:30 UTC, requested west-derived cursor **35212871815**:

| Endpoint | Returned sequences | Comparison |
| --- | --- | --- |
| relay1.us-east.bsky.network | 35212359546–35212359673 | Did not resume at requested position |
| bsky.network | 35212871815–35212871942 | 128 events |
| relay1.us-west.bsky.network | 35212871815–35212871942 | All 128 raw frames identical to bsky.network |

The east invocation log includes the requested cursor in its WebSocket URL.
Whether the server or the probe client causes the observed lower-position
fallback is not established; do not infer a wire-error contract from this.

Zat's other v0.6.3 default hosts were also probed with east cursor 35212335733:
northamerica.firehose.network began at 10604301658, europe.firehose.network at
10006459743, and asia.firehose.network at 8565195152. Each returned 128 events;
none established replay compatibility with east. No broader reliability claim
is made about these services.

Raw captures and invocation logs remain on the relay-eval server under
`/tmp/stream-relay-equivalence`; the initial east anchor is
`/tmp/stream-relay-anchor.jsonl`. These temporary artifacts are not permanent
receipts. To reproduce a bounded capture from a cloud host:

```sh
timeout 5s atmoq firehose \
  --relay-host wss://relay1.us-east.bsky.network \
  --cursor 35212335733 --limit 128 --idle-ms 2000 --raw
```

Old positions eventually expire: obtain fresh anchors for future comparisons.
Compare decoded event identity/content as well as sequence; accepting the
requested integer proves nothing about its meaning. A fresh same-host capture
and replay is the positive control.

## Proposed scope and admission requirements

An initial implementation should support only explicit equivalent-stream
endpoint groups, defaulting to today's single host. Stay on a healthy host;
switch on bounded failure criteria, with cooldown and bounded retries. Do
not force periodic switching or automatic failback without a demonstrated
benefit. Shared fan-out infrastructure may still have a common upstream
failure domain.

Before implementing that policy:

1. Establish an operator-supported equivalence contract and candidate for east,
   or explicitly propose a migration to a different logical stream. The two
   matching front/west windows are evidence of current shared content, not a
   durable guarantee or a reason to migrate production.
2. Define source identity/epoch and checkpoint migration. Hostnames and equal
   sequence numbers are not stream identities. An unknown or changed source
   must not inherit a persisted cursor silently.
3. Design a bounded overlap check using event fingerprints before admitting
   a candidate's events. Persist any restart-critical anchors with the cursor's
   durability boundary. Matching finite history is a guard against accidental
   misconfiguration, not proof that future contents cannot diverge.
4. Specify the transition with in-flight per-DID work, accepted and durable
   cursors, identity/account ratchets, archive ordering, and repairs. Replaying
   a durable checkpoint into a still-running pipeline can duplicate work;
   discarding accepted but undurable work can lose it. Prove the chosen drain
   or replay protocol instead of relying on commit deduplication alone.
5. Define fail-closed outcomes for missing overlap, contradictory content,
   expired retention, future cursor, backward sequence, and source resets.
   Never silently drop the cursor and jump to live tip to regain a green
   health signal. Protocol sequences may legitimately have gaps.

The minimum test matrix uses real loopback WebSocket peers, generated signed
events, the production ingest pipeline, RocksDB, archive reads and process
restarts. Extend existing abrupt-disconnect, slow-upstream, durability and
oracle fixtures rather than inventing a parallel ingestion implementation:

- Equivalent endpoints: abrupt disconnect, silence, trickle, failed handshake,
  lagging backup, bounded recovery, and no missing or extra archive events.
- Non-equivalent endpoints with the same numeric cursor: reject before their
  events reach verification/archive state. Include matching initial overlap
  followed by contradictory content to specify the guard's limits.
- Future/expired cursors, reset sequences, valid sequence gaps, duplicate
  frames, malformed control frames, and retention loss during an outage.
- In-flight work across multiple DIDs, identity/account events, pending repairs,
  slow storage, allocation failure, and fatal storage errors. Local fatal
  failures must not become endless relay rotation.
- Process kills around every checkpoint/source transition: reopen and compare
  archive contents and durable metadata against uninterrupted execution.
- All endpoints down: bounded connection attempts, memory and file descriptors;
  cancellation during dial/read/backoff; no reconnect storm or failback flapping.
- Configuration defaults/migration, active-source and rejection metrics, and
  unchanged single-host behavior against pinned upstream.

Before main: document the deliberate divergence, pass required fmt/build/tests
and relevant real-process contracts, run the full admission gate for the exact
candidate, and collect a bounded cloud soak with repeated forced endpoint
failures. A sampled public probe cannot replace this gate. Keep changes on a
feature branch until those receipts exist. Rollout and rollback must preserve
checkpoint/source compatibility and use the documented admission/deploy path.

## Prepared standby model

Parked discussion; no implementation selected. Separate deciding to switch
from preparing a replacement:

- **Detection:** react to connection health, event freshness, and disagreement
  between sources. Rate alone cannot distinguish a quiet network from missing
  traffic; neither source is automatically ground truth.
- **Preparation:** keep a second subscription with its own cursor and bounded
  overlap history. Starting it on an early warning saves resources, but cannot
  cover failures without warning. Continuous preparation costs bandwidth and
  processing even when no switch occurs.
- **Readiness:** being at both live tips is insufficient. One relay may be ahead
  for one account and behind for another. Establish how the standby's events
  connect to already processed account histories; do not compare relay cursors
  as a measure of distance or assume a fixed overlap guarantees completeness.
- **Handover:** reconcile overlap, suppress already processed events, and admit
  new events while preserving per-account ordering. Define treatment of missing
  history, identity/account events, and restart recovery before choosing policy
  thresholds. Restoring current repository state is not the same as recovering
  every historical event.

The open design question is what evidence makes a standby ready, and what
delivery guarantees remain possible when sources disagree or overlap expires.
Health policy can be heuristic; its uncertainty must not silently weaken the
handover contract. Resume here if independent-relay redundancy becomes a
priority; the evidence and admission requirements above still apply.

## Protocol references

- [AT Protocol sync](https://atproto.com/specs/sync): relay instances generally
  have distinct sequence offsets and ordering; per-repository revisions are
  distinct from stream cursors.
- [Event streams](https://atproto.com/specs/event-stream): cursor scope and
  replay/retention semantics; sequence gaps are permitted.
- [Bluesky operational update](https://github.com/bluesky-social/atproto/discussions/3036):
  Rainbow fan-outs preserve their upstream relay's sequence, whereas independent
  relay migrations require overlap and may process events twice.