aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-11-15 16:33:22 +0000
committertv <tv@krebsco.de>2026-11-15 16:33:22 +0000
commitb8c3c1a5adaa2a64fc17bd89a943ccf1ad386373 (patch)
tree3bb9bf2580932cadd3d0eb724d5343c55ff1f0fa
parentb0d68ad3b99aa06029f30d7dc45455108b52dadc (diff)
store: values ordered by seq only where the policy asks for signed values
The order by `seq` sat in `store::candidates`, which every swarm reads through: in a swarm that isn't strict, a string shaped like an envelope, written at the same time as a plain value or a map, was read first. What a swarm without a strict policy reads must not change for signed values. The order now applies only where the policy asks for signed values (`"values": "signed"`), as any value at the policy's place says, read as written (`signs_values`), so the policy's own reading doesn't go round. Elsewhere `candidates` is newest first, as always. It is looked at only where a place holds several values and one is an envelope.
-rw-r--r--docs/api.md6
-rw-r--r--src/document/store.rs105
2 files changed, 96 insertions, 15 deletions
diff --git a/docs/api.md b/docs/api.md
index 41a4f4d..a839f74 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -164,8 +164,10 @@ way on every node:
* **The same key**: one write wins, the same one everywhere. "Newest" means by
Automerge's operation order (the write made after seeing more changes; between equals,
by the writer's actor ID), not by any clock: of two truly concurrent writes, which wins
- is arbitrary, but it is the same on every node. Values their users signed come first
- (Signed values, below): of those, the one its user numbered highest (`seq`).
+ is arbitrary, but it is the same on every node. Where the swarm's policy asks for
+ signed values (Signed values, below), a string that is an envelope comes before
+ anything else written there at once, a map too: of those, the one its user numbered
+ highest (`seq`), of equal ones the one with the lower SHA-256.
* **Maps written at the same key** merge into one: their keys are united, each key as
above.
* **A write and a delete** of the same key: the write stays (a delete removes only what
diff --git a/src/document/store.rs b/src/document/store.rs
index 06dcce4..ba1a1ec 100644
--- a/src/document/store.rs
+++ b/src/document/store.rs
@@ -224,11 +224,46 @@ fn signed_order(value: &Value<'_>) -> Option<(u64, [u8; 32])> {
Some((payload.seq, Sha256::digest(text.as_bytes()).into()))
}
+/// Whether `doc`'s policy asks for signed values (`access::policy`: `"values":
+/// "signed"`), as any value at its place says, read as written: below every reading
+/// that goes by it (`candidates`), the policy's own included.
+fn signs_values(doc: &impl ReadDoc) -> bool {
+ let mut maps = vec![automerge::ROOT];
+ for key in [super::meta::ROOT, super::meta::ACCESS] {
+ maps = maps
+ .iter()
+ .flat_map(|map| doc.get_all(map, key).unwrap_or_default())
+ .filter_map(|(value, id)| matches!(value, Value::Object(ObjType::Map)).then_some(id))
+ .collect();
+ }
+ let asks = |value: &JsonValue| value.get("values") == Some(&JsonValue::from("signed"));
+ maps.iter()
+ .flat_map(|map| doc.get_all(map, "policy").unwrap_or_default())
+ .any(|(value, id)| match value {
+ Value::Object(ObjType::Map) => doc
+ .get_all(&id, "values")
+ .unwrap_or_default()
+ .iter()
+ .any(|(value, _)| {
+ matches!(value, Value::Scalar(scalar)
+ if matches!(scalar.as_ref(), ScalarValue::Str(text) if text == "signed"))
+ }),
+ Value::Scalar(scalar) => match scalar.as_ref() {
+ ScalarValue::Str(text) => {
+ super::signed::read(text).is_some_and(|payload| asks(&payload.value))
+ }
+ _ => false,
+ },
+ _ => false,
+ })
+}
+
/// All concurrent values of `key` across a merged set of parent maps, the one that
-/// counts first: signed values (`access::envelope`) before any other, the highest
-/// `seq` first, of equal ones the lower digest; then the others, newest first. So
-/// which signed value a place shows is its user's to say, not the order of operations,
-/// which whoever writes a change steers.
+/// counts first. Newest first; where the policy asks for signed values
+/// (`signs_values`), signed values (`document::signed`) before any other, the highest
+/// `seq` first, of equal ones the lower digest, then the others, newest first. So in a
+/// strict swarm which signed value a place shows is its user's to say, not the order
+/// of operations, which whoever writes a change steers. Elsewhere nothing changes.
fn candidates(
doc: &impl ReadDoc,
parents: &[ObjId],
@@ -242,11 +277,19 @@ fn candidates(
}
all.sort_by(|a, b| op_order(&b.1).cmp(&op_order(&a.1)));
if all.len() > 1 {
- // Stable: the others stay newest first.
- all.sort_by_cached_key(|(value, _)| match signed_order(value) {
- Some((seq, digest)) => (false, std::cmp::Reverse(seq), digest),
- None => (true, std::cmp::Reverse(0), [0; 32]),
- });
+ let orders: Vec<_> = all.iter().map(|(value, _)| signed_order(value)).collect();
+ if orders.iter().any(Option::is_some) && signs_values(doc) {
+ let mut ordered: Vec<_> = orders.into_iter().zip(all).collect();
+ // Stable: the others stay newest first.
+ ordered.sort_by_key(|(order, _)| match order {
+ Some((seq, digest)) => (false, std::cmp::Reverse(*seq), *digest),
+ None => (true, std::cmp::Reverse(0), [0; 32]),
+ });
+ all = ordered
+ .into_iter()
+ .map(|(_, candidate)| candidate)
+ .collect();
+ }
}
Ok(all)
}
@@ -1735,11 +1778,12 @@ mod tests {
)
}
- /// Of signed values written at once at one place, the highest `seq` is read,
- /// whichever was written last, and before anything unsigned; a write replaces them
- /// all.
+ /// Of signed values written at once at one place, where the policy asks for signed
+ /// values, the highest `seq` is read, whichever was written last, and before
+ /// anything unsigned; a write replaces them all. Without such a policy, the newest,
+ /// as always.
#[test]
- fn the_highest_seq_is_read() {
+ fn the_highest_seq_is_read_where_values_are_signed() {
let doc = |actor: &[u8]| crate::document::Document::new().with_actor(ActorId::from(actor));
let (mut ours, mut theirs, mut third) = (doc(b"a"), doc(b"b"), doc(b"c"));
// Ours: the older one, written after many operations, so that it is the newest.
@@ -1762,6 +1806,26 @@ mod tests {
})
.unwrap();
ours.merge(&mut theirs).unwrap();
+ assert_eq!(read_plain(&ours, &path("a")).unwrap(), Some(json!("old")));
+ // Any value at the policy's place asking for them, as written or signed.
+ let mut plain = ours.fork();
+ try_change(&mut plain, |doc| {
+ write_path(
+ doc,
+ &path("_continuum/access/policy"),
+ &json!({"version": 1, "values": "signed"}),
+ )
+ })
+ .unwrap();
+ assert_eq!(read_plain(&plain, &path("a")).unwrap(), Some(json!("new")));
+ try_change(&mut ours, |doc| {
+ write_path(
+ doc,
+ &path("_continuum/access/policy"),
+ &json!(envelope_of(&json!({"version": 1, "values": "signed"}), 0)),
+ )
+ })
+ .unwrap();
assert_eq!(read_plain(&ours, &path("a")).unwrap(), Some(json!("new")));
ours.merge(&mut third).unwrap();
assert_eq!(read_plain(&ours, &path("a")).unwrap(), Some(json!("new")));
@@ -1771,6 +1835,21 @@ mod tests {
.unwrap();
assert_eq!(read_candidates(&ours, &path("a")).unwrap().len(), 1);
assert_eq!(read_plain(&ours, &path("a")).unwrap(), Some(json!("after")));
+ // Another policy: the newest.
+ let mut open = third.fork();
+ open.merge(&mut theirs).unwrap();
+ try_change(&mut open, |doc| {
+ write_path(
+ doc,
+ &path("_continuum/access/policy"),
+ &json!({"version": 1}),
+ )
+ })
+ .unwrap();
+ assert_eq!(
+ read_plain(&open, &path("a")).unwrap(),
+ Some(json!("unsigned"))
+ );
}
/// An envelope reads as the value it holds, a signed `null` as nothing, anything