Skip to main content

artifactize_core/
changes.rs

1//! Best-effort, state-scoped invalidation hints. SQLite and session files remain authoritative.
2//! The first subscriber temporarily hosts a hub; there is no daemon and writers never elect one.
3mod probe;
4#[cfg(test)]
5pub(crate) mod test_support;
6#[cfg(test)]
7mod tests;
8mod transport;
9
10use crate::types::{RequestId, RunId, SessionId};
11use serde::{Deserialize, Serialize};
12use std::{
13    collections::{BTreeMap, BTreeSet},
14    path::Path,
15    sync::{Arc, Mutex, OnceLock, Weak},
16    time::Duration,
17};
18use tokio::{
19    io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
20    sync::{Notify, broadcast, oneshot},
21    task::JoinSet,
22};
23use tokio_util::sync::CancellationToken;
24use transport::Endpoint;
25
26/// Reconcile missed commits and database replacement without reloading idle snapshots.
27pub const RECONCILE: Duration = Duration::from_secs(5);
28/// A dead hub is replaced promptly, without a spin loop or a permanent process.
29const RECONNECT: Duration = Duration::from_millis(500);
30/// Bound startup and short-command shutdown; notification availability cannot block correctness.
31const DELIVERY_TIMEOUT: Duration = Duration::from_millis(300);
32/// Bound hostile frames before allocation (IDs are at most 200 bytes).
33const MAX_FRAME_BYTES: usize = 1024;
34/// Share a small number of long-lived per-state publisher tasks; a writer can always
35/// commit without notifications when those are full.
36const MAX_STATES: usize = 32;
37/// Cap per-hub handles and tasks so abandoned or idle clients cannot exhaust them.
38const MAX_CLIENTS: usize = 64;
39/// Absorb a burst of commits without unbounded buffering for a stalled subscriber.
40const MAX_BACKLOG: usize = 64;
41/// Above this many dirty transcripts and drafts, one resync is cheaper than tracking every hint.
42const MAX_DIRTY_TRANSCRIPTS: usize = 64;
43/// Above this many dirty Runs, reread the state rather than holding an unbounded set.
44const MAX_DIRTY_RUNS: usize = 64;
45/// Version 2 names the Run a write changed ([`Change::RunInvalidated`]). The wire format is
46/// independent of the state database schema and durable session-event format. The Hello
47/// handshake rejects any unsupported version instead of interpreting incompatible hints; a
48/// reader that cannot connect reconciles every [`RECONCILE`] instead.
49const VERSION: u32 = 2;
50
51/// Hints carry no records, credentials, scheduler decisions or remote-store events.
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53pub enum Change {
54    /// The list of Runs changed: a Run was created or removed, or a write could not be tied to
55    /// a Run. Any Run may have changed with it.
56    StateInvalidated,
57    /// That Run's records changed: its state, a request, or an execution one of its requests
58    /// holds.
59    RunInvalidated(RunId),
60    SessionInvalidated(SessionId),
61    DraftInvalidated(RequestId),
62    /// Initial registration, reconnect, gap, overflow or database replacement: read afresh.
63    Resync,
64}
65
66/// What the hints since a reader's last read say it must read again: nothing, these Runs, or
67/// everything. Session hints are not about the state database and change nothing here.
68#[derive(Debug, Clone, Default, PartialEq, Eq)]
69pub enum Changed {
70    #[default]
71    Nothing,
72    Runs(BTreeSet<RunId>),
73    Everything,
74}
75impl Changed {
76    pub fn add(&mut self, change: &Change) {
77        match change {
78            Change::StateInvalidated | Change::Resync => *self = Self::Everything,
79            Change::RunInvalidated(id) if !matches!(self, Self::Everything) => {
80                self.add_run(id.clone());
81            }
82            Change::RunInvalidated(_) => {}
83            Change::SessionInvalidated(_) | Change::DraftInvalidated(_) => {}
84        }
85    }
86    fn add_run(&mut self, id: RunId) {
87        match self {
88            Self::Nothing => *self = Self::Runs(BTreeSet::from([id])),
89            Self::Runs(ids) => {
90                ids.insert(id);
91                if ids.len() > MAX_DIRTY_RUNS {
92                    *self = Self::Everything;
93                }
94            }
95            Self::Everything => {}
96        }
97    }
98    fn pop(&mut self) -> Option<Change> {
99        match self {
100            Self::Nothing => None,
101            Self::Runs(ids) => {
102                let change = ids.pop_first().map(Change::RunInvalidated);
103                if ids.is_empty() {
104                    *self = Self::Nothing;
105                }
106                change
107            }
108            Self::Everything => {
109                *self = Self::Nothing;
110                Some(Change::StateInvalidated)
111            }
112        }
113    }
114    /// Keep what `other` says changed as well, as when a read that took it was not used.
115    pub fn merge(&mut self, other: Self) {
116        match other {
117            Self::Nothing => {}
118            Self::Everything => *self = Self::Everything,
119            Self::Runs(ids) => {
120                for id in ids {
121                    self.add_run(id);
122                }
123            }
124        }
125    }
126    /// What a read reads again: what the hints named or, when the database was `written` and
127    /// no hint named the change yet (a writer that could not reach the hub), everything.
128    pub fn or_written(&self, written: bool) -> Self {
129        match self {
130            Self::Nothing if written => Self::Everything,
131            changed => changed.clone(),
132        }
133    }
134    /// Whether Run `id` may have changed.
135    pub fn run(&self, id: &RunId) -> bool {
136        match self {
137            Self::Nothing => false,
138            Self::Runs(ids) => ids.contains(id),
139            Self::Everything => true,
140        }
141    }
142}
143
144/// Changes not yet delivered: a resync replaces everything else pending, and a state change
145/// replaces pending Run changes.
146enum Dirty {
147    Pending {
148        state: Changed,
149        sessions: BTreeSet<SessionId>,
150        drafts: BTreeSet<RequestId>,
151    },
152    Resync,
153}
154impl Default for Dirty {
155    fn default() -> Self {
156        Self::Pending {
157            state: Changed::Nothing,
158            sessions: BTreeSet::new(),
159            drafts: BTreeSet::new(),
160        }
161    }
162}
163impl Dirty {
164    fn add(&mut self, change: Change) {
165        let Self::Pending {
166            state,
167            sessions,
168            drafts,
169        } = self
170        else {
171            return;
172        };
173        match change {
174            Change::Resync => {
175                *self = Self::Resync;
176                return;
177            }
178            Change::StateInvalidated => *state = Changed::Everything,
179            Change::RunInvalidated(id) => state.add_run(id),
180            Change::SessionInvalidated(id) => {
181                sessions.insert(id);
182            }
183            Change::DraftInvalidated(id) => {
184                drafts.insert(id);
185            }
186        }
187        if sessions.len() + drafts.len() > MAX_DIRTY_TRANSCRIPTS {
188            *self = Self::Resync;
189        }
190    }
191    fn pop(&mut self) -> Option<Change> {
192        match self {
193            Self::Resync => {
194                *self = Self::default();
195                Some(Change::Resync)
196            }
197            Self::Pending {
198                state,
199                sessions,
200                drafts,
201            } => state
202                .pop()
203                .or_else(|| sessions.pop_first().map(Change::SessionInvalidated))
204                .or_else(|| drafts.pop_first().map(Change::DraftInvalidated)),
205        }
206    }
207    fn is_empty(&self) -> bool {
208        matches!(self, Self::Pending { state: Changed::Nothing, sessions, drafts } if sessions.is_empty() && drafts.is_empty())
209    }
210}
211struct Inbox {
212    #[cfg(test)]
213    registration: tokio::sync::watch::Sender<Option<crate::config::HubEpoch>>,
214    // A test can wait for received hints rather than confusing the hub's ACK with delivery.
215    #[cfg(test)]
216    received: tokio::sync::watch::Sender<Option<u64>>,
217    dirty: Mutex<Dirty>,
218    wake: Notify,
219}
220impl Default for Inbox {
221    fn default() -> Self {
222        Self {
223            #[cfg(test)]
224            registration: tokio::sync::watch::channel(None).0,
225            #[cfg(test)]
226            received: tokio::sync::watch::channel(None).0,
227            dirty: Mutex::default(),
228            wake: Notify::new(),
229        }
230    }
231}
232impl Inbox {
233    fn add(&self, change: Change) {
234        self.dirty.lock().unwrap().add(change);
235        self.wake.notify_one();
236    }
237    async fn next(&self) -> Change {
238        loop {
239            // Register before checking: a hint arriving between check and await is retained.
240            let wake = self.wake.notified();
241            if let Some(change) = self.dirty.lock().unwrap().pop() {
242                return change;
243            }
244            wake.await;
245        }
246    }
247}
248
249/// The OS directory outside `state` where its subscriptions meet. Every process using that
250/// state shares it, so only the owner of a temporary state removes it with the state.
251pub fn namespace(state: &Path) -> std::io::Result<std::path::PathBuf> {
252    Endpoint::new(state).map(|endpoint| endpoint.directory().to_owned())
253}
254
255/// Register before reading the baseline. Dirties arriving during that read stay queued.
256/// Drop requests cancellation; await [`Self::close`] before removing the subscribed state.
257pub struct Subscription {
258    inbox: Arc<Inbox>,
259    cancel: CancellationToken,
260    task: tokio::task::JoinHandle<Result<(), String>>,
261}
262impl Subscription {
263    pub async fn new(state: &Path) -> Self {
264        let mut interval =
265            tokio::time::interval_at(tokio::time::Instant::now() + RECONCILE, RECONCILE);
266        interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
267        Self::with_reconciliation(state, Reconciliation::Interval(interval)).await
268    }
269
270    async fn with_reconciliation(state: &Path, reconciliation: Reconciliation) -> Self {
271        let inbox = Arc::new(Inbox::default());
272        let cancel = CancellationToken::new();
273        let (ready, registered) = oneshot::channel();
274        let state = state.to_path_buf();
275        let task = tokio::spawn(watch(
276            state,
277            inbox.clone(),
278            cancel.clone(),
279            ready,
280            reconciliation,
281        ));
282        // Keep cancellation ownership even if the caller abandons registration midway.
283        let subscription = Self {
284            inbox,
285            cancel,
286            task,
287        };
288        // An unavailable or unsafe endpoint degrades, never prevents a baseline read.
289        let _ = registered.await;
290        subscription
291    }
292    /// Stop this subscription and wait for its connection, hub and probe database to close.
293    /// Other subscriptions remain independent. Dropping this future still requests cancellation.
294    pub async fn close(mut self) -> Result<(), String> {
295        self.cancel.cancel();
296        crate::task::joined((&mut self.task).await).map_err(|error| error.to_string())?
297    }
298    /// Process-owner death has no database writer; reuse the subscription's reconciliation
299    /// cadence when an observer also owns liveness reconciliation.
300    pub async fn next_reconciled(&mut self) -> Change {
301        tokio::time::timeout(RECONCILE, self.next_state())
302            .await
303            .unwrap_or(Change::Resync)
304    }
305    pub async fn next(&mut self) -> Change {
306        self.inbox.next().await
307    }
308    /// Schedulers and non-session UIs can ignore session-only hints without reloading state.
309    /// A Run's hint is returned: the caller reads that Run again, or the state.
310    pub async fn next_state(&mut self) -> Change {
311        loop {
312            let change = self.next().await;
313            if !matches!(change, Change::SessionInvalidated(_)) {
314                return change;
315            }
316        }
317    }
318}
319impl Drop for Subscription {
320    fn drop(&mut self) {
321        self.cancel.cancel();
322    }
323}
324
325#[derive(Default)]
326struct Outbox {
327    dirty: Dirty,
328    submitted: u64,
329    delivered: u64,
330}
331struct Publishing {
332    endpoint: Endpoint,
333    pending: Mutex<Outbox>,
334    wake: Notify,
335    drained: Notify,
336    // Fixture barriers must distinguish an actual hub ACK from best-effort timeout.
337    #[cfg(test)]
338    delivery_error: Mutex<Option<String>>,
339}
340/// Cloneable synchronous producer, also safe to invoke on the SQLite worker thread.
341#[derive(Clone, Default)]
342pub(crate) struct Publisher(Option<Arc<Publishing>>);
343static PUBLISHERS: OnceLock<Mutex<BTreeMap<crate::config::EndpointId, Weak<Publishing>>>> =
344    OnceLock::new();
345impl Publisher {
346    pub(crate) fn new(state: &Path) -> Self {
347        let Ok(runtime) = tokio::runtime::Handle::try_current() else {
348            return Self::default();
349        };
350        let Ok(endpoint) = Endpoint::new(state) else {
351            return Self::default();
352        };
353        let mut publishers = PUBLISHERS.get_or_init(Default::default).lock().unwrap();
354        publishers.retain(|_, publisher| publisher.strong_count() != 0);
355        if let Some(publisher) = publishers.get(&endpoint.identity).and_then(Weak::upgrade) {
356            return Self(Some(publisher));
357        }
358        if publishers.len() >= MAX_STATES {
359            return Self::default();
360        }
361        let publisher = Arc::new(Publishing {
362            endpoint,
363            pending: Mutex::new(Outbox::default()),
364            wake: Notify::new(),
365            drained: Notify::new(),
366            #[cfg(test)]
367            delivery_error: Mutex::default(),
368        });
369        publishers.insert(
370            publisher.endpoint.identity.clone(),
371            Arc::downgrade(&publisher),
372        );
373        runtime.spawn(publish(publisher.clone()));
374        Self(Some(publisher))
375    }
376    pub(crate) fn notify(&self, change: Change) {
377        if let Some(publisher) = &self.0 {
378            let mut pending = publisher.pending.lock().unwrap();
379            pending.dirty.add(change);
380            pending.submitted = pending.submitted.wrapping_add(1);
381            drop(pending);
382            publisher.wake.notify_one();
383        }
384    }
385}
386
387/// Drain short-lived commands centrally. Only bounded hints are sent; a failed delivery is safe.
388pub async fn drain() {
389    let publishers: Vec<_> = PUBLISHERS
390        .get()
391        .map(|publishers| {
392            publishers
393                .lock()
394                .unwrap()
395                .values()
396                .filter_map(Weak::upgrade)
397                .collect()
398        })
399        .unwrap_or_default();
400    let wait = async {
401        for publisher in publishers {
402            let target = publisher.pending.lock().unwrap().submitted;
403            loop {
404                let drained = publisher.drained.notified();
405                if publisher.pending.lock().unwrap().delivered >= target {
406                    break;
407                }
408                drained.await;
409            }
410        }
411    };
412    let _ = tokio::time::timeout(DELIVERY_TIMEOUT, wait).await;
413}
414
415#[derive(Serialize, Deserialize)]
416enum Frame {
417    Hello {
418        version: u32,
419        identity: crate::config::EndpointId,
420        subscriber: bool,
421    },
422    Registered {
423        epoch: crate::config::HubEpoch,
424    },
425    Publish(Change),
426    Delivered,
427    Hint {
428        epoch: crate::config::HubEpoch,
429        sequence: u64,
430        change: Change,
431    },
432}
433async fn read_frame<R: AsyncRead + Unpin>(reader: &mut R) -> std::io::Result<Frame> {
434    let bytes = reader.read_u32().await? as usize;
435    if bytes == 0 || bytes > MAX_FRAME_BYTES {
436        return Err(std::io::ErrorKind::InvalidData.into());
437    }
438    let mut data = vec![0; bytes];
439    reader.read_exact(&mut data).await?;
440    serde_json::from_slice(&data).map_err(std::io::Error::other)
441}
442async fn write_frame<W: AsyncWrite + Unpin>(writer: &mut W, frame: &Frame) -> std::io::Result<()> {
443    let data = serde_json::to_vec(frame).map_err(std::io::Error::other)?;
444    if data.len() > MAX_FRAME_BYTES {
445        return Err(std::io::ErrorKind::InvalidData.into());
446    }
447    writer.write_u32(data.len() as u32).await?;
448    writer.write_all(&data).await?;
449    writer.flush().await
450}
451async fn connect(
452    endpoint: &Endpoint,
453    subscriber: bool,
454) -> std::io::Result<(transport::Stream, crate::config::HubEpoch)> {
455    let mut stream = endpoint.connect().await?;
456    write_frame(
457        &mut stream,
458        &Frame::Hello {
459            version: VERSION,
460            identity: endpoint.identity.clone(),
461            subscriber,
462        },
463    )
464    .await?;
465    match read_frame(&mut stream).await? {
466        Frame::Registered { epoch } if epoch.len() <= crate::types::MAX_ID_BYTES => {
467            Ok((stream, epoch))
468        }
469        _ => Err(std::io::ErrorKind::InvalidData.into()),
470    }
471}
472async fn publish(publisher: Arc<Publishing>) {
473    loop {
474        let wake = publisher.wake.notified();
475        if publisher.pending.lock().unwrap().dirty.is_empty() {
476            tokio::select! {
477                _ = wake => {},
478                _ = tokio::time::sleep(RECONNECT) => {
479                    // The task must not retain a publisher forever after its writers disappear.
480                    if Arc::strong_count(&publisher) == 1 {
481                        break;
482                    }
483                    continue;
484                }
485            }
486        }
487        let (mut dirty, target) = {
488            let mut pending = publisher.pending.lock().unwrap();
489            (std::mem::take(&mut pending.dirty), pending.submitted)
490        };
491        // No retries when no reader exists: future registration and the probe recover all state.
492        let delivery = async {
493            let (mut stream, _) = connect(&publisher.endpoint, false).await?;
494            while let Some(change) = dirty.pop() {
495                write_frame(&mut stream, &Frame::Publish(change)).await?;
496                if !matches!(read_frame(&mut stream).await?, Frame::Delivered) {
497                    return Err(std::io::ErrorKind::InvalidData.into());
498                }
499            }
500            Ok::<_, std::io::Error>(())
501        };
502        let _delivery = tokio::time::timeout(DELIVERY_TIMEOUT, delivery).await;
503        #[cfg(test)]
504        if !matches!(&_delivery, Ok(Ok(()))) {
505            *publisher.delivery_error.lock().unwrap() = Some(format!("{_delivery:?}"));
506        }
507        publisher.pending.lock().unwrap().delivered = target;
508        publisher.drained.notify_one();
509    }
510}
511
512enum Reconciliation {
513    Interval(tokio::time::Interval),
514    #[cfg(test)]
515    Controlled(tokio::sync::mpsc::UnboundedReceiver<()>),
516}
517
518impl Reconciliation {
519    async fn tick(&mut self) {
520        match self {
521            Self::Interval(interval) => {
522                interval.tick().await;
523            }
524            #[cfg(test)]
525            Self::Controlled(ticks) => {
526                if ticks.recv().await.is_none() {
527                    std::future::pending::<()>().await;
528                }
529            }
530        }
531    }
532}
533
534async fn watch(
535    state: std::path::PathBuf,
536    inbox: Arc<Inbox>,
537    cancel: CancellationToken,
538    ready: oneshot::Sender<()>,
539    mut reconcile: Reconciliation,
540) -> Result<(), String> {
541    let mut ready = Some(ready);
542    let endpoint = Endpoint::new(&state).ok();
543    let mut hub = None;
544    let mut probe = probe::Probe::new(state);
545    // Establish the cheap persistent baseline before the caller reads its snapshot.
546    let _ = probe.changed().await;
547    loop {
548        if cancel.is_cancelled() {
549            break;
550        }
551        if let Some(endpoint) = &endpoint {
552            if hub
553                .as_ref()
554                .is_some_and(|task: &tokio::task::JoinHandle<()>| task.is_finished())
555            {
556                hub = None;
557            }
558            if hub.is_none()
559                && let Ok(Some(owner)) = endpoint.elect()
560                && let Ok(listener) = endpoint.listen()
561            {
562                let endpoint = endpoint.clone();
563                let token = cancel.child_token();
564                hub = Some(tokio::spawn(async move {
565                    let _ = serve(endpoint, listener, owner, token).await;
566                }));
567            }
568            let connection = tokio::time::timeout(DELIVERY_TIMEOUT, connect(endpoint, true));
569            tokio::select! {
570                _ = cancel.cancelled() => break,
571                result = connection => {
572                    if let Ok(Ok((stream, epoch))) = result {
573                        inbox.add(Change::Resync);
574                        #[cfg(test)]
575                        inbox.registration.send_replace(Some(epoch.clone()));
576                        if let Some(ready) = ready.take() {
577                            let _ = ready.send(());
578                        }
579                        let receive = receive(stream, epoch, inbox.clone());
580                        tokio::pin!(receive);
581                        loop {
582                            tokio::select! {
583                                _ = cancel.cancelled() => break,
584                                _ = &mut receive => {
585                                    #[cfg(test)]
586                                    inbox.registration.send_replace(None);
587                                    inbox.add(Change::Resync);
588                                    break;
589                                }
590                                // A commit no hint reported is read like one; only a
591                                // replaced database is read afresh.
592                                _ = reconcile.tick() => match probe.changed().await {
593                                    probe::Probed::Same => {}
594                                    probe::Probed::Written => inbox.add(Change::StateInvalidated),
595                                    probe::Probed::Replaced => inbox.add(Change::Resync),
596                                }
597                            }
598                        }
599                    }
600                }
601            }
602        }
603        if let Some(ready) = ready.take() {
604            inbox.add(Change::Resync);
605            let _ = ready.send(());
606        }
607        tokio::select! {
608            _ = cancel.cancelled() => break,
609            _ = reconcile.tick() => {
610                let _ = probe.changed().await;
611                // No secure transport: low-frequency authoritative reconciliation also
612                // recovers session-only writes, which SQLite data_version cannot observe.
613                inbox.add(Change::Resync);
614            },
615            _ = tokio::time::sleep(RECONNECT) => {},
616        }
617    }
618    if let Some(task) = hub {
619        // Its child token is cancelled too; let serve join every client before releasing IPC.
620        let _ = crate::task::joined(task.await);
621    }
622    probe.close().await
623}
624async fn receive(
625    mut stream: transport::Stream,
626    epoch: crate::config::HubEpoch,
627    inbox: Arc<Inbox>,
628) -> std::io::Result<()> {
629    let mut previous = None;
630    loop {
631        match read_frame(&mut stream).await? {
632            Frame::Hint {
633                epoch: incoming,
634                sequence,
635                change,
636            } if incoming == epoch => {
637                if previous.is_some_and(|previous: u64| sequence != previous.wrapping_add(1)) {
638                    inbox.add(Change::Resync);
639                }
640                previous = Some(sequence);
641                inbox.add(change);
642                #[cfg(test)]
643                inbox.received.send_replace(Some(sequence));
644            }
645            _ => return Err(std::io::ErrorKind::InvalidData.into()),
646        }
647    }
648}
649
650#[derive(Clone)]
651struct Hint {
652    sequence: u64,
653    change: Change,
654}
655async fn serve(
656    endpoint: Endpoint,
657    mut listener: transport::Listener,
658    _owner: std::fs::File,
659    cancel: CancellationToken,
660) -> std::io::Result<()> {
661    let epoch: crate::config::HubEpoch = crate::agent::uuid()
662        .map_err(std::io::Error::other)?
663        .parse()
664        .expect("UUID hub epoch");
665    let (sender, _) = broadcast::channel(MAX_BACKLOG);
666    let sequence = Arc::new(Mutex::new(0_u64));
667    let mut clients = JoinSet::new();
668    loop {
669        tokio::select! {
670            _ = cancel.cancelled() => break,
671            Some(result) = clients.join_next(), if !clients.is_empty() => {
672                let _ = crate::task::joined(result);
673            },
674            result = listener.accept(), if clients.len() < MAX_CLIENTS => {
675                let stream = result?;
676                let (identity, epoch, sender, sequence) = (
677                    endpoint.identity.clone(),
678                    epoch.clone(),
679                    sender.clone(),
680                    sequence.clone(),
681                );
682                clients.spawn(async move {
683                    let _ = client(stream, identity, epoch, sender, sequence).await;
684                });
685            }
686        }
687    }
688    clients.abort_all();
689    while let Some(result) = clients.join_next().await {
690        let _ = crate::task::joined(result);
691    }
692    Ok(())
693}
694async fn client(
695    mut stream: transport::Stream,
696    identity: crate::config::EndpointId,
697    epoch: crate::config::HubEpoch,
698    sender: broadcast::Sender<Hint>,
699    sequence: Arc<Mutex<u64>>,
700) -> std::io::Result<()> {
701    // Peer lookup can fail after a short-lived connection closes (Darwin ENOTCONN).
702    // Reject only that client, never tear down the listener or other subscribers.
703    transport::validate_peer(&stream)?;
704    let hello = tokio::time::timeout(DELIVERY_TIMEOUT, read_frame(&mut stream)).await??;
705    let Frame::Hello {
706        version: VERSION,
707        identity: incoming,
708        subscriber,
709    } = hello
710    else {
711        return Err(std::io::ErrorKind::InvalidData.into());
712    };
713    if incoming != identity {
714        return Err(std::io::ErrorKind::PermissionDenied.into());
715    }
716    // Register before acknowledging. Broadcast retains any hint that races the baseline read.
717    let mut receiver = sender.subscribe();
718    tokio::time::timeout(
719        DELIVERY_TIMEOUT,
720        write_frame(
721            &mut stream,
722            &Frame::Registered {
723                epoch: epoch.clone(),
724            },
725        ),
726    )
727    .await??;
728    if subscriber {
729        let (mut reader, mut writer) = tokio::io::split(stream);
730        let outgoing = async {
731            loop {
732                let hint = match receiver.recv().await {
733                    Ok(hint) => hint,
734                    Err(broadcast::error::RecvError::Lagged(_)) => Hint {
735                        sequence: *sequence.lock().unwrap(),
736                        change: Change::Resync,
737                    },
738                    Err(_) => return Ok::<_, std::io::Error>(()),
739                };
740                // A slow client loses only hints, not memory or the hub's other clients.
741                tokio::time::timeout(
742                    DELIVERY_TIMEOUT,
743                    write_frame(
744                        &mut writer,
745                        &Frame::Hint {
746                            epoch: epoch.clone(),
747                            sequence: hint.sequence,
748                            change: hint.change,
749                        },
750                    ),
751                )
752                .await??;
753            }
754        };
755        tokio::select! { result = outgoing => result, _ = reader.read_u8() => Ok(()) }
756    } else {
757        loop {
758            let frame = tokio::time::timeout(DELIVERY_TIMEOUT, read_frame(&mut stream)).await??;
759            let Frame::Publish(change) = frame else {
760                return Err(std::io::ErrorKind::InvalidData.into());
761            };
762            {
763                // Serialize sequence assignment and broadcast, including concurrent writers.
764                let mut sequence = sequence.lock().unwrap();
765                *sequence = sequence.wrapping_add(1);
766                let _ = sender.send(Hint {
767                    sequence: *sequence,
768                    change,
769                });
770            }
771            tokio::time::timeout(
772                DELIVERY_TIMEOUT,
773                write_frame(&mut stream, &Frame::Delivered),
774            )
775            .await??;
776        }
777    }
778}