Skip to main content

agentmux_srv_core/backend/user_sync/
round.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! One round of sync with one peer, for one collection (SPEC_USER_DATA_SYNC_LAYER ยง4.2, the loop's body): the asking
5//! side of the `sync.*` ops. A round learns the membership changes each side lacks (`sync.members`), takes the keys of
6//! any epoch this machine lacks (`sync.keys`), pulls the records it lacks, and pushes the ones the peer lacks. It is
7//! pure over a [`PeerCalls`] (the calls to the peer) and a [`Session`] (this machine's own state): a transport hands
8//! it both and it never opens a connection, so it is tested against in-memory machines. A [`Session`] lends the
9//! round this machine's [`Ctx`] only for the length of one closure, so a transport that keeps the store locked while
10//! a closure runs never keeps it locked across a call to the peer (which is itself asking this machine for the same
11//! store). Which peers, when, and what wakes the loop belong to the transport.
12//!
13//! A round never gives up the others' records because one is refused: each record is checked and applied on its own,
14//! the refusals are counted by kind, and a refusal that is the peer's news (an epoch this machine has not reached, a
15//! sequence skipped) ends the pull so the next round takes it again from the membership step.
16
17use super::adapter::Adapter;
18use super::chain_store;
19use super::log::{self, Outcome, Refused, Signer, SyncError};
20use super::members::{Change, Entry, Kind, MemberError, Taken};
21use super::ops::{self, Ctx, Held, KeysAns, KeysReq, MembersAns, MembersReq, OpError, PullAns, PullReq, PushAns, PushReq};
22
23/// The most batches one round pulls or pushes: a peer with more waits for the next round.
24pub const MAX_BATCHES: usize = 64;
25/// The most times one round asks for membership entries (a longer chain than one answer carries).
26pub const MAX_MEMBER_ASKS: usize = 8;
27
28/// Why a call to the peer did not give an answer.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub enum CallError {
31    /// The peer could not be reached or did not answer.
32    Unreachable(String),
33    /// The peer answered with a refusal; the code is the op's (`OpError::code`) or the transport's.
34    Refused(String),
35}
36
37/// This machine's side: its sync state, lent to one closure at a time.
38pub trait Session {
39    /// Runs `f` with this machine's state, or says why it could not be had (the store is busy, say): `f` did not run.
40    fn with<R>(&mut self, f: impl FnOnce(&mut Ctx) -> R) -> Result<R, String>;
41}
42
43/// The calls to one peer. Each is one remote op; the transport signs and carries it.
44pub trait PeerCalls {
45    fn hello(&mut self, collections: &[String]) -> Result<Vec<Held>, CallError>;
46    fn members(&mut self, req: &MembersReq) -> Result<MembersAns, CallError>;
47    fn keys(&mut self, req: &KeysReq) -> Result<KeysAns, CallError>;
48    fn pull(&mut self, req: &PullReq) -> Result<PullAns, CallError>;
49    fn push(&mut self, req: &PushReq) -> Result<PushAns, CallError>;
50}
51
52/// How a round ended.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub enum Ended {
55    /// Both sides now hold the same, as far as this round could tell.
56    Synced,
57    /// This install does not hold the computer's sync lock: nothing was asked.
58    NotActive,
59    /// The peer's install does not hold its lock right now: try again later.
60    PeerIdle,
61    /// The peer could not be reached.
62    Unreachable(String),
63    /// This machine does not hold the collection, or is not in it.
64    NotHere,
65    /// The peer does not list this machine as a member (it was removed there, or never added): nothing was exchanged
66    /// beyond what a former member may learn.
67    NotAMemberThere,
68    /// This machine learned it was removed from the collection, and by whom. Nothing after that was asked.
69    Removed { by: String },
70    /// The peer sent something this machine will not take (an answer over a cap, an unsound chain).
71    Distrusted(String),
72    /// A local store error: the round stopped.
73    Failed(String),
74}
75
76/// What a round did.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct Round {
79    pub ended: Ended,
80    /// Membership entries taken from the peer, and how many of ours the peer took.
81    pub entries_taken: usize,
82    pub entries_given: usize,
83    pub keys_taken: usize,
84    /// Records this machine wrote again at the new key epoch, because a removal cut them off.
85    pub reissued: usize,
86    /// Records pulled and applied (not counting ones already held), kept as the older side, or in conflict.
87    pub pulled: usize,
88    pub kept_local: usize,
89    pub conflicts: usize,
90    /// Records the peer took from this machine.
91    pub pushed: usize,
92    /// Records refused on either side, by kind (the refusal's name).
93    pub refused: Vec<String>,
94}
95
96impl Round {
97    fn new() -> Round {
98        Round { ended: Ended::Synced, entries_taken: 0, entries_given: 0, keys_taken: 0, reissued: 0, pulled: 0, kept_local: 0, conflicts: 0, pushed: 0, refused: Vec::new() }
99    }
100
101    fn end(mut self, ended: Ended) -> Round {
102        self.ended = ended;
103        self
104    }
105
106    fn refuse(&mut self, why: &Refused) {
107        let name = match why {
108            Refused::UnknownCollection => "unknown_collection",
109            Refused::UnknownOrigin => "unknown_origin",
110            Refused::Bad(_) => "bad_record",
111            Refused::Epoch { .. } => "epoch",
112            Refused::Skew(_) => "skew",
113            Refused::Gap { .. } => "gap",
114            Refused::Rollback => "rollback",
115        };
116        if !self.refused.iter().any(|r| r == name) {
117            self.refused.push(name.to_string());
118        }
119    }
120
121    /// Whether anything changed on either side.
122    pub fn changed(&self) -> bool {
123        self.entries_taken + self.entries_given + self.keys_taken + self.reissued + self.pulled + self.kept_local + self.conflicts + self.pushed > 0
124    }
125}
126
127fn stop(e: CallError) -> Ended {
128    match e {
129        CallError::Unreachable(why) => Ended::Unreachable(why),
130        CallError::Refused(code) if code == OpError::NotActive.code() => Ended::PeerIdle,
131        CallError::Refused(code) if code == OpError::NotMember.code() => Ended::NotAMemberThere,
132        CallError::Refused(code) => Ended::Distrusted(format!("the peer refused: {code}")),
133    }
134}
135
136fn db(e: impl std::fmt::Display) -> Ended {
137    Ended::Failed(e.to_string())
138}
139
140/// The machine that signed this machine's removal, when the chain removes it.
141fn removed_by(entries: &[Entry], me: &str) -> Option<String> {
142    entries.iter().find(|e| matches!(&e.change, Change::Remove { id, .. } if id == me)).map(|e| e.signer.clone())
143}
144
145/// [`Session::with`], its failure as the end of the round.
146fn lent<S: Session, R>(s: &mut S, f: impl FnOnce(&mut Ctx) -> R) -> Result<R, Ended> {
147    s.with(f).map_err(Ended::Failed)
148}
149
150fn is_member(ctx: &Ctx, collection: &str) -> bool {
151    ctx.chains.get(collection).and_then(|c| c.state(collection).ok()).is_some_and(|s| s.members.get(ctx.me.id).is_some_and(|m| m.kind == Kind::Machine))
152}
153
154fn taken_count(taken: &[Result<Taken, MemberError>]) -> usize {
155    taken.iter().filter(|t| matches!(t, Ok(Taken::Extended | Taken::Replaced(_)))).count()
156}
157
158/// What to say to the peer next, read from this machine's state.
159struct Ask {
160    have: u64,
161    offered: Vec<Entry>,
162    /// Only the end of a long chain was asked for, so an entry may follow one that is not held.
163    windowed: bool,
164}
165
166/// Learns the membership entries each side lacks. A removal of this machine ends the round.
167fn exchange_members<S: Session, P: PeerCalls>(s: &mut S, peer: &mut P, collection: &str, mut peer_n: u64, mut peer_head: Option<String>, out: &mut Round) -> Result<(), Ended> {
168    for _ in 0..MAX_MEMBER_ASKS {
169        let ask = lent(s, |ctx| {
170            let chain = ctx.chains.get(collection).ok_or(Ended::NotHere)?;
171            let len = chain.entries.len();
172            // The chains are the same only when they are as long as each other with the same head, or the peer says nothing
173            // of its head. When the heads are known to differ, the peer may hold a different entry anywhere the chains
174            // differ (a fork that one side has since gone on from), so each side is given the other's chain from half the
175            // cap back from where the shorter ends: held entries are only duplicates, and a fork is settled where it is. Later
176            // asks (the head is no longer known) go on from where the peer is.
177            let same = peer_n as usize == len && chain.entries.last().map(Entry::hash) == peer_head;
178            let divergent = !same && peer_head.is_some();
179            let start = (len.min(peer_n as usize)).saturating_sub(ops::MAX_ENTRIES / 2);
180            let (have, skip) = if divergent { (start, start) } else { (len, peer_n as usize) };
181            let offered = chain.entries.iter().skip(skip).take(ops::MAX_ENTRIES).cloned().collect();
182            Ok::<_, Ended>(Ask { have: have as u64, offered, windowed: divergent && start > 0 })
183        })??;
184        peer_head = None;
185        let windowed = ask.windowed;
186        let ans = peer.members(&MembersReq { collection: collection.to_string(), have_n: ask.have, offered: ask.offered }).map_err(stop)?;
187        if ans.entries.len() > ops::MAX_ENTRIES {
188            return Err(Ended::Distrusted("a membership answer over the cap".into()));
189        }
190        out.entries_given += taken_count(&ans.taken);
191        let (took, now, removed, unsound) = lent(s, |ctx| {
192            let chain = ctx.chains.get_mut(collection).ok_or(Ended::NotHere)?;
193            let mut taken: Vec<Result<Taken, MemberError>> = Vec::new();
194            let mut unsound = None;
195            let mut lost: Vec<u32> = Vec::new();
196            for entry in ans.entries.iter().cloned() {
197                let epochs = ops::removals_before(chain);
198                match chain.take(collection, entry) {
199                    Ok(t) => {
200                        lost.extend(ops::lost_epochs(&epochs, &Ok(t.clone())));
201                        taken.push(Ok(t));
202                    }
203                    // An entry on a branch that loses is a result, as `ops::members` records it. So is one that follows no entry
204                    // held, when only the end of a long chain was asked for: its start is not here to join to.
205                    Err(MemberError::ForkLost) => taken.push(Err(MemberError::ForkLost)),
206                    Err(MemberError::DoesNotExtend) if windowed => taken.push(Err(MemberError::DoesNotExtend)),
207                    Err(e) => {
208                        unsound = Some(e);
209                        break;
210                    }
211                }
212            }
213            // What was taken before an entry that does not verify is stored as it is for any other.
214            ops::discard_lost_keys(ctx.keys, collection, &lost);
215            ops::sync_epoch(ctx.conn, collection, chain).map_err(|e| Ended::Failed(format!("{e:?}")))?;
216            chain_store::save(ctx.conn, collection, chain).map_err(db)?;
217            let removed = if is_member(ctx, collection) { None } else { Some(removed_by(&ctx.chains[collection].entries, ctx.me.id).unwrap_or_default()) };
218            Ok((taken_count(&taken), ctx.chains[collection].entries.len() as u64, removed, unsound))
219        })??;
220        out.entries_taken += took;
221        if let Some(e) = unsound {
222            return Err(Ended::Distrusted(format!("a membership entry that does not verify: {e:?}")));
223        }
224        if let Some(by) = removed {
225            return Err(Ended::Removed { by });
226        }
227        // Another ask only when the peer has more of its chain than it sent and this machine advanced.
228        if ans.entries.is_empty() || now >= ans.n {
229            break;
230        }
231        peer_n = peer_n.max(now.min(ans.n));
232    }
233    Ok(())
234}
235
236/// Takes the keys of epochs this machine lacks.
237fn take_keys<S: Session, P: PeerCalls>(s: &mut S, peer: &mut P, collection: &str, out: &mut Round) -> Result<(), Ended> {
238    let have = lent(s, |ctx| {
239        let epoch = ctx.chains.get(collection).and_then(|c| c.state(collection).ok()).map_or(0, |st| st.epoch);
240        let have = ctx.keys.held(collection);
241        if (0..=epoch).all(|e| have.contains(&e)) {
242            None
243        } else {
244            Some(have)
245        }
246    })?;
247    let Some(have) = have else { return Ok(()) };
248    let ans = peer.keys(&KeysReq { collection: collection.to_string(), have }).map_err(stop)?;
249    if ans.keys.len() > ops::MAX_NAMES {
250        return Err(Ended::Distrusted("a key answer over the cap".into()));
251    }
252    out.keys_taken += lent(s, |ctx| ctx.keys.take(collection, &ans.keys))?;
253    Ok(())
254}
255
256/// Settles the records a change of the membership chain moved in or out of the key epochs' ends (a write stored as void
257/// under a removal that lost a fork, say): the chain changes in the exchange of entries, before anything is pulled.
258fn settle_voids<S: Session>(s: &mut S, collection: &str, adapter: &dyn Adapter, out: &mut Round) -> Result<(), Ended> {
259    let moved = lent(s, |ctx| log::recheck(ctx.conn, collection, ctx.me.id, adapter))?.map_err(db)?;
260    out.pulled += moved;
261    Ok(())
262}
263
264/// Writes again, at the collection's current key epoch, what this machine wrote after the others had stopped at an
265/// older one (a removal cut it off): the peer would refuse it as it stands. Not while the removal is still contested, and
266/// not before the key of the new epoch has arrived: the next round does it. Only what is still the record's state, so a
267/// later write of another machine is not written over.
268fn reissue<S: Session>(s: &mut S, collection: &str, out: &mut Round) -> Result<(), Ended> {
269    let done = lent(s, |ctx| {
270        if !ops::may_seal(ctx, collection) {
271            return Ok(0);
272        }
273        let ring = ctx.keys.ring(collection);
274        let mut signer = Signer { machine: ctx.me.id, private: ctx.me.private, clock: &mut *ctx.clock };
275        ops::reissue(ctx.conn, &mut signer, &ring, collection, ctx.now_ms)
276    })?;
277    match done {
278        Ok(n) => out.reissued += n,
279        Err(SyncError::Db(e)) => return Err(db(e)),
280        Err(_) => {}
281    }
282    Ok(())
283}
284
285/// Pulls and applies, batch by batch, until the peer has no more or a batch changes nothing.
286fn pull_all<S: Session, P: PeerCalls>(s: &mut S, peer: &mut P, collection: &str, adapter: &dyn Adapter, out: &mut Round) -> Result<(), Ended> {
287    for _ in 0..MAX_BATCHES {
288        let before = lent(s, |ctx| log::vector(ctx.conn, collection))?.map_err(db)?;
289        let req = PullReq { collection: collection.to_string(), vector: before.clone(), limit: ops::MAX_BATCH_RECORDS };
290        let ans = peer.pull(&req).map_err(stop)?;
291        ops::check_pull_answer(&ans, req.limit).map_err(|_| Ended::Distrusted("a pull answer over the cap".into()))?;
292        let (after, stalled) = lent(s, |ctx| {
293            let state = ctx.chains.get(collection).and_then(|c| c.state(collection).ok()).ok_or(Ended::NotHere)?;
294            let pins = state.pins();
295            let mut stalled = false;
296            for rec in &ans.records {
297                // Only the collection asked about: its members' pins say nothing of another collection's.
298                if rec.header.collection != collection {
299                    out.refuse(&Refused::UnknownCollection);
300                    continue;
301                }
302                match log::apply_remote(ctx.conn, rec, &pins, ctx.clock, ctx.now_ms, adapter) {
303                    Ok(Outcome::Applied) => out.pulled += 1,
304                    Ok(Outcome::KeptLocal) => out.kept_local += 1,
305                    Ok(Outcome::Conflict) => out.conflicts += 1,
306                    Ok(Outcome::Duplicate | Outcome::Void) => {}
307                    Err(SyncError::Refused(why)) => {
308                        out.refuse(&why);
309                        // A skipped sequence or an epoch not reached yet: what follows from that origin would be
310                        // refused the same way, so the round leaves it for the next one.
311                        stalled |= matches!(why, Refused::Gap { .. } | Refused::Epoch { .. });
312                    }
313                    Err(SyncError::Db(e)) => return Err(db(e)),
314                    Err(SyncError::Seal(e)) => return Err(Ended::Failed(e)),
315                }
316            }
317            Ok((log::vector(ctx.conn, collection).map_err(db)?, stalled))
318        })??;
319        if !ans.more || after == before || stalled {
320            break;
321        }
322    }
323    Ok(())
324}
325
326/// Pushes what the peer lacks, batch by batch, until it holds all of it or a batch moves nothing.
327fn push_all<S: Session, P: PeerCalls>(s: &mut S, peer: &mut P, collection: &str, mut theirs: log::Vector, out: &mut Round) -> Result<(), Ended> {
328    for _ in 0..MAX_BATCHES {
329        let records = lent(s, |ctx| {
330            let mut records = log::since(ctx.conn, collection, &theirs, ops::MAX_BATCH_RECORDS).map_err(db)?;
331            ops::cap_bytes(&mut records);
332            Ok::<_, Ended>(records)
333        })??;
334        if records.is_empty() {
335            break;
336        }
337        let ans = peer.push(&PushReq { collection: collection.to_string(), records: records.clone() }).map_err(stop)?;
338        if ans.results.len() != records.len() {
339            return Err(Ended::Distrusted("a push answer that does not match the request".into()));
340        }
341        for result in &ans.results {
342            match result {
343                Ok(Outcome::Applied | Outcome::KeptLocal | Outcome::Conflict) => out.pushed += 1,
344                Ok(Outcome::Duplicate | Outcome::Void) => {}
345                Err(why) => out.refuse(why),
346            }
347        }
348        let moved = ans.vector != theirs;
349        theirs = ans.vector;
350        if !moved {
351            break;
352        }
353    }
354    Ok(())
355}
356
357/// One round with one peer for one collection.
358pub fn sync_collection<S: Session, P: PeerCalls>(s: &mut S, peer: &mut P, collection: &str, adapter: &dyn Adapter) -> Round {
359    let mut out = Round::new();
360    let start = lent(s, |ctx| {
361        if !ctx.active {
362            Err(Ended::NotActive)
363        } else if !is_member(ctx, collection) {
364            Err(Ended::NotHere)
365        } else {
366            Ok(ctx.chains[collection].entries.len() as u64)
367        }
368    })
369    .and_then(|r| r);
370    let mine = match start {
371        Ok(n) => n,
372        Err(ended) => return out.end(ended),
373    };
374    let held = match peer.hello(&[collection.to_string()]) {
375        Ok(held) => held,
376        Err(e) => return out.end(stop(e)),
377    };
378    let Some(held) = held.into_iter().find(|h| h.collection == collection) else {
379        // The peer leaves this machine out of what it answers, which is also how it answers a machine it removed. A
380        // former member may still ask for the membership entries up to its own removal, so ask: that is how a removed
381        // machine learns it was, and by whom.
382        return match exchange_members(s, peer, collection, mine, None, &mut out) {
383            // Only what the peer's refusal says is "not a member there"; any other end is what happened.
384            Ok(()) | Err(Ended::NotAMemberThere) => out.end(Ended::NotAMemberThere),
385            Err(ended) => out.end(ended),
386        };
387    };
388    let steps = (|| {
389        exchange_members(s, peer, collection, held.n, held.head.clone(), &mut out)?;
390        take_keys(s, peer, collection, &mut out)?;
391        settle_voids(s, collection, adapter, &mut out)?;
392        pull_all(s, peer, collection, adapter, &mut out)?;
393        // After the pull: what the others wrote to the same record meanwhile is then in its state, and a write this
394        // machine made that it no longer is the state of is not written again over it.
395        reissue(s, collection, &mut out)?;
396        push_all(s, peer, collection, held.vector.clone(), &mut out)
397    })();
398    match steps {
399        Ok(()) => out,
400        Err(ended) => out.end(ended),
401    }
402}