agentmux_srv_core/backend/vault/sync_merge.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What the Vault does when a record arrives from another machine (docs/specs/SPEC_VAULT_SHARED_ACROSS_MACHINES_LAN_AND_CLOUD_2026_11_01.md
5//! sections 6.2 to 6.5): the answer the sync layer asks of an adapter, `Applied`, `KeptLocal` or `Conflict(both)`.
6//!
7//! A value is never merged and never lost to a clock. When two machines change an entry before either has seen the
8//! other's change, the later version becomes current and the other is kept, as a version called "changed on <machine> at
9//! the same time" that is not pruned after 7 days. A delete is a version like any other: apart from a change, the later
10//! of the two is current and the other is kept, so the answer is the same on every machine in whatever order the records
11//! arrive. A rotation in progress is never overwritten, nor deleted until it ends. Only the tags are merged, as a union.
12//!
13//! Every function is pure over versions and tags: no store, no clock, no network. The records' bodies stay sealed in
14//! [`super::sync_seal`]; what is decided here needs only their versions.
15
16use super::sync_seal::Version;
17
18/// A record arriving from another machine, as far as the merge needs to know it.
19#[derive(Debug, Clone, PartialEq)]
20pub struct Change {
21 pub version: Version,
22 /// The version this change replaced on the machine that made it. It travels in the clear beside the version and is
23 /// also in the record's associated data (`sync_seal::Place::base`), so the caller takes it from a record that has
24 /// opened: a relay cannot change it to hide a conflict. Even then it only lets a newer record take the place of the
25 /// current one, never an older (see [`merge`]).
26 pub base: Option<Version>,
27 /// The tags of the new value; `None` for a tombstone, which carries only its id and versions.
28 pub tags: Option<Vec<String>>,
29}
30
31/// What this machine holds of the same record.
32#[derive(Debug, Clone, PartialEq, Default)]
33pub struct Held {
34 /// Every version of the record this machine has had, the current one first. A tombstone is the current one of a
35 /// deleted record. Empty when the machine has never heard of the record.
36 pub versions: Vec<Version>,
37 pub deleted: bool,
38 /// A rotation is under way here: its new value is waiting to be confirmed, and no sync may overwrite it.
39 pub pending_rotation: bool,
40 /// The current value's tags.
41 pub tags: Vec<String>,
42}
43
44/// Which of two versions is the one every machine uses from now on.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum Side {
47 Local,
48 Incoming,
49}
50
51/// The state of the version that did not become current.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum Kept {
54 /// Made on `machine` at the same time as the current one, neither having seen the other.
55 SameTime { machine: String },
56 /// Made on `machine` on top of a value whose rotation has not ended here: it waits as a version, and the person
57 /// settles it when the rotation is over.
58 WaitsForRotation { machine: String },
59 /// A delete made on `machine` of a value whose rotation has not ended here: it waits too, because the rotation may
60 /// already have changed the credential at its source, and deleting the entry would lose the new value.
61 DeleteWaitsForRotation { machine: String },
62 /// A change made on `machine` apart from a delete of the entry, and the one the delete is later than: the entry ends
63 /// deleted on every machine, and the change is kept as a version the person can restore.
64 ChangedWhileDeleted { machine: String },
65 /// A delete made on `machine` apart from a change that is later than it: the entry ends as changed on every machine,
66 /// and the delete is kept, so the person can see it and delete the entry again.
67 Deleted { machine: String },
68 /// Two deletes of the entry made apart on `machine` and elsewhere: the later is current and the earlier is kept, so
69 /// a change made between them is compared with the same delete on every machine.
70 DeletedAlso { machine: String },
71}
72
73impl Kept {
74 /// What the Vault pane shows beside the version.
75 pub fn label(&self) -> String {
76 match self {
77 Kept::SameTime { machine } => format!("changed on {machine} at the same time"),
78 Kept::WaitsForRotation { machine } => format!("changed on {machine} while this was being rotated"),
79 Kept::DeleteWaitsForRotation { machine } => format!("deleted on {machine} while this was being rotated"),
80 Kept::ChangedWhileDeleted { machine } => format!("changed on {machine} while it was deleted elsewhere"),
81 Kept::Deleted { machine } => format!("deleted on {machine} while it was changed elsewhere"),
82 Kept::DeletedAlso { machine } => format!("deleted on {machine} as well"),
83 }
84 }
85}
86
87/// The adapter's answer to the layer (spec 6.3).
88#[derive(Debug, Clone, PartialEq)]
89pub enum Decision {
90 /// The incoming record replaces the current one.
91 Applied,
92 /// The incoming record is one this machine already has, or is older than what it holds: nothing changes.
93 KeptLocal,
94 /// Neither replaces the other. `current` is the one every machine uses until the person chooses, `kept` is the state
95 /// of the other (kept as a version, never dropped), and `tags` is the union of both's tags, which goes on the
96 /// current one.
97 Conflict { current: Side, kept: Kept, tags: Vec<String> },
98}
99
100/// `a`'s tags, then those of `b` that `a` does not have.
101pub fn union_tags(a: &[String], b: &[String]) -> Vec<String> {
102 let mut out = a.to_vec();
103 for t in b {
104 if !out.contains(t) {
105 out.push(t.clone());
106 }
107 }
108 out
109}
110
111/// What to do with `change` when this machine holds `held` (`None`, or no versions, if it has never had the record).
112pub fn merge(held: Option<&Held>, change: &Change) -> Decision {
113 let Some(h) = held.filter(|h| !h.versions.is_empty()) else {
114 return Decision::Applied;
115 };
116 // One this machine has had: a repeat, or a version already replaced.
117 if h.versions.contains(&change.version) {
118 return Decision::KeptLocal;
119 }
120 let current = &h.versions[0];
121 let value_in = change.tags.as_deref();
122 // The change was made on top of what this machine holds, and is later than it: it follows on. A change that only
123 // claims to follow, but is not later, is treated as made at the same time, so an old record replayed with a false
124 // base cannot take the place of a new one.
125 if change.base.as_ref() == Some(current) && change.version > *current {
126 return if h.pending_rotation && !h.deleted {
127 let machine = change.version.machine.clone();
128 let kept = if value_in.is_some() { Kept::WaitsForRotation { machine } } else { Kept::DeleteWaitsForRotation { machine } };
129 Decision::Conflict { current: Side::Local, kept, tags: h.tags.clone() }
130 } else {
131 Decision::Applied
132 };
133 }
134 // Not on top of what this machine holds: made apart from it, or after versions this machine has not been sent yet.
135 // The later version is the current one, whatever the two are (a value or a delete), so every machine reaches the same
136 // answer in whatever order the records arrive, and the other is kept as a version for the person. Which came after
137 // which on the wall clock is not what decides it, only the versions: a late ancestor is older than what is held and
138 // never replaces it, and a record that is on top of one this machine has not been sent yet (a restore after a delete,
139 // edited again) ends current when the earlier ones arrive, because it is the latest.
140 let incoming_later = change.version > *current;
141 let rotating = h.pending_rotation && !h.deleted;
142 let side = if rotating || !incoming_later { Side::Local } else { Side::Incoming };
143 let (local_machine, incoming_machine) = (current.machine.clone(), change.version.machine.clone());
144 match (h.deleted, value_in) {
145 // Two deletes of the same record: it is deleted either way, but which delete is current is still decided by the
146 // versions, because a change made apart from them is compared with the current one.
147 (true, None) if side == Side::Local => Decision::KeptLocal,
148 (true, None) => Decision::Conflict { current: Side::Incoming, kept: Kept::DeletedAlso { machine: local_machine }, tags: h.tags.clone() },
149 (false, Some(theirs)) => {
150 let kept = match side {
151 Side::Local if rotating => Kept::WaitsForRotation { machine: incoming_machine },
152 Side::Local => Kept::SameTime { machine: incoming_machine },
153 Side::Incoming => Kept::SameTime { machine: local_machine },
154 };
155 let tags = match side {
156 Side::Local => union_tags(&h.tags, theirs),
157 Side::Incoming => union_tags(theirs, &h.tags),
158 };
159 Decision::Conflict { current: side, kept, tags }
160 }
161 // A delete against a value: the later is current, and the other is kept.
162 (deleted_here, _) => {
163 let kept = match (side, deleted_here) {
164 (Side::Local, false) if rotating => Kept::DeleteWaitsForRotation { machine: incoming_machine },
165 // Here a value, a delete arrives and is older: the delete is the one kept.
166 (Side::Local, false) => Kept::Deleted { machine: incoming_machine },
167 // Here a delete, a value arrives and is older: the value is the one kept.
168 (Side::Local, true) => Kept::ChangedWhileDeleted { machine: incoming_machine },
169 // The incoming is later and takes the place of what is here: what was here is the one kept.
170 (Side::Incoming, false) => Kept::ChangedWhileDeleted { machine: local_machine },
171 (Side::Incoming, true) => Kept::Deleted { machine: local_machine },
172 };
173 // A value that takes the place of a delete is the current value, so its tags are the value's (with any the delete
174 // held), as they are on the machine that kept the value. Any other side leaves the tags of what is current.
175 let tags = match (deleted_here, side, value_in) {
176 (true, Side::Incoming, Some(theirs)) => union_tags(theirs, &h.tags),
177 _ => h.tags.clone(),
178 };
179 Decision::Conflict { current: side, kept, tags }
180 }
181 }
182}
183
184/// After a full resync: the records only this machine has (`mine`, against `theirs`, the ids every other member holds).
185/// They are shown to the person as "Only on this machine: keep or delete", never brought back or deleted silently.
186pub fn only_here(mine: &[String], theirs: &[String]) -> Vec<String> {
187 mine.iter().filter(|id| !theirs.contains(id)).cloned().collect()
188}
189
190#[cfg(test)]
191#[path = "sync_merge_tests.rs"]
192mod tests;