mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6a463712a4 |
No files matched your search
@@ -146,10 +146,14 @@ impl<L: Layout> Gdd<L> {
|
||||
// Carry the per-peer cursor + view settings so a `.gdd` reopened elsewhere restores the viewport.
|
||||
let session_state = SessionState {
|
||||
peer_id: self.session.peer(),
|
||||
user_id: self.session.user(),
|
||||
head_rev: self.session.head_rev(),
|
||||
last_broadcast_rev: self.session.last_broadcast_rev(),
|
||||
redo_stack: self.session.redo_stack().to_vec(),
|
||||
next_node_counter: self.session.next_node_counter(),
|
||||
last_hot_sequence: self.session.last_hot_sequence(),
|
||||
settled: self.session.settled_marks().clone(),
|
||||
clock: self.session.clock_counter(),
|
||||
view_settings: self.view_settings.clone(),
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
};
|
||||
|
||||
@@ -16,7 +16,7 @@ use document_container::backends::folder::FolderBackend;
|
||||
use document_container::{AnyContainer, AsyncContainer, ByteHolder};
|
||||
#[cfg(feature = "conversion")]
|
||||
use document_graph_storage::{CommitError, NodeMetadataSource};
|
||||
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session};
|
||||
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session, UserId};
|
||||
#[cfg(feature = "conversion")]
|
||||
use graphene_resource::LoadResource;
|
||||
use graphene_resource::ResourceHash;
|
||||
@@ -141,18 +141,19 @@ impl<L: Layout> Gdd<L> {
|
||||
let has_history = io::exists(&working, layout.history_basename(), codecs.history).await;
|
||||
|
||||
let peer = session_state.peer_id;
|
||||
let user = session_state.user_id;
|
||||
let mut session = match (has_registry, has_history) {
|
||||
(true, true) => {
|
||||
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
|
||||
let history = load_history(&working, &layout, codecs.history).await?;
|
||||
Session::load(peer, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
|
||||
Session::load(peer, user, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
|
||||
}
|
||||
(true, false) => {
|
||||
// Registry-only export: synthesize a history that reproduces this state.
|
||||
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
|
||||
Session::bootstrap_from_registry(peer, registry)?
|
||||
Session::bootstrap_from_registry(peer, user, registry)?
|
||||
}
|
||||
(false, _) => Session::replay_from_history(peer, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
|
||||
(false, _) => Session::replay_from_history(peer, user, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
|
||||
};
|
||||
|
||||
// Restore the published frontier (silent/published undo boundary) regardless of which load arm ran.
|
||||
@@ -160,6 +161,10 @@ impl<L: Layout> Gdd<L> {
|
||||
session.publish_up_to(rev);
|
||||
}
|
||||
|
||||
session.restore_hot_sequence(session_state.last_hot_sequence);
|
||||
session.restore_clock(session_state.clock);
|
||||
// Before the hot log replays, so a settled op in it is dropped rather than staged again.
|
||||
session.absorb_settled_marks(&session_state.settled);
|
||||
replay_hot_log(&working, &layout, codecs.hot_log, &mut session).await?;
|
||||
|
||||
Ok(Self {
|
||||
@@ -178,7 +183,11 @@ impl<L: Layout> Gdd<L> {
|
||||
let manifest = Manifest::new(document_uuid, editor_version, stdlib_version);
|
||||
let codecs = manifest.codecs;
|
||||
io::write_single(&working, layout.manifest_basename(), MANIFEST_CODEC, &manifest)?;
|
||||
let session_state = SessionState { peer_id: peer, ..Default::default() };
|
||||
let session_state = SessionState {
|
||||
peer_id: peer,
|
||||
user_id: UserId(peer.0),
|
||||
..Default::default()
|
||||
};
|
||||
io::write_single(&working, layout.session_basename(), codecs.session, &session_state)?;
|
||||
|
||||
let session = Session::with_peer(peer);
|
||||
|
||||
@@ -194,10 +194,14 @@ impl<L: Layout> Gdd<L> {
|
||||
fn persist_session_state(&mut self) -> Result<(), Error> {
|
||||
let state = SessionState {
|
||||
peer_id: self.session.peer(),
|
||||
user_id: self.session.user(),
|
||||
head_rev: self.session.head_rev(),
|
||||
last_broadcast_rev: self.session.last_broadcast_rev(),
|
||||
redo_stack: self.session.redo_stack().to_vec(),
|
||||
next_node_counter: self.session.next_node_counter(),
|
||||
last_hot_sequence: self.session.last_hot_sequence(),
|
||||
settled: self.session.settled_marks().clone(),
|
||||
clock: self.session.clock_counter(),
|
||||
view_settings: self.view_settings.clone(),
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
};
|
||||
@@ -205,12 +209,10 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Re-snapshot the materialized working registry to `registry.bin`. `Session::load` trusts the stored
|
||||
/// registry to match the persisted `head`, so any cursor move (undo/redo) that rewinds the working
|
||||
/// registry without retiring must re-persist it or a reopen would read a registry inconsistent with
|
||||
/// `head`. Synchronous and hot-path-safe (`write_non_blocking`).
|
||||
/// Re-snapshot the retired registry to `registry.bin`. `Session::load` trusts it to match the persisted `head`
|
||||
/// and replays the hot log on top, so it must hold no hot op, and any cursor move must re-persist it.
|
||||
fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
|
||||
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.registry())?;
|
||||
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.retired_registry())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//!
|
||||
//! Lives in `session.json`. Rewritten on retirement.
|
||||
|
||||
use document_graph_storage::{NetworkId, PeerId, Rev, Value};
|
||||
use document_graph_storage::{HotSequence, NetworkId, PeerId, Rev, SettledHotOps, UserId, Value};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
@@ -15,6 +15,10 @@ pub struct SessionState {
|
||||
/// tiebreaking and minting peer-scoped IDs.
|
||||
#[serde(default)]
|
||||
pub peer_id: PeerId,
|
||||
/// The person using this device, which the peer registers as, so authorship and undo follow the person
|
||||
/// across the peer ids they accumulate.
|
||||
#[serde(default)]
|
||||
pub user_id: UserId,
|
||||
/// Local-chain cursor. Points at the most recently applied retired delta, or `None` on an empty
|
||||
/// document (no commits yet).
|
||||
#[serde(default)]
|
||||
@@ -31,6 +35,10 @@ pub struct SessionState {
|
||||
/// collide on minted IDs.
|
||||
#[serde(default)]
|
||||
pub next_node_counter: u64,
|
||||
/// The sequence of the last hot op this peer authored, feeding [`document_graph_storage::HotOp::sequence`], so a
|
||||
/// reopen never reuses a spent sequence.
|
||||
#[serde(default)]
|
||||
pub last_hot_sequence: HotSequence,
|
||||
/// Per-peer view settings (PTZ, rulers, overlays, snapping, panel collapse). Local to the viewer,
|
||||
/// so kept out of the CRDT/history. Editor owns the keys/values (opaque `ui::doc::*` blobs).
|
||||
#[serde(default)]
|
||||
@@ -39,4 +47,12 @@ pub struct SessionState {
|
||||
/// Per-peer like [`view_settings`](Self::view_settings); opaque `ui::nav::*` / `ui::previewing` blobs.
|
||||
#[serde(default)]
|
||||
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, Value>>,
|
||||
/// Which hot ops are retired, so a late copy a peer re-sends after a reopen is dropped rather than retired a second
|
||||
/// time. About one sequence per author; runs only for ops in flight when saved.
|
||||
#[serde(default)]
|
||||
pub settled: SettledHotOps,
|
||||
/// The Lamport counter, so a reopen never mints a stamp already spent, even one no op in history or the hot log
|
||||
/// carries any more.
|
||||
#[serde(default)]
|
||||
pub clock: u64,
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{Codec, Error, GddV1, GddV1Layout, Layout, Manifest, io, manifest};
|
||||
use document_graph_storage::{HotOp, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
|
||||
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
|
||||
|
||||
fn empty_container() -> AnyContainer {
|
||||
AnyContainer::Memory(MemoryBackend::new())
|
||||
@@ -122,6 +122,7 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: HotSequence(1),
|
||||
};
|
||||
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
|
||||
|
||||
@@ -146,6 +147,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: HotSequence(1),
|
||||
};
|
||||
let late = HotOp {
|
||||
op: RegistryDelta::AddNetwork {
|
||||
@@ -153,6 +155,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 10, peer: PeerId(5) },
|
||||
sequence: HotSequence(2),
|
||||
};
|
||||
gdd.apply_hot_op(early).unwrap();
|
||||
gdd.apply_hot_op(late).unwrap();
|
||||
@@ -190,6 +193,7 @@ fn last_broadcast_rev_persists_across_reopen() {
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: HotSequence(1),
|
||||
};
|
||||
gdd.apply_hot_op(op).unwrap();
|
||||
let retired = gdd.retire(TimeStamp { counter: 1, peer: PeerId(5) }).unwrap_or_else(|error| panic!("retire failed: {error:?}"));
|
||||
@@ -596,11 +600,19 @@ fn first_commit_registers_peer_and_survives_reopen() {
|
||||
|
||||
gdd.commit_from_runtime(&network, &NoMetadata, &ResourceRegistry::new(), &HashMapResourceStorage::new())
|
||||
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
|
||||
assert_eq!(gdd.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "first commit registers the peer");
|
||||
assert_eq!(
|
||||
gdd.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
|
||||
Some(UserId(21)),
|
||||
"first commit registers the peer"
|
||||
);
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
|
||||
assert_eq!(reopened.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "registration survives reopen");
|
||||
assert_eq!(
|
||||
reopened.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
|
||||
Some(UserId(21)),
|
||||
"registration survives reopen"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -619,6 +631,7 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: HotSequence(1),
|
||||
};
|
||||
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
|
||||
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
// Staging a whole document after a recorded batch, and what a reopen must carry over.
|
||||
#![cfg(feature = "conversion")]
|
||||
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::{NoMetadata, PeerId, Registry};
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
|
||||
use graph_craft::{ProtoNodeIdentifier, concrete};
|
||||
use graphene_resource::ResourceRegistry;
|
||||
|
||||
fn network_with_one_node() -> NodeNetwork {
|
||||
let node = DocumentNode {
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
|
||||
call_argument: concrete!(()),
|
||||
..Default::default()
|
||||
};
|
||||
NodeNetwork {
|
||||
nodes: [(NodeId(1), node)].into_iter().collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A whole-document stage after a recorded batch stages nothing new: restating the batch would fail on the node it added.
|
||||
#[test]
|
||||
fn a_whole_document_stage_after_a_recorded_batch_stages_nothing_new() {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), 1, "ed".into(), "std".into()).unwrap();
|
||||
let store = HashMapResourceStorage::new();
|
||||
let resources = ResourceRegistry::new();
|
||||
gdd.stage_runtime_snapshot(&NodeNetwork::default(), &NoMetadata, &resources, &store)
|
||||
.expect("first whole-document stage");
|
||||
|
||||
let target = Registry::convert_from_runtime(&network_with_one_node(), &NoMetadata, &resources, PeerId(21)).unwrap();
|
||||
let ops = document_graph_storage::delta::compute_deltas(gdd.registry(), &target.registry);
|
||||
gdd.stage_constructed_ops(ops, &target.declaration_bytes, &store).expect("recorded batch");
|
||||
let hot_before = gdd.session().hot_log().len();
|
||||
|
||||
gdd.stage_runtime_snapshot(&network_with_one_node(), &NoMetadata, &resources, &store)
|
||||
.expect("the runtime already matches what was staged");
|
||||
assert_eq!(gdd.session().hot_log().len(), hot_before, "nothing new to stage");
|
||||
}
|
||||
|
||||
/// `registry.bin` is the retired snapshot the hot log replays onto, so an op still hot at save time must stay out of it.
|
||||
#[test]
|
||||
fn a_reopen_keeps_unretired_hot_ops_out_of_the_retired_snapshot() {
|
||||
use document_graph_storage::{AttributeDelta, HotOp, HotSequence, RegistryDelta, TimeStamp, Value};
|
||||
let set = |value: u32, counter: u64| HotOp {
|
||||
op: RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: AttributeDelta {
|
||||
key: "k".into(),
|
||||
value: Some(Value::from(serde_json::json!(value))),
|
||||
},
|
||||
},
|
||||
timestamp: TimeStamp { counter, peer: PeerId(22) },
|
||||
sequence: HotSequence(counter),
|
||||
};
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), 1, "ed".into(), "std".into()).unwrap();
|
||||
gdd.apply_hot_op(set(1, 1)).unwrap();
|
||||
gdd.apply_hot_op(set(2, 2)).unwrap();
|
||||
gdd.retire(TimeStamp { counter: 1, peer: PeerId(22) }).unwrap();
|
||||
|
||||
let retired = gdd.session().retired_registry().clone();
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
assert!(reopened.session().retired_registry().value_equal(&retired), "the hot op leaked into the retired snapshot");
|
||||
assert_eq!(reopened.session().hot_log().len(), 1);
|
||||
});
|
||||
}
|
||||
|
||||
/// A reopen continues this peer's clock and run of hot op sequences, with ops still hot and after they all retired,
|
||||
/// since a reused sequence would let a peer's settled marks drop the new op.
|
||||
#[test]
|
||||
fn a_reopen_continues_the_hot_op_sequence() {
|
||||
use document_graph_storage::{AttributeDelta, RegistryDelta, Value};
|
||||
let set = |value: u32| RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: AttributeDelta {
|
||||
key: "k".into(),
|
||||
value: Some(Value::from(serde_json::json!(value))),
|
||||
},
|
||||
};
|
||||
// Stages one op and returns the sequence it got.
|
||||
fn stage(gdd: &mut GddV1, op: RegistryDelta) -> u64 {
|
||||
gdd.stage_constructed_ops(vec![op], &Default::default(), &HashMapResourceStorage::new()).unwrap();
|
||||
gdd.session().hot_log().last().unwrap().sequence.0
|
||||
}
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(23), 1, "ed".into(), "std".into()).unwrap();
|
||||
stage(&mut gdd, set(1));
|
||||
let up_to = gdd.session().hot_log().last().unwrap().timestamp;
|
||||
gdd.retire(up_to).unwrap();
|
||||
let last = stage(&mut gdd, set(2));
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
assert_eq!(stage(&mut reopened, set(3)), last + 1);
|
||||
|
||||
let up_to = reopened.session().hot_log().last().unwrap().timestamp;
|
||||
reopened.retire(up_to).unwrap();
|
||||
let last = reopened.session().last_hot_sequence().0;
|
||||
let clock = reopened.session().clock_counter();
|
||||
let (working, layout) = reopened.into_storage();
|
||||
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
assert_eq!(reopened.session().clock_counter(), clock, "the clock carries over");
|
||||
assert_eq!(stage(&mut reopened, set(4)), last + 1);
|
||||
});
|
||||
}
|
||||
@@ -8,21 +8,42 @@ use std::collections::BTreeMap;
|
||||
/// keys live on `Node.inputs_attributes[i]`; per-network keys live on `Network.attributes`.
|
||||
pub mod attr;
|
||||
|
||||
/// A type-erased attribute value paired with the timestamp at which it was last set.
|
||||
/// A type-erased attribute value paired with the timestamp at which it was last set. A deleted key
|
||||
/// stays as a stamped tombstone, so an older write loses in either arrival order; readers see it as absent.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AttributeValue {
|
||||
pub value: Value,
|
||||
pub timestamp: TimeStamp,
|
||||
// No skipping: the registry is positional on disk.
|
||||
#[serde(default)]
|
||||
pub deleted: bool,
|
||||
}
|
||||
|
||||
impl AttributeValue {
|
||||
pub fn new(value: Value, timestamp: TimeStamp) -> Self {
|
||||
Self { value, timestamp }
|
||||
Self { value, timestamp, deleted: false }
|
||||
}
|
||||
|
||||
/// The tombstone of a key deleted at `timestamp`.
|
||||
pub fn deleted(timestamp: TimeStamp) -> Self {
|
||||
Self {
|
||||
value: Value::None,
|
||||
timestamp,
|
||||
deleted: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Attribute maps. Each entity carries an `attributes_timestamp`: when its map was last written whole, by an
|
||||
/// addition or a whole-list input write. A key absent from the map is deleted as of that stamp, so an older
|
||||
/// write is dropped and an older tombstone is redundant.
|
||||
pub type Attributes = BTreeMap<String, AttributeValue>;
|
||||
|
||||
/// The live entries of an attribute map: every key that is not a tombstone.
|
||||
pub fn live(attributes: &Attributes) -> impl Iterator<Item = (&String, &AttributeValue)> {
|
||||
attributes.iter().filter(|(_, value)| !value.deleted)
|
||||
}
|
||||
|
||||
/// Write helpers for `Attributes`.
|
||||
pub trait AttributesWrite {
|
||||
/// Inserts `value` under `key`.
|
||||
@@ -44,7 +65,7 @@ pub trait AttributesWrite {
|
||||
|
||||
impl AttributesWrite for Attributes {
|
||||
fn set(&mut self, key: &str, value: Value, timestamp: TimeStamp) {
|
||||
self.insert(key.to_string(), AttributeValue { value, timestamp });
|
||||
self.insert(key.to_string(), AttributeValue::new(value, timestamp));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,6 +87,6 @@ pub trait AttributesRead {
|
||||
|
||||
impl AttributesRead for Attributes {
|
||||
fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
|
||||
self.get(key).and_then(|v| from_value(&v.value).ok())
|
||||
self.get(key).filter(|v| !v.deleted).and_then(|v| from_value(&v.value).ok())
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,15 @@
|
||||
use crate::{
|
||||
AttributeValue, Attributes, AttributesWrite, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value,
|
||||
attr, compute_rev,
|
||||
AttributeValue, Attributes, AttributesWrite, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Prior, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId,
|
||||
Value, attr, compute_rev,
|
||||
};
|
||||
use graphene_resource::ResourceHash;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Content-addressed delta: `id` is `blake3_128(parents, author, timestamp, delta_type)`.
|
||||
///
|
||||
/// `reverse` is state-dependent undo bookkeeping (it captures pre-state at the moment the forward
|
||||
/// op was applied), so it's serialized for storage but excluded from the identity hash — two peers
|
||||
/// observing the same forward delta against different local states would otherwise compute
|
||||
/// different Revs for the same logical op.
|
||||
/// `reverse` is state-dependent undo bookkeeping (what the op overwrote, captured as it applied), so it's
|
||||
/// serialized for storage but excluded from the identity hash: two peers applying the same forward delta to
|
||||
/// different local states would otherwise compute different Revs for the same logical op.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Delta {
|
||||
pub id: Rev,
|
||||
@@ -19,16 +18,22 @@ pub struct Delta {
|
||||
pub author: PeerId,
|
||||
pub timestamp: TimeStamp,
|
||||
pub kind: RegistryDelta,
|
||||
pub reverse: RegistryDelta,
|
||||
/// What every slot `kind` wrote held before it, stamps included, in write order. See [`Prior`].
|
||||
pub reverse: Vec<Prior>,
|
||||
/// Local, mutable annotations on this commit (interaction-end marker, future commit messages / labels).
|
||||
/// Deliberately excluded from `compute_rev`: relabeling a commit must not change its content-addressed
|
||||
/// identity, and two peers annotating the same op differently must still dedup to one `Rev`.
|
||||
#[serde(default)]
|
||||
pub attributes: Attributes,
|
||||
/// When the delta entered history, in Unix milliseconds by the clock of the peer that retired it; display only,
|
||||
/// and outside the rev like `attributes`. Zero means unrecorded, saving the tag byte an `Option` costs per delta;
|
||||
/// read it through [`retired_at`](Self::retired_at). Last, since the history codec is positional.
|
||||
#[serde(default)]
|
||||
pub(crate) retired_at_ms: u64,
|
||||
}
|
||||
|
||||
impl Delta {
|
||||
pub fn new(parent: Option<Rev>, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: RegistryDelta) -> Self {
|
||||
pub fn new(parent: Option<Rev>, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: Vec<Prior>) -> Self {
|
||||
let id = compute_rev(parent, author, timestamp, &kind);
|
||||
Self {
|
||||
id,
|
||||
@@ -38,6 +43,7 @@ impl Delta {
|
||||
kind,
|
||||
reverse,
|
||||
attributes: Attributes::default(),
|
||||
retired_at_ms: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,9 +61,10 @@ impl Delta {
|
||||
parent,
|
||||
author,
|
||||
timestamp,
|
||||
reverse: kind.clone(),
|
||||
reverse: Vec::new(),
|
||||
kind,
|
||||
attributes: Attributes::default(),
|
||||
retired_at_ms: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,6 +86,11 @@ impl Delta {
|
||||
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == Value::Bool(true))
|
||||
}
|
||||
|
||||
/// When the delta entered history in wall-clock milliseconds, if the peer that retired it recorded it.
|
||||
pub fn retired_at(&self) -> Option<u64> {
|
||||
(self.retired_at_ms != 0).then_some(self.retired_at_ms)
|
||||
}
|
||||
|
||||
/// The content-addressed `Rev` this delta's identity fields hash to. Equals `id` for a delta built
|
||||
/// via `new`/`merge`; differs only if `id` was tampered with or the hash derivation changed.
|
||||
pub fn recomputed_id(&self) -> Rev {
|
||||
@@ -101,8 +113,7 @@ pub enum RegistryDelta {
|
||||
id: NodeId,
|
||||
node: Node,
|
||||
},
|
||||
/// `snapshot` lets the reverse `AddNode` rebuild without reading the (already-removed) node from
|
||||
/// the registry, mirroring `RemoveNetwork`.
|
||||
/// `snapshot` is the node as removed, which folds in like any write so a removal of a node never seen still lands.
|
||||
RemoveNode {
|
||||
id: NodeId,
|
||||
snapshot: Node,
|
||||
@@ -155,13 +166,12 @@ pub enum RegistryDelta {
|
||||
id: NetworkId,
|
||||
network: Network,
|
||||
},
|
||||
/// `snapshot` lets the reverse delta rebuild without re-walking history.
|
||||
/// `snapshot` is the network as removed; see [`RemoveNode`](Self::RemoveNode).
|
||||
RemoveNetwork {
|
||||
id: NetworkId,
|
||||
snapshot: Network,
|
||||
},
|
||||
/// Register a whole resource entry at once. Overwrites any existing entry for `id`; the reverse
|
||||
/// of `RemoveResource`, the way `AddNetwork` pairs with `RemoveNetwork`.
|
||||
/// Register a whole resource entry at once, the way `AddNetwork` pairs with `RemoveNetwork`.
|
||||
AddResource {
|
||||
id: ResourceId,
|
||||
entry: ResourceEntry,
|
||||
@@ -190,9 +200,8 @@ pub enum RegistryDelta {
|
||||
id: ResourceId,
|
||||
key: SourceKey,
|
||||
},
|
||||
/// Append-only registration of a device's `PeerId` against its owning `UserId`.
|
||||
/// First write wins; conflicting re-registration errors. Duplicate identical registration
|
||||
/// is a no-op. Not LWW — the mapping is forever.
|
||||
/// Registers a device's `PeerId` to the `UserId` behind it. LWW per peer, so a device that changes person
|
||||
/// registers again and the newest registration wins wherever it lands.
|
||||
RegisterPeer {
|
||||
peer: PeerId,
|
||||
user: UserId,
|
||||
@@ -207,6 +216,8 @@ pub enum RegistryDelta {
|
||||
Merge {
|
||||
extra_parents: Vec<Rev>,
|
||||
},
|
||||
/// The last op of its author's transaction. Changes nothing, and retirement drops it.
|
||||
EndTransaction,
|
||||
// Allow for future delta types without a model change
|
||||
Other(Value),
|
||||
}
|
||||
@@ -218,31 +229,39 @@ pub struct AttributeDelta {
|
||||
pub value: Option<Value>,
|
||||
}
|
||||
|
||||
pub(crate) fn reverse_attribute_delta(delta: &AttributeDelta, attributes: &Attributes) -> AttributeDelta {
|
||||
AttributeDelta {
|
||||
key: delta.key.clone(),
|
||||
value: attributes.get(&delta.key).map(|previous| previous.value.clone()),
|
||||
/// Lands a single-key write. `floor` is the map's `attributes_timestamp`; see [`Attributes`]. A deletion
|
||||
/// leaves a tombstone.
|
||||
pub(crate) fn apply_attribute_delta(delta: AttributeDelta, timestamp: TimeStamp, attributes: &mut Attributes, floor: TimeStamp) {
|
||||
let AttributeDelta { key, value } = delta;
|
||||
let decided = attributes.get(&key).map_or(floor, |existing| existing.timestamp);
|
||||
if timestamp <= decided {
|
||||
return;
|
||||
}
|
||||
let entry = match value {
|
||||
Some(value) => AttributeValue::new(value, timestamp),
|
||||
None => AttributeValue::deleted(timestamp),
|
||||
};
|
||||
attributes.insert(key, entry);
|
||||
}
|
||||
|
||||
pub(crate) fn apply_attribute_delta(delta: AttributeDelta, timestamp: TimeStamp, force: bool, attributes: &mut Attributes) {
|
||||
let AttributeDelta { key, value } = delta;
|
||||
match value {
|
||||
Some(value) => match attributes.entry(key) {
|
||||
std::collections::btree_map::Entry::Occupied(mut entry) => {
|
||||
if force || timestamp > entry.get().timestamp {
|
||||
entry.insert(AttributeValue { value, timestamp });
|
||||
}
|
||||
}
|
||||
std::collections::btree_map::Entry::Vacant(entry) => {
|
||||
entry.insert(AttributeValue { value, timestamp });
|
||||
}
|
||||
},
|
||||
None => {
|
||||
let should_remove = force || attributes.get(&key).is_none_or(|existing| timestamp > existing.timestamp);
|
||||
if should_remove {
|
||||
attributes.remove(&key);
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_missing_retirement_time_costs_what_a_zero_costs_and_round_trips() {
|
||||
let base = Delta::new(None, PeerId(1), TimeStamp { counter: 1, peer: PeerId(1) }, RegistryDelta::EndTransaction, Vec::new());
|
||||
let mut stamped = base.clone();
|
||||
stamped.retired_at_ms = 1_790_000_000_000;
|
||||
|
||||
let bare_base = postcard::to_allocvec(&base).expect("encode");
|
||||
let bare_stamped = postcard::to_allocvec(&stamped).expect("encode");
|
||||
// Only the integer's varint differs: one byte for zero, six for today's milliseconds, no tag byte in either.
|
||||
assert_eq!(bare_stamped.len() - bare_base.len(), postcard::to_allocvec(&1_790_000_000_000u64).unwrap().len() - 1);
|
||||
|
||||
let decoded: Delta = postcard::from_bytes(&bare_stamped).expect("decode");
|
||||
assert_eq!(decoded.retired_at(), Some(1_790_000_000_000));
|
||||
let decoded: Delta = postcard::from_bytes(&bare_base).expect("decode");
|
||||
assert_eq!(decoded.retired_at(), None);
|
||||
}
|
||||
}
|
||||
@@ -166,14 +166,14 @@ fn diff_resource_entry(id: ResourceId, from: &ResourceEntry, to: &ResourceEntry,
|
||||
deltas.push(RegistryDelta::SetResourceHash { id, hash: to.hash });
|
||||
}
|
||||
|
||||
for (key, _) in &from.sources {
|
||||
for (key, _) in from.live_sources() {
|
||||
if to.source(key).is_none() {
|
||||
deltas.push(RegistryDelta::RemoveSource { id, key: *key });
|
||||
}
|
||||
}
|
||||
|
||||
// Compare source bodies only; the per-source timestamp is derived from the diff, not part of it.
|
||||
for (key, to_source) in &to.sources {
|
||||
for (key, to_source) in to.live_sources() {
|
||||
if from.source(key).is_none_or(|from_source| from_source.source != to_source.source) {
|
||||
deltas.push(RegistryDelta::AddSource {
|
||||
id,
|
||||
@@ -196,15 +196,15 @@ fn nodes_have_same_implementation(a: &Node, b: &Node) -> bool {
|
||||
fn compute_attribute_deltas(from: &crate::Attributes, to: &crate::Attributes) -> Vec<AttributeDelta> {
|
||||
let mut deltas = Vec::new();
|
||||
|
||||
for key in from.keys() {
|
||||
if !to.contains_key(key) {
|
||||
for (key, _) in crate::attributes::live(from) {
|
||||
if to.get(key).is_none_or(|value| value.deleted) {
|
||||
deltas.push(AttributeDelta { key: key.clone(), value: None });
|
||||
}
|
||||
}
|
||||
|
||||
// Compare by `value` only; the per-entry `timestamp` is derived from the diff, not part of it.
|
||||
for (key, to_value) in to {
|
||||
if from.get(key).is_none_or(|from_value| from_value.value != to_value.value) {
|
||||
for (key, to_value) in crate::attributes::live(to) {
|
||||
if from.get(key).is_none_or(|from_value| from_value.deleted || from_value.value != to_value.value) {
|
||||
deltas.push(AttributeDelta {
|
||||
key: key.clone(),
|
||||
value: Some(to_value.value.clone()),
|
||||
@@ -287,6 +287,7 @@ mod tests {
|
||||
input: NodeInput::Import { index: 0 },
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
attributes: Attributes::new(),
|
||||
attributes_timestamp: TimeStamp::ORIGIN,
|
||||
});
|
||||
|
||||
let deltas = compute_deltas(&from, &to);
|
||||
@@ -340,6 +341,7 @@ mod tests {
|
||||
crate::AttributeValue {
|
||||
value: Value::Str("old".into()),
|
||||
timestamp: stamp(0),
|
||||
deleted: false,
|
||||
},
|
||||
);
|
||||
from.node_instances.insert(NodeId(42), node);
|
||||
@@ -350,6 +352,7 @@ mod tests {
|
||||
crate::AttributeValue {
|
||||
value: Value::Str("new".into()),
|
||||
timestamp: stamp(1),
|
||||
deleted: false,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -375,6 +378,7 @@ mod tests {
|
||||
crate::AttributeValue {
|
||||
value: Value::Str("value".into()),
|
||||
timestamp: stamp(1),
|
||||
deleted: false,
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -1,23 +1,29 @@
|
||||
use std::collections::btree_map::Entry;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::hash::Hash;
|
||||
|
||||
use crate::{
|
||||
CrdtError, Delta, ExportSlot, History, HotOp, LamportClock, MAX_EXPORT_SLOTS, NetworkId, NodeId, NodeInput, PeerId, Registry, RegistryDelta, ResourceEntry, Rev, SourceValue, TimeStamp, Value,
|
||||
apply_attribute_delta, reverse_attribute_delta,
|
||||
Attributes, CrdtError, Delta, ExportSlot, History, HotOp, HotSequence, Implementation, InputSlot, LamportClock, MAX_EXPORT_SLOTS, MAX_INPUT_SLOTS, Network, NetworkId, Node, NodeId, NodeInput,
|
||||
PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, Rev, SettledHotOps, SourceValue, TimeStamp, Tombstone, UserId, apply_attribute_delta,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Document {
|
||||
/// Working registry: retired state with the current hot ops applied on top. This is what live
|
||||
/// reads and `registry()` observe, and what undo/redo force-apply against.
|
||||
/// reads and `registry()` observe.
|
||||
pub(crate) working_registry: Registry,
|
||||
/// Live broadcast stream, applied to the `working_registry` on receive, GC'd at retirement.
|
||||
/// Persisted for crash recovery so in-flight unretired work survives editor restarts.
|
||||
pub(crate) hot_log: Vec<HotOp>,
|
||||
/// The stamps of the hot log's ops, so a re-announced op is recognised without a scan.
|
||||
pub(crate) hot_timestamps: HashSet<TimeStamp>,
|
||||
/// Which hot ops are retired into history, so a late copy is dropped;
|
||||
/// retired deltas keep no link back to their hot ops.
|
||||
pub(crate) settled: SettledHotOps,
|
||||
/// The registry as of the last retirement, with no un-retired hot ops applied. Retirement computes
|
||||
/// each delta's `reverse` against this (so LWW reverses capture the true pre-op value, not the
|
||||
/// hot-polluted working state) and advances it, stamping fields at the fresh `T_retire`. Kept equal
|
||||
/// to `registry` *by value* whenever the hot log is empty (undo/redo resync it after moving the
|
||||
/// cursor), but field timestamps can differ: retirement bumps the snapshot's to `T_retire` while the
|
||||
/// working registry keeps the staging-time timestamps. Benign while the local monotonic clock makes
|
||||
/// new edits win
|
||||
/// hot-polluted working state) and advances it. It equals the working registry whenever the hot log is
|
||||
/// empty.
|
||||
pub(crate) retired_snapshot: Registry,
|
||||
/// User's cursor in their local history chain. `None` on an empty document (no commits yet).
|
||||
pub(crate) head: Option<Rev>,
|
||||
@@ -28,17 +34,40 @@ pub struct Document {
|
||||
pub(crate) redo_stack: Vec<Rev>,
|
||||
pub(crate) clock: LamportClock,
|
||||
pub(crate) peer: PeerId,
|
||||
/// Latest retired commit on the local chain that has been broadcast to at least one peer.
|
||||
/// Commits after this can be rewritten silently; commits at or before this are published
|
||||
/// and require forward reverse-delta ops to undo. `None` means nothing broadcast yet.
|
||||
/// The person behind this peer; what `RegisterPeer` records for it.
|
||||
pub(crate) user: UserId,
|
||||
/// Latest retired commit on the local chain that a peer holds. Commits after it can be undone silently; commits up
|
||||
/// to it are published and stay. `None` means nothing published yet.
|
||||
pub(crate) last_broadcast_rev: Option<Rev>,
|
||||
/// Shared-monotonic counter feeding `next_node_id`. Bumped on every mint regardless of which
|
||||
/// peer is calling; collision avoidance comes from hashing `(self.peer, counter)`, so two peers
|
||||
/// reading the same counter still produce distinct IDs.
|
||||
pub(crate) next_node_counter: u64,
|
||||
/// Counts this peer's own hot ops, so each carries its position in a gap-free run. See [`HotOp::sequence`].
|
||||
pub(crate) last_hot_sequence: HotSequence,
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// An empty document for `peer`, at the origin of its clock.
|
||||
pub(crate) fn empty(peer: PeerId, user: UserId) -> Self {
|
||||
Self {
|
||||
working_registry: Registry::default(),
|
||||
retired_snapshot: Registry::default(),
|
||||
history: History::new(),
|
||||
hot_log: Vec::new(),
|
||||
hot_timestamps: HashSet::new(),
|
||||
settled: SettledHotOps::default(),
|
||||
head: None,
|
||||
redo_stack: Vec::new(),
|
||||
clock: LamportClock::new(peer),
|
||||
peer,
|
||||
user,
|
||||
last_broadcast_rev: None,
|
||||
next_node_counter: 0,
|
||||
last_hot_sequence: HotSequence::NONE,
|
||||
}
|
||||
}
|
||||
|
||||
/// Mint a fresh `NodeId` scoped to this document's peer. The 64-bit ID is `blake3(peer, counter)`
|
||||
/// truncated; the counter is shared across peers and persisted with the document.
|
||||
pub fn next_node_id(&mut self) -> NodeId {
|
||||
@@ -51,75 +80,83 @@ impl Document {
|
||||
NodeId(u64::from_le_bytes(truncated))
|
||||
}
|
||||
|
||||
pub(crate) fn restore_node_from_history(&mut self, target: RegistryTarget, node_id: NodeId) -> Result<(), CrdtError> {
|
||||
let delta = self
|
||||
.find_in_ancestry(|d| matches!(d.reverse, RegistryDelta::AddNode { id, .. } if id == node_id))
|
||||
.ok_or(CrdtError::NodeNotInHistory(node_id))?;
|
||||
self.revert_delta(target, delta)
|
||||
}
|
||||
|
||||
pub(crate) fn restore_network_from_history(&mut self, target: RegistryTarget, network_id: NetworkId) -> Result<(), CrdtError> {
|
||||
// Find the Delta whose forward op removed this network. Its `reverse` is `AddNetwork`,
|
||||
// which is what we want to re-apply.
|
||||
let delta = self
|
||||
.find_in_ancestry(|d| matches!(d.reverse, RegistryDelta::AddNetwork { id, .. } if id == network_id))
|
||||
.ok_or(CrdtError::NetworkNotInHistory(network_id))?;
|
||||
self.revert_delta(target, delta)
|
||||
}
|
||||
|
||||
/// Search every delta reachable from `head` (following all parents, including a merge's
|
||||
/// `extra_parents`) for the first matching `predicate`, breadth-first. Resurrection needs full
|
||||
/// ancestry reachability, so a node added only on a merged-in branch is still found.
|
||||
fn find_in_ancestry(&self, predicate: impl Fn(&Delta) -> bool) -> Option<Delta> {
|
||||
let mut queue: std::collections::VecDeque<Rev> = self.head.into_iter().collect();
|
||||
let mut seen: std::collections::HashSet<Rev> = self.head.into_iter().collect();
|
||||
while let Some(rev) = queue.pop_front() {
|
||||
let Some(delta) = self.history.get(rev) else { continue };
|
||||
if predicate(delta) {
|
||||
return Some(delta.clone());
|
||||
}
|
||||
for parent in delta.all_parents() {
|
||||
if seen.insert(parent) {
|
||||
queue.push_back(parent);
|
||||
}
|
||||
}
|
||||
/// Put back what a delta overwrote in the retired snapshot (silent-zone undo), leaving it as folding history up
|
||||
/// to the delta's parent would. The working registry follows: it is the same registry when nothing is hot.
|
||||
pub(crate) fn revert_delta(&mut self, delta: &Delta) {
|
||||
crate::prior::restore(&mut self.retired_snapshot, &delta.reverse);
|
||||
if self.hot_log.is_empty() {
|
||||
crate::prior::restore(&mut self.working_registry, &delta.reverse);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Apply a delta's `reverse` as the new forward op (silent-zone undo). Force-applied: structural
|
||||
/// ops are idempotent, and LWW arms assign the reverse value unconditionally even though it carries
|
||||
/// the same timestamp as the forward op it undoes.
|
||||
pub(crate) fn revert_delta(&mut self, target: RegistryTarget, mut delta: Delta) -> Result<(), CrdtError> {
|
||||
for parent in delta.all_parents() {
|
||||
if !self.history.contains(parent) {
|
||||
return Err(CrdtError::NotFoundInHistory(parent));
|
||||
}
|
||||
}
|
||||
std::mem::swap(&mut delta.kind, &mut delta.reverse);
|
||||
self.apply_op_with(target, delta.kind, delta.timestamp, ApplyMode::Force)
|
||||
}
|
||||
|
||||
/// Apply a live broadcast op. Updates the registry via LWW and appends to the hot log.
|
||||
/// Doesn't touch history or `head` — hot ops are transient.
|
||||
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
||||
self.apply_op(hot_op.op.clone(), hot_op.timestamp)?;
|
||||
/// Apply a locally staged op: LWW into the registry, append to the hot log, leave history and `head`
|
||||
/// alone. Skips the retirement check, so staging never silently drops local work; outside callers use
|
||||
/// [`Session::apply_hot_op`](crate::Session::apply_hot_op).
|
||||
pub(crate) fn apply_hot_op(&mut self, hot_op: HotOp, mode: ApplyMode) -> Result<(), CrdtError> {
|
||||
self.apply_op_with(RegistryTarget::Working, hot_op.op.clone(), hot_op.timestamp, mode)?;
|
||||
self.hot_timestamps.insert(hot_op.timestamp);
|
||||
self.hot_log.push(hot_op);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Replay a hot op recovered from persisted state. Idempotent on structural ops so that
|
||||
/// re-applying an op whose effect is already reflected in the registry is a no-op rather
|
||||
/// than an error.
|
||||
/// Replay a hot op recovered from persisted state or received from a peer. Replaying one already
|
||||
/// reflected in the registry changes nothing.
|
||||
pub fn replay_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
||||
// Re-adding a settled op would leave a hot log entry no retirement will ever name.
|
||||
if self.settled.covers(hot_op.id()) {
|
||||
return Ok(());
|
||||
}
|
||||
// A re-announcement of a held op must not become a second copy.
|
||||
if self.hot_timestamps.contains(&hot_op.timestamp) {
|
||||
return Ok(());
|
||||
}
|
||||
// Our own ops raise the sequence counter too, should the persisted one lag behind the hot log.
|
||||
if hot_op.timestamp.peer == self.peer {
|
||||
self.last_hot_sequence = self.last_hot_sequence.max(hot_op.sequence);
|
||||
}
|
||||
|
||||
self.apply_op_idempotent(hot_op.op.clone(), hot_op.timestamp)?;
|
||||
self.hot_timestamps.insert(hot_op.timestamp);
|
||||
self.hot_log.push(hot_op);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Apply a retired commit. Idempotent on structural ops (AddNode/AddNetwork on existing
|
||||
/// targets, Remove on missing ones) since hot ops already produced the structural state.
|
||||
/// The point is to bump field timestamps to T_retire via the LWW arms.
|
||||
/// Take on a peer's marks as well as this peer's. Returns whether a hot op was dropped.
|
||||
pub(crate) fn absorb_settled(&mut self, remote: &SettledHotOps) -> bool {
|
||||
self.settled.absorb(remote);
|
||||
self.drop_settled_hot_ops()
|
||||
}
|
||||
|
||||
/// Bring the stamp index back in line after the hot log was filtered as a whole.
|
||||
pub(crate) fn resync_hot_timestamps(&mut self) {
|
||||
self.hot_timestamps = self.hot_log.iter().map(|hot_op| hot_op.timestamp).collect();
|
||||
}
|
||||
|
||||
/// Re-derive the working registry as the retired snapshot plus every hot op, for a change that cannot
|
||||
/// be applied in place. O(N + L), for rare paths only.
|
||||
pub(crate) fn rebuild_working(&mut self) {
|
||||
self.working_registry = self.retired_snapshot.clone();
|
||||
for hot_op in std::mem::take(&mut self.hot_log) {
|
||||
// Nothing is deferred, so this cannot fail on a referent; don't strand the op over anything else.
|
||||
let _ = self.apply_op_idempotent(hot_op.op.clone(), hot_op.timestamp);
|
||||
self.hot_log.push(hot_op);
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop settled hot ops and re-derive the working registry without them; their effect comes back with their deltas.
|
||||
fn drop_settled_hot_ops(&mut self) -> bool {
|
||||
let before = self.hot_log.len();
|
||||
let settled = &self.settled;
|
||||
self.hot_log.retain(|hot_op| !settled.covers(hot_op.id()));
|
||||
let dropped = self.hot_log.len() != before;
|
||||
if dropped {
|
||||
self.resync_hot_timestamps();
|
||||
self.rebuild_working();
|
||||
}
|
||||
dropped
|
||||
}
|
||||
|
||||
/// Apply a retired commit and record it in history.
|
||||
pub fn apply_delta(&mut self, delta: Delta) -> Result<(), CrdtError> {
|
||||
for parent in delta.all_parents() {
|
||||
if !self.history.contains(parent) {
|
||||
@@ -139,340 +176,503 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
fn registry_ref(&self, target: RegistryTarget) -> &Registry {
|
||||
pub(crate) fn registry_ref(&self, target: RegistryTarget) -> &Registry {
|
||||
match target {
|
||||
RegistryTarget::Working => &self.working_registry,
|
||||
RegistryTarget::Snapshot => &self.retired_snapshot,
|
||||
}
|
||||
}
|
||||
|
||||
/// New local/remote op against the working registry: add ops error on duplicate targets and
|
||||
/// `Change*` ops error on a missing target, while remove ops no-op when the target is already
|
||||
/// absent; LWW arms keep the newer-timestamp value (strict `>`). The common entry point for edits.
|
||||
/// A fresh local edit against the working registry; see [`ApplyMode::Live`].
|
||||
#[cfg(test)]
|
||||
pub(crate) fn apply_op(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
|
||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Live)
|
||||
}
|
||||
|
||||
/// Replay/retire against the working registry: structural ops skip duplicate/missing targets (the
|
||||
/// state is already present from hot ops or a prior snapshot); LWW arms still gate on strict `>`.
|
||||
/// An op from a peer or from persisted state, against the working registry.
|
||||
pub(crate) fn apply_op_idempotent(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
|
||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Idempotent)
|
||||
}
|
||||
|
||||
/// Silent-zone undo/redo rewind against the working registry: structural ops are idempotent, and
|
||||
/// LWW arms assign unconditionally. We own the single-writer chain here, so the precomputed reverse
|
||||
/// (undo) or forward (redo) value is authoritative even though its timestamp ties what it replaces.
|
||||
pub(crate) fn force_apply_op(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
|
||||
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Force)
|
||||
}
|
||||
|
||||
/// Applies one op. Every field of the registry is last-writer-wins on a timestamp, whether an entity
|
||||
/// exists included, so the registry folds to the same values whatever order the ops land in:
|
||||
///
|
||||
/// - An addition writes every field of the entity at its stamp, and is evidence it exists from then.
|
||||
/// - A removal is evidence the entity does not exist from its stamp. Its content stays as a tombstone,
|
||||
/// and the removal's snapshot folds in like any other write.
|
||||
/// - A write, or a reference from another entity's op, is evidence the entity exists at its stamp, so it
|
||||
/// revives an older removal; an older write lands on the tombstone, for a later revival to see.
|
||||
/// - A write to an entity never seen lands on a placeholder until its addition arrives; see [`write()`].
|
||||
pub(crate) fn apply_op_with(&mut self, target: RegistryTarget, op: RegistryDelta, timestamp: TimeStamp, mode: ApplyMode) -> Result<(), CrdtError> {
|
||||
// Advance the local clock past every observed op, including ones that subsequently no-op or
|
||||
// error. Observation is about causality knowledge, not about whether the op took effect.
|
||||
self.clock.observe(timestamp);
|
||||
|
||||
// Structural ops skip (rather than error) on duplicate/missing targets when not a fresh edit;
|
||||
// LWW arms assign unconditionally only under `Force`.
|
||||
let idempotent = mode != ApplyMode::Live;
|
||||
let force = mode == ApplyMode::Force;
|
||||
|
||||
// Resurrect any concurrently-removed targets the op references before binding the registry
|
||||
// (resurrection re-borrows `self` via history), so the mutation below holds one `registry` ref.
|
||||
self.ensure_referenced_exist(target, &op)?;
|
||||
let live = mode == ApplyMode::Live;
|
||||
|
||||
let registry = self.registry_mut(target);
|
||||
match op {
|
||||
RegistryDelta::AddNode { id, node } => {
|
||||
if registry.node_instances.contains_key(&id) {
|
||||
if idempotent {
|
||||
// Hot ops already created this node; skip rather than error.
|
||||
return Ok(());
|
||||
}
|
||||
if live && registry.node_instances.contains_key(&id) {
|
||||
return Err(CrdtError::NodeAlreadyExists(id));
|
||||
}
|
||||
registry.node_instances.insert(id, node);
|
||||
write_network(registry, node.network, timestamp, mode, |_| Ok(()))?;
|
||||
add(&mut registry.node_instances, &mut registry.removed_nodes, id, node, timestamp);
|
||||
}
|
||||
RegistryDelta::RemoveNode { id, .. } => {
|
||||
registry.node_instances.remove(&id);
|
||||
RegistryDelta::RemoveNode { id, snapshot } => {
|
||||
remove(&mut registry.node_instances, &mut registry.removed_nodes, id, snapshot, timestamp);
|
||||
}
|
||||
RegistryDelta::SetNodeInputs { id, inputs } => {
|
||||
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
// The list is one value rather than independently mergeable slots, so the newest slot stands in
|
||||
// for a timestamp the list itself does not carry, and an older write is dropped whole.
|
||||
let newest = node.inputs.iter().map(|slot| slot.timestamp).max().unwrap_or(TimeStamp::ORIGIN);
|
||||
if force || timestamp > newest {
|
||||
// The slots arrive carrying the placeholder timestamp they were built with, so they take this
|
||||
// op's instead. Leaving the placeholder would reset every slot to the origin and make each
|
||||
// later per-slot gate vacuously true, letting a stale write win.
|
||||
node.inputs = inputs.into_iter().map(|slot| crate::InputSlot { timestamp, ..slot }).collect();
|
||||
RegistryDelta::SetNodeInputs { id, mut inputs } => {
|
||||
inputs.iter_mut().for_each(|slot| stamp_slot(slot, timestamp));
|
||||
let referenced: Vec<NodeId> = inputs
|
||||
.iter()
|
||||
.filter_map(|slot| match slot.input {
|
||||
NodeInput::Node { id, .. } => Some(id),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
ensure_seen(registry, &referenced, mode)?;
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
merge_inputs(node, inputs, timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
for referenced in referenced {
|
||||
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
|
||||
}
|
||||
}
|
||||
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
|
||||
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
let input = node.inputs.get_mut(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
|
||||
if force || timestamp > input.timestamp {
|
||||
input.input = new_input;
|
||||
input.timestamp = timestamp;
|
||||
let referenced = match new_input {
|
||||
NodeInput::Node { id, .. } => Some(id),
|
||||
_ => None,
|
||||
};
|
||||
ensure_seen(registry, referenced.as_slice(), mode)?;
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) };
|
||||
if timestamp > input.timestamp {
|
||||
input.input = new_input;
|
||||
input.timestamp = timestamp;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
if let Some(referenced) = referenced {
|
||||
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
|
||||
}
|
||||
}
|
||||
RegistryDelta::SetNodeImplementation { id, implementation } => {
|
||||
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
if force || timestamp > node.implementation_timestamp {
|
||||
node.implementation = implementation;
|
||||
node.implementation_timestamp = timestamp;
|
||||
ensure_seen(registry, &[id], mode)?;
|
||||
if let Implementation::Network(network) = implementation {
|
||||
write_network(registry, network, timestamp, mode, |_| Ok(()))?;
|
||||
}
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
if timestamp > node.implementation_timestamp {
|
||||
node.implementation = implementation;
|
||||
node.implementation_timestamp = timestamp;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
RegistryDelta::ChangeNodeAttribute { id, delta } => {
|
||||
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
apply_attribute_delta(delta, timestamp, force, &mut node.attributes);
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
apply_attribute_delta(delta, timestamp, &mut node.attributes, node.attributes_timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => {
|
||||
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
let input = node.inputs.get_mut(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
|
||||
apply_attribute_delta(delta, timestamp, force, &mut input.attributes);
|
||||
write_node(registry, id, timestamp, mode, |node| {
|
||||
let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) };
|
||||
apply_attribute_delta(delta, timestamp, &mut input.attributes, input.attributes_timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
RegistryDelta::SetNetworkExport { id, index, export } => {
|
||||
let net = registry.networks.get_mut(&id).ok_or(CrdtError::NetworkDoesNotExist(id))?;
|
||||
let slot_idx = index as usize;
|
||||
|
||||
if slot_idx >= net.exports.len() {
|
||||
if slot_idx >= MAX_EXPORT_SLOTS {
|
||||
return Err(CrdtError::ExportSlotOutOfBounds(index));
|
||||
let referenced = match export {
|
||||
Some(NodeInput::Node { id, .. }) => Some(id),
|
||||
_ => None,
|
||||
};
|
||||
ensure_seen(registry, referenced.as_slice(), mode)?;
|
||||
write_network(registry, id, timestamp, mode, |net| {
|
||||
let slot_idx = index as usize;
|
||||
if slot_idx >= net.exports.len() {
|
||||
if slot_idx >= MAX_EXPORT_SLOTS {
|
||||
return Err(CrdtError::ExportSlotOutOfBounds(index));
|
||||
}
|
||||
net.exports.resize(slot_idx + 1, ExportSlot::default());
|
||||
}
|
||||
net.exports.resize(
|
||||
slot_idx + 1,
|
||||
ExportSlot {
|
||||
target: None,
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let existing = &mut net.exports[slot_idx];
|
||||
if force || timestamp > existing.timestamp {
|
||||
existing.target = export;
|
||||
existing.timestamp = timestamp;
|
||||
let existing = &mut net.exports[slot_idx];
|
||||
if timestamp > existing.timestamp {
|
||||
existing.target = export;
|
||||
existing.timestamp = timestamp;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
if let Some(referenced) = referenced {
|
||||
write_node(registry, referenced, timestamp, mode, |_| Ok(()))?;
|
||||
}
|
||||
}
|
||||
RegistryDelta::AddNetwork { id, network: contents } => {
|
||||
if registry.networks.contains_key(&id) {
|
||||
if idempotent {
|
||||
return Ok(());
|
||||
}
|
||||
RegistryDelta::AddNetwork { id, network } => {
|
||||
if live && registry.networks.contains_key(&id) {
|
||||
return Err(CrdtError::NetworkAlreadyExists(id));
|
||||
}
|
||||
registry.networks.insert(id, contents);
|
||||
add(&mut registry.networks, &mut registry.removed_networks, id, network, timestamp);
|
||||
}
|
||||
RegistryDelta::RemoveNetwork { id, .. } => {
|
||||
registry.networks.remove(&id);
|
||||
RegistryDelta::RemoveNetwork { id, snapshot } => {
|
||||
remove(&mut registry.networks, &mut registry.removed_networks, id, snapshot, timestamp);
|
||||
}
|
||||
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
|
||||
let net = registry.networks.get_mut(&id).ok_or(CrdtError::NetworkDoesNotExist(id))?;
|
||||
apply_attribute_delta(delta, timestamp, force, &mut net.attributes);
|
||||
write_network(registry, id, timestamp, mode, |net| {
|
||||
apply_attribute_delta(delta, timestamp, &mut net.attributes, net.attributes_timestamp);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
RegistryDelta::SetResourceHash { id, hash } => {
|
||||
let entry = registry.resources.entry(id).or_default();
|
||||
if force || timestamp > entry.hash_timestamp {
|
||||
entry.hash = hash;
|
||||
entry.hash_timestamp = timestamp;
|
||||
}
|
||||
upsert_resource(registry, id, timestamp, |entry| {
|
||||
if timestamp > entry.hash_timestamp {
|
||||
entry.hash = hash;
|
||||
entry.hash_timestamp = timestamp;
|
||||
}
|
||||
});
|
||||
}
|
||||
RegistryDelta::AddSource { id, key, source } => {
|
||||
let entry = registry.resources.entry(id).or_default();
|
||||
let value = SourceValue { source, timestamp };
|
||||
if force { entry.force_set_source(key, value) } else { entry.set_source(key, value) }
|
||||
upsert_resource(registry, id, timestamp, |entry| {
|
||||
let value = SourceValue { source, timestamp, deleted: false };
|
||||
entry.set_source(key, value);
|
||||
});
|
||||
}
|
||||
RegistryDelta::RemoveSource { id, key } => {
|
||||
if let Some(entry) = registry.resources.get_mut(&id) {
|
||||
if force {
|
||||
entry.force_remove_source(&key);
|
||||
} else {
|
||||
entry.remove_source(&key, timestamp);
|
||||
}
|
||||
}
|
||||
// An upsert, so a removal for an entry never seen leaves a tombstone its addition loses to.
|
||||
upsert_resource(registry, id, timestamp, |entry| {
|
||||
entry.remove_source(&key, timestamp);
|
||||
});
|
||||
}
|
||||
RegistryDelta::AddResource { id, entry } => {
|
||||
registry.resources.insert(id, entry);
|
||||
add(&mut registry.resources, &mut registry.removed_resources, id, entry, timestamp);
|
||||
}
|
||||
RegistryDelta::RemoveResource { id, .. } => {
|
||||
registry.resources.remove(&id);
|
||||
RegistryDelta::RemoveResource { id, snapshot } => {
|
||||
remove(&mut registry.resources, &mut registry.removed_resources, id, snapshot, timestamp);
|
||||
}
|
||||
RegistryDelta::RegisterPeer { peer, user } => match registry.peer_users.get(&peer) {
|
||||
Some(existing) if *existing != user => return Err(CrdtError::PeerRegistrationConflict(peer)),
|
||||
Some(_) => {}
|
||||
None => {
|
||||
registry.peer_users.insert(peer, user);
|
||||
RegistryDelta::RegisterPeer { peer, user } => {
|
||||
// The newest registration of a device wins, whatever order they land in.
|
||||
if registry.peer_users.get(&peer).is_none_or(|existing| timestamp > existing.at) {
|
||||
registry.peer_users.insert(peer, PeerRegistration { user, at: timestamp });
|
||||
}
|
||||
},
|
||||
}
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => {
|
||||
apply_attribute_delta(delta, timestamp, force, &mut registry.attributes);
|
||||
apply_attribute_delta(delta, timestamp, &mut registry.attributes, TimeStamp::ORIGIN);
|
||||
}
|
||||
// Merge is a structural sync point only; it mutates no registry state.
|
||||
RegistryDelta::Merge { .. } | RegistryDelta::Other(_) => {}
|
||||
RegistryDelta::Merge { .. } | RegistryDelta::EndTransaction | RegistryDelta::Other(_) => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Resurrect (from history) any nodes/networks an op references that were concurrently removed, so
|
||||
/// the op applies against a consistent registry. Cascading: a node's owning network is restored
|
||||
/// before the node. No-op for ops that reference nothing absent.
|
||||
fn ensure_referenced_exist(&mut self, target: RegistryTarget, op: &RegistryDelta) -> Result<(), CrdtError> {
|
||||
match op {
|
||||
RegistryDelta::AddNode { node, .. } => self.ensure_network_exists(target, node.network())?,
|
||||
RegistryDelta::ChangeNodeInput { id, new_input, .. } => {
|
||||
if let NodeInput::Node { id: referenced, .. } = new_input {
|
||||
self.ensure_node_exists(target, *referenced)?;
|
||||
}
|
||||
self.ensure_node_exists(target, *id)?;
|
||||
/// An entity whose existence and every field are last-writer-wins on a timestamp.
|
||||
pub(crate) trait Presence: Sized {
|
||||
/// The newest stamp of an addition or a write: the latest evidence the entity exists.
|
||||
fn presence(&self) -> TimeStamp;
|
||||
fn set_presence(&mut self, at: TimeStamp);
|
||||
/// Stamps every field at `at`, the way an addition writes all of them.
|
||||
fn stamp_all(&mut self, at: TimeStamp);
|
||||
/// Folds `other` in, keeping whichever value of each field is newer.
|
||||
fn merge(&mut self, other: Self);
|
||||
/// Dead content for an entity nothing has added yet, for writes to land on until an addition comes.
|
||||
/// Every field is at the origin, so the addition's values win.
|
||||
fn placeholder() -> Self;
|
||||
}
|
||||
|
||||
impl Presence for Node {
|
||||
fn presence(&self) -> TimeStamp {
|
||||
self.presence
|
||||
}
|
||||
fn set_presence(&mut self, at: TimeStamp) {
|
||||
self.presence = at;
|
||||
}
|
||||
fn placeholder() -> Self {
|
||||
Node::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(0)), 0)
|
||||
}
|
||||
fn stamp_all(&mut self, at: TimeStamp) {
|
||||
self.presence = at;
|
||||
self.added = at;
|
||||
self.inputs_timestamp = at;
|
||||
self.implementation_timestamp = at;
|
||||
self.inputs.iter_mut().for_each(|slot| stamp_slot(slot, at));
|
||||
stamp_attributes(&mut self.attributes, &mut self.attributes_timestamp, at);
|
||||
}
|
||||
fn merge(&mut self, other: Self) {
|
||||
if other.added > self.added {
|
||||
self.network = other.network;
|
||||
self.added = other.added;
|
||||
}
|
||||
if other.implementation_timestamp > self.implementation_timestamp {
|
||||
self.implementation = other.implementation;
|
||||
self.implementation_timestamp = other.implementation_timestamp;
|
||||
}
|
||||
merge_inputs(self, other.inputs, other.inputs_timestamp);
|
||||
merge_attributes(&mut self.attributes, &mut self.attributes_timestamp, other.attributes, other.attributes_timestamp);
|
||||
self.presence = self.presence.max(other.presence);
|
||||
}
|
||||
}
|
||||
|
||||
impl Presence for Network {
|
||||
fn presence(&self) -> TimeStamp {
|
||||
self.presence
|
||||
}
|
||||
fn set_presence(&mut self, at: TimeStamp) {
|
||||
self.presence = at;
|
||||
}
|
||||
fn placeholder() -> Self {
|
||||
Network::default()
|
||||
}
|
||||
fn stamp_all(&mut self, at: TimeStamp) {
|
||||
self.presence = at;
|
||||
self.exports.iter_mut().for_each(|slot| slot.timestamp = at);
|
||||
stamp_attributes(&mut self.attributes, &mut self.attributes_timestamp, at);
|
||||
}
|
||||
fn merge(&mut self, other: Self) {
|
||||
let len = self.exports.len().max(other.exports.len());
|
||||
self.exports.resize_with(len, ExportSlot::default);
|
||||
for (slot, incoming) in self.exports.iter_mut().zip(other.exports) {
|
||||
if incoming.timestamp > slot.timestamp {
|
||||
*slot = incoming;
|
||||
}
|
||||
RegistryDelta::SetNodeInputs { id, inputs } => {
|
||||
for slot in inputs {
|
||||
if let NodeInput::Node { id: referenced, .. } = slot.input {
|
||||
self.ensure_node_exists(target, referenced)?;
|
||||
}
|
||||
}
|
||||
self.ensure_node_exists(target, *id)?;
|
||||
}
|
||||
merge_attributes(&mut self.attributes, &mut self.attributes_timestamp, other.attributes, other.attributes_timestamp);
|
||||
self.presence = self.presence.max(other.presence);
|
||||
}
|
||||
}
|
||||
|
||||
impl Presence for ResourceEntry {
|
||||
fn presence(&self) -> TimeStamp {
|
||||
self.presence
|
||||
}
|
||||
fn set_presence(&mut self, at: TimeStamp) {
|
||||
self.presence = at;
|
||||
}
|
||||
fn placeholder() -> Self {
|
||||
ResourceEntry::default()
|
||||
}
|
||||
fn stamp_all(&mut self, at: TimeStamp) {
|
||||
self.presence = at;
|
||||
self.hash_timestamp = at;
|
||||
self.stamp_sources(at);
|
||||
}
|
||||
fn merge(&mut self, other: Self) {
|
||||
if other.hash_timestamp > self.hash_timestamp {
|
||||
self.hash = other.hash;
|
||||
self.hash_timestamp = other.hash_timestamp;
|
||||
}
|
||||
self.merge_sources(other.sources, other.sources_timestamp);
|
||||
self.presence = self.presence.max(other.presence);
|
||||
}
|
||||
}
|
||||
|
||||
fn stamp_slot(slot: &mut InputSlot, at: TimeStamp) {
|
||||
slot.timestamp = at;
|
||||
stamp_attributes(&mut slot.attributes, &mut slot.attributes_timestamp, at);
|
||||
}
|
||||
|
||||
/// Writes the map whole at `at`: the floor deletes every other key without a tombstone per key.
|
||||
fn stamp_attributes(attributes: &mut Attributes, floor: &mut TimeStamp, at: TimeStamp) {
|
||||
attributes.retain(|_, value| !value.deleted);
|
||||
attributes.values_mut().for_each(|value| value.timestamp = at);
|
||||
*floor = at;
|
||||
}
|
||||
|
||||
/// Folds `other` in key by key. A key only one map holds is dead when the other map's floor is newer, since
|
||||
/// that map was written whole after it; an entry stamped exactly at a floor was written by that whole-map
|
||||
/// write and survives. Where both hold a key, the newer entry wins.
|
||||
fn merge_attributes(attributes: &mut Attributes, floor: &mut TimeStamp, other: Attributes, other_floor: TimeStamp) {
|
||||
attributes.retain(|_, value| value.timestamp >= other_floor);
|
||||
for (key, value) in other {
|
||||
match attributes.entry(key) {
|
||||
Entry::Occupied(entry) if value.timestamp > entry.get().timestamp => *entry.into_mut() = value,
|
||||
Entry::Vacant(entry) if value.timestamp >= *floor => {
|
||||
entry.insert(value);
|
||||
}
|
||||
RegistryDelta::SetNodeImplementation { id, implementation } => {
|
||||
if let crate::Implementation::Network(network) = implementation {
|
||||
self.ensure_network_exists(target, *network)?;
|
||||
}
|
||||
self.ensure_node_exists(target, *id)?;
|
||||
}
|
||||
RegistryDelta::ChangeNodeAttribute { id, .. } | RegistryDelta::ChangeNodeInputAttribute { id, .. } => self.ensure_node_exists(target, *id)?,
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: network, export: export_target, ..
|
||||
} => {
|
||||
if let Some(NodeInput::Node { id: referenced, .. }) = export_target {
|
||||
self.ensure_node_exists(target, *referenced)?;
|
||||
}
|
||||
self.ensure_network_exists(target, *network)?;
|
||||
}
|
||||
RegistryDelta::ChangeNetworkAttribute { id: network, .. } => self.ensure_network_exists(target, *network)?,
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
*floor = (*floor).max(other_floor);
|
||||
}
|
||||
|
||||
fn ensure_node_exists(&mut self, target: RegistryTarget, node_id: NodeId) -> Result<(), CrdtError> {
|
||||
if !self.registry_ref(target).node_instances.contains_key(&node_id) {
|
||||
self.restore_node_from_history(target, node_id)?;
|
||||
/// Folds an input list stamped `at` into the node's. The newer list decides the slot count, except that a
|
||||
/// slot written after that shape still exists, with the gap up to it filled by unset slots stamped by the
|
||||
/// shape. A slot both lists hold keeps its newer value, and its attributes fold key by key. A whole-list
|
||||
/// write and a per-slot write thus land the same in either order.
|
||||
fn merge_inputs(node: &mut Node, other: Vec<InputSlot>, at: TimeStamp) {
|
||||
let (mut newer, shape, older) = if at > node.inputs_timestamp {
|
||||
(other, at, std::mem::take(&mut node.inputs))
|
||||
} else {
|
||||
(std::mem::take(&mut node.inputs), node.inputs_timestamp, other)
|
||||
};
|
||||
for (index, incoming) in older.into_iter().enumerate() {
|
||||
if index >= newer.len() {
|
||||
if slot_newest(&incoming) <= shape {
|
||||
continue;
|
||||
}
|
||||
newer.resize_with(index + 1, || InputSlot::unset(shape));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_network_exists(&mut self, target: RegistryTarget, network_id: NetworkId) -> Result<(), CrdtError> {
|
||||
if !self.registry_ref(target).networks.contains_key(&network_id) {
|
||||
self.restore_network_from_history(target, network_id)?;
|
||||
let slot = &mut newer[index];
|
||||
if incoming.timestamp > slot.timestamp {
|
||||
slot.input = incoming.input;
|
||||
slot.timestamp = incoming.timestamp;
|
||||
}
|
||||
Ok(())
|
||||
merge_attributes(&mut slot.attributes, &mut slot.attributes_timestamp, incoming.attributes, incoming.attributes_timestamp);
|
||||
}
|
||||
node.inputs = newer;
|
||||
node.inputs_timestamp = shape;
|
||||
}
|
||||
|
||||
/// Compute the inverse of `delta` against the registry named by `target`. Retirement passes
|
||||
/// [`RegistryTarget::Snapshot`] so LWW reverses (export target, inputs, attributes, resource hash)
|
||||
/// capture the true pre-op value rather than the hot-polluted working state.
|
||||
pub(crate) fn compute_reverse_delta(&self, target: RegistryTarget, delta: &RegistryDelta) -> Result<RegistryDelta, CrdtError> {
|
||||
let registry = self.registry_ref(target);
|
||||
Ok(match delta {
|
||||
RegistryDelta::AddNode { id, node } => RegistryDelta::RemoveNode { id: *id, snapshot: node.clone() },
|
||||
RegistryDelta::RemoveNode { id, snapshot } => RegistryDelta::AddNode { id: *id, node: snapshot.clone() },
|
||||
&RegistryDelta::SetNodeInputs { id, .. } => {
|
||||
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
RegistryDelta::SetNodeInputs { id, inputs: node.inputs.clone() }
|
||||
}
|
||||
&RegistryDelta::SetNodeImplementation { id, .. } => {
|
||||
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
RegistryDelta::SetNodeImplementation {
|
||||
id,
|
||||
implementation: node.implementation.clone(),
|
||||
}
|
||||
}
|
||||
&RegistryDelta::ChangeNodeInput { id, index: input_idx, .. } => {
|
||||
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
let slot = node.inputs().get(input_idx as usize).ok_or(CrdtError::InputIndexOutOfBounds(input_idx as usize))?;
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id,
|
||||
index: input_idx,
|
||||
new_input: slot.input.clone(),
|
||||
}
|
||||
}
|
||||
&RegistryDelta::ChangeNodeAttribute { id, ref delta } => {
|
||||
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
RegistryDelta::ChangeNodeAttribute {
|
||||
id,
|
||||
delta: reverse_attribute_delta(delta, node.attributes()),
|
||||
}
|
||||
}
|
||||
&RegistryDelta::ChangeNodeInputAttribute { id, index, ref delta } => {
|
||||
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
let input = node.inputs().get(index as usize).ok_or(CrdtError::InputIndexOutOfBounds(index as usize))?;
|
||||
RegistryDelta::ChangeNodeInputAttribute {
|
||||
id,
|
||||
index,
|
||||
delta: reverse_attribute_delta(delta, &input.attributes),
|
||||
}
|
||||
}
|
||||
&RegistryDelta::SetNetworkExport { id, index, .. } => {
|
||||
// If the network is absent the forward op will resurrect it; the reverse is "set the export to None"
|
||||
// since pre-forward there was no export to point at.
|
||||
let export_target = registry.networks.get(&id).and_then(|net| net.exports.get(index as usize)).and_then(|s| s.target.clone());
|
||||
RegistryDelta::SetNetworkExport { id, index, export: export_target }
|
||||
}
|
||||
RegistryDelta::AddNetwork { id, network } => RegistryDelta::RemoveNetwork { id: *id, snapshot: network.clone() },
|
||||
&RegistryDelta::RemoveNetwork { id, ref snapshot } => RegistryDelta::AddNetwork { id, network: snapshot.clone() },
|
||||
&RegistryDelta::ChangeNetworkAttribute { id, ref delta } => {
|
||||
let current = registry.networks.get(&id).map(|net| &net.attributes).ok_or(CrdtError::NetworkDoesNotExist(id))?;
|
||||
RegistryDelta::ChangeNetworkAttribute {
|
||||
id,
|
||||
delta: reverse_attribute_delta(delta, current),
|
||||
}
|
||||
}
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: reverse_attribute_delta(delta, ®istry.attributes),
|
||||
},
|
||||
// Registrations are append-only and not user-undoable; reverse is the same op,
|
||||
// which applies as a no-op on the already-registered PeerId.
|
||||
&RegistryDelta::RegisterPeer { peer, user } => RegistryDelta::RegisterPeer { peer, user },
|
||||
&RegistryDelta::SetResourceHash { id, .. } => RegistryDelta::SetResourceHash {
|
||||
id,
|
||||
hash: registry.resources.get(&id).and_then(|entry| entry.hash),
|
||||
},
|
||||
&RegistryDelta::AddSource { id, key, .. } => match registry.resources.get(&id).and_then(|entry| entry.source(&key)) {
|
||||
// The slot already held a source: undo restores it.
|
||||
Some(existing) => RegistryDelta::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: existing.source.clone(),
|
||||
},
|
||||
// The slot was empty: undo removes what this op added.
|
||||
None => RegistryDelta::RemoveSource { id, key },
|
||||
},
|
||||
&RegistryDelta::RemoveSource { id, key } => match registry.resources.get(&id).and_then(|entry| entry.source(&key)) {
|
||||
Some(existing) => RegistryDelta::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: existing.source.clone(),
|
||||
},
|
||||
// Nothing to restore; reverse is a no-op removal.
|
||||
None => RegistryDelta::RemoveSource { id, key },
|
||||
},
|
||||
&RegistryDelta::AddResource { id, .. } => match registry.resources.get(&id) {
|
||||
// Overwrote an existing entry: undo restores it.
|
||||
Some(existing) => RegistryDelta::AddResource { id, entry: existing.clone() },
|
||||
// Created a new entry: undo removes what this op added (snapshot is empty since there was nothing prior).
|
||||
None => RegistryDelta::RemoveResource {
|
||||
id,
|
||||
snapshot: ResourceEntry::default(),
|
||||
},
|
||||
},
|
||||
&RegistryDelta::RemoveResource { id, .. } => {
|
||||
let snapshot = registry.resources.get(&id).cloned().unwrap_or_default();
|
||||
RegistryDelta::AddResource { id, entry: snapshot }
|
||||
}
|
||||
RegistryDelta::Merge { extra_parents } => RegistryDelta::Merge { extra_parents: extra_parents.clone() },
|
||||
&RegistryDelta::Other(_) => RegistryDelta::Other(Value::None),
|
||||
})
|
||||
/// The newest write the slot carries, its attributes included.
|
||||
fn slot_newest(slot: &InputSlot) -> TimeStamp {
|
||||
slot.attributes
|
||||
.values()
|
||||
.map(|value| value.timestamp)
|
||||
.fold(slot.timestamp.max(slot.attributes_timestamp), TimeStamp::max)
|
||||
}
|
||||
|
||||
/// The slot at `index` for a write at `at`. A slot past the end comes into being when the write is newer
|
||||
/// than the list's shape, as in [`merge_inputs`], and is `None` when the shape is newer. For a fresh local
|
||||
/// edit the index is out of bounds.
|
||||
fn slot_for_write(node: &mut Node, index: usize, at: TimeStamp, mode: ApplyMode) -> Result<Option<&mut InputSlot>, CrdtError> {
|
||||
if index >= node.inputs.len() {
|
||||
if index >= MAX_INPUT_SLOTS || mode == ApplyMode::Live {
|
||||
return Err(CrdtError::InputIndexOutOfBounds(index));
|
||||
}
|
||||
if at <= node.inputs_timestamp {
|
||||
return Ok(None);
|
||||
}
|
||||
let shape = node.inputs_timestamp;
|
||||
node.inputs.resize_with(index + 1, || InputSlot::unset(shape));
|
||||
}
|
||||
Ok(node.inputs.get_mut(index))
|
||||
}
|
||||
|
||||
/// The entity's content wherever it sits: live, or held by its tombstone.
|
||||
fn content_mut<'a, K: Hash + Eq + Copy, T>(live: &'a mut HashMap<K, T>, dead: &'a mut HashMap<K, Tombstone<T>>, id: K) -> Option<&'a mut T> {
|
||||
live.get_mut(&id).or_else(|| dead.get_mut(&id).map(|mark| &mut mark.content))
|
||||
}
|
||||
|
||||
/// Brings a removed entity back when its presence has grown past its removal. A placeholder stays dead
|
||||
/// whatever its presence.
|
||||
fn settle<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K) {
|
||||
if dead.get(&id).is_some_and(|mark| !mark.placeholder && mark.content.presence() > mark.at) {
|
||||
let mark = dead.remove(&id).expect("checked above");
|
||||
live.insert(id, mark.content);
|
||||
}
|
||||
}
|
||||
|
||||
/// Folds `content` into whatever is held under `id`, or holds it as new. Content comes from an addition or
|
||||
/// a removal's snapshot, so it proves the entity was added and a placeholder holding it stops being one.
|
||||
fn fold<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, content: T) {
|
||||
if let Some(mark) = dead.get_mut(&id).filter(|mark| mark.placeholder) {
|
||||
// The placeholder holds only early writes: they land on the real content as if the addition came first.
|
||||
let early = std::mem::replace(&mut mark.content, content);
|
||||
mark.content.merge(early);
|
||||
mark.placeholder = false;
|
||||
} else if let Some(existing) = content_mut(live, dead, id) {
|
||||
existing.merge(content);
|
||||
} else {
|
||||
live.insert(id, content);
|
||||
}
|
||||
settle(live, dead, id);
|
||||
}
|
||||
|
||||
/// An addition at `at`: every field of `content` is written at `at`, and the entity exists from then
|
||||
/// unless a newer removal holds it dead.
|
||||
fn add<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, mut content: T, at: TimeStamp) {
|
||||
content.stamp_all(at);
|
||||
fold(live, dead, id, content);
|
||||
}
|
||||
|
||||
/// A removal at `at`: the entity is dead from then unless a newer addition or write holds it live. The
|
||||
/// snapshot folds in first, so a removal of an entity never seen still lands and its addition loses when
|
||||
/// it arrives.
|
||||
fn remove<K: Hash + Eq + Copy, T: Presence>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, snapshot: T, at: TimeStamp) {
|
||||
fold(live, dead, id, snapshot);
|
||||
if let Some(mark) = dead.get_mut(&id) {
|
||||
mark.at = mark.at.max(at);
|
||||
} else if live.get(&id).is_some_and(|content| at > content.presence()) {
|
||||
let content = live.remove(&id).expect("checked above");
|
||||
dead.insert(id, Tombstone { content, at, placeholder: false });
|
||||
}
|
||||
}
|
||||
|
||||
/// A write at `at` to the entity under `id`, applied by `write` to its content wherever it sits. The
|
||||
/// write is evidence the entity exists at `at`, so it revives an older removal. A write to an entity
|
||||
/// never seen lands on a placeholder tombstone that stays dead until an addition folds into it, so ops
|
||||
/// land the same in any order and nothing is deferred. For a fresh local edit the entity is `missing()`.
|
||||
fn write<K: Hash + Eq + Copy, T: Presence>(
|
||||
live: &mut HashMap<K, T>,
|
||||
dead: &mut HashMap<K, Tombstone<T>>,
|
||||
id: K,
|
||||
at: TimeStamp,
|
||||
mode: ApplyMode,
|
||||
missing: impl FnOnce() -> CrdtError,
|
||||
write: impl FnOnce(&mut T) -> Result<(), CrdtError>,
|
||||
) -> Result<(), CrdtError> {
|
||||
let unseen = !live.contains_key(&id) && !dead.contains_key(&id);
|
||||
if unseen {
|
||||
if mode == ApplyMode::Live {
|
||||
return Err(missing());
|
||||
}
|
||||
dead.insert(
|
||||
id,
|
||||
Tombstone {
|
||||
content: T::placeholder(),
|
||||
at: TimeStamp::ORIGIN,
|
||||
placeholder: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
let content = content_mut(live, dead, id).expect("held above");
|
||||
if let Err(error) = write(content) {
|
||||
// A rejected op changes nothing, so the placeholder made for it goes too.
|
||||
if unseen {
|
||||
dead.remove(&id);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
content.set_presence(content.presence().max(at));
|
||||
settle(live, dead, id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A fresh local edit cannot name a node never seen. Checked before an op's first write, so a refused op changes nothing.
|
||||
fn ensure_seen(registry: &Registry, ids: &[NodeId], mode: ApplyMode) -> Result<(), CrdtError> {
|
||||
let unseen = |id: &&NodeId| !registry.node_instances.contains_key(id) && !registry.removed_nodes.contains_key(id);
|
||||
match ids.iter().find(unseen) {
|
||||
Some(&id) if mode == ApplyMode::Live => Err(CrdtError::TargetNodeDoesNotExist(id)),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`write()`] to a node; with a no-op `f`, records a reference to it.
|
||||
fn write_node(registry: &mut Registry, id: NodeId, at: TimeStamp, mode: ApplyMode, f: impl FnOnce(&mut Node) -> Result<(), CrdtError>) -> Result<(), CrdtError> {
|
||||
write(&mut registry.node_instances, &mut registry.removed_nodes, id, at, mode, || CrdtError::TargetNodeDoesNotExist(id), f)
|
||||
}
|
||||
|
||||
fn write_network(registry: &mut Registry, id: NetworkId, at: TimeStamp, mode: ApplyMode, f: impl FnOnce(&mut Network) -> Result<(), CrdtError>) -> Result<(), CrdtError> {
|
||||
write(&mut registry.networks, &mut registry.removed_networks, id, at, mode, || CrdtError::NetworkDoesNotExist(id), f)
|
||||
}
|
||||
|
||||
/// Like [`write()`] for a resource, except that an entry never seen is created first, since single-field
|
||||
/// resource ops are upserts. Every other field starts at the origin, so a later addition fills them in.
|
||||
fn upsert_resource(registry: &mut Registry, id: ResourceId, at: TimeStamp, f: impl FnOnce(&mut ResourceEntry)) {
|
||||
if !registry.resources.contains_key(&id) && !registry.removed_resources.contains_key(&id) {
|
||||
registry.resources.insert(
|
||||
id,
|
||||
ResourceEntry {
|
||||
presence: at,
|
||||
..ResourceEntry::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
let entry = content_mut(&mut registry.resources, &mut registry.removed_resources, id).expect("held above");
|
||||
f(entry);
|
||||
entry.set_presence(entry.presence().max(at));
|
||||
settle(&mut registry.resources, &mut registry.removed_resources, id);
|
||||
}
|
||||
|
||||
/// Which of a [`Document`]'s two registries an apply targets: the working copy (retired state plus
|
||||
@@ -484,13 +684,12 @@ pub(crate) enum RegistryTarget {
|
||||
Snapshot,
|
||||
}
|
||||
|
||||
/// How [`Document::apply_op_with`] resolves structural collisions and LWW timestamp ties.
|
||||
/// How [`Document::apply_op_with`] treats what it finds.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum ApplyMode {
|
||||
/// Fresh local/remote edit: structural ops error on duplicate/missing targets; LWW uses strict `>`.
|
||||
/// A fresh local edit: adding what exists, or writing to what was never seen, is an error, since a local
|
||||
/// edit cannot mean either.
|
||||
Live,
|
||||
/// Replay/retire: structural ops skip duplicate/missing targets; LWW still uses strict `>`.
|
||||
/// An op from a peer or from persisted state: every arm is a timestamp comparison.
|
||||
Idempotent,
|
||||
/// Silent-zone undo/redo rewind: structural ops are idempotent and LWW arms assign unconditionally.
|
||||
Force,
|
||||
}
|
||||
@@ -221,11 +221,13 @@ pub fn convert_resource_entry(resources: &graphene_resource::ResourceRegistry, i
|
||||
peer,
|
||||
};
|
||||
let body = to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
|
||||
entry.set_source(
|
||||
// Built rather than written: the chain is put in place as converted, floor and all at the origin.
|
||||
entry.force_set_source(
|
||||
key,
|
||||
crate::SourceValue {
|
||||
source: body,
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
deleted: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -339,7 +341,15 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
|
||||
write_ui_network_attributes(&mut attributes, node_network, metadata_path, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
|
||||
write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
|
||||
|
||||
registry.networks.insert(network_id, Network { exports, attributes });
|
||||
registry.networks.insert(
|
||||
network_id,
|
||||
Network {
|
||||
presence: TimeStamp::ORIGIN,
|
||||
exports,
|
||||
attributes,
|
||||
attributes_timestamp: TimeStamp::ORIGIN,
|
||||
},
|
||||
);
|
||||
ctx.network_ids.insert(metadata_path.to_vec(), network_id);
|
||||
|
||||
Ok(())
|
||||
@@ -417,6 +427,7 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
|
||||
input: convert_input(input, parent_path, network_id, ctx.ids(metadata_path))?,
|
||||
timestamp,
|
||||
attributes: input_attrs,
|
||||
attributes_timestamp: timestamp,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -449,10 +460,14 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
|
||||
write_ui_attributes(&mut attributes, ctx.metadata, metadata_path, runtime_node_id, timestamp)?;
|
||||
|
||||
Ok(Node {
|
||||
presence: timestamp,
|
||||
added: timestamp,
|
||||
inputs_timestamp: timestamp,
|
||||
implementation,
|
||||
implementation_timestamp: timestamp,
|
||||
inputs,
|
||||
attributes,
|
||||
attributes_timestamp: timestamp,
|
||||
network: network_id,
|
||||
})
|
||||
}
|
||||
@@ -812,7 +827,15 @@ impl<'m> ScopedConversion<'m> {
|
||||
write_ui_network_attributes(&mut attributes, node_network, local_path, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
|
||||
write_scope_injections(&mut attributes, node_network, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
|
||||
|
||||
registry.networks.insert(network_id, Network { exports, attributes });
|
||||
registry.networks.insert(
|
||||
network_id,
|
||||
Network {
|
||||
presence: TimeStamp::ORIGIN,
|
||||
exports,
|
||||
attributes,
|
||||
attributes_timestamp: TimeStamp::ORIGIN,
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -3,21 +3,26 @@
|
||||
//! [`History`] owns the deltas in topological order (every parent precedes its children) plus an
|
||||
//! index from [`Rev`] to position for O(1) lookup. The order is a valid replay order, so it is what
|
||||
//! gets serialized to the on-disk history file and what [`crate::Session::replay_from_history`]
|
||||
//! consumes. Retired commits have a single writer in every regime (solo editing, or leader-ordered
|
||||
//! collaboration where the leader serializes retired commits), so appending preserves the order by
|
||||
//! construction. The only operation that introduces out-of-order deltas is [`merge`](History::merge),
|
||||
//! which re-sorts the combined set into the canonical order to restore the invariant.
|
||||
//! consumes. Appending a commit keeps the order; deltas arriving out of it are put back by
|
||||
//! a canonical sort.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::{AttributesWrite, CrdtError, Delta, Rev, TimeStamp, Value};
|
||||
use crate::{AttributesWrite, CrdtError, Delta, RegistryDelta, ResourceHash, Rev, TimeStamp, Value};
|
||||
|
||||
/// Every mutator maintains the indexes, so the tips and named hashes are probes, not scans of a growing history.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct History {
|
||||
/// Deltas in topological order. Mutated only via [`push`](Self::push).
|
||||
deltas: Vec<Delta>,
|
||||
/// `Rev` to its position in `deltas`. Kept in sync with `deltas` by every mutator.
|
||||
index: HashMap<Rev, usize>,
|
||||
/// Every rev some delta names as a parent.
|
||||
referenced: HashSet<Rev>,
|
||||
/// Deltas no other delta names as a parent.
|
||||
tips: HashSet<Rev>,
|
||||
/// Content hashes the deltas name, from resource additions and removals.
|
||||
resource_hashes: HashSet<ResourceHash>,
|
||||
}
|
||||
|
||||
impl History {
|
||||
@@ -27,8 +32,9 @@ impl History {
|
||||
|
||||
/// Build from deltas already in topological order (the on-disk load path), indexing them in place.
|
||||
pub fn from_ordered(deltas: Vec<Delta>) -> Self {
|
||||
let index = deltas.iter().enumerate().map(|(position, delta)| (delta.id, position)).collect();
|
||||
Self { deltas, index }
|
||||
let mut history = Self::default();
|
||||
deltas.into_iter().for_each(|delta| history.push(delta));
|
||||
history
|
||||
}
|
||||
|
||||
pub fn get(&self, rev: Rev) -> Option<&Delta> {
|
||||
@@ -39,6 +45,11 @@ impl History {
|
||||
self.index.contains_key(&rev)
|
||||
}
|
||||
|
||||
/// The content hashes named by any resource addition or removal in history.
|
||||
pub fn resource_hashes(&self) -> &HashSet<ResourceHash> {
|
||||
&self.resource_hashes
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.deltas.len()
|
||||
}
|
||||
@@ -51,10 +62,22 @@ impl History {
|
||||
/// (idempotent re-apply) overwrites the existing entry in place rather than appending, so the
|
||||
/// order and index are unchanged.
|
||||
pub fn push(&mut self, delta: Delta) {
|
||||
match &delta.kind {
|
||||
RegistryDelta::AddResource { entry, .. } => self.resource_hashes.extend(entry.hash),
|
||||
RegistryDelta::RemoveResource { snapshot, .. } => self.resource_hashes.extend(snapshot.hash),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(&position) = self.index.get(&delta.id) {
|
||||
self.deltas[position] = delta;
|
||||
return;
|
||||
}
|
||||
for parent in delta.all_parents() {
|
||||
self.referenced.insert(parent);
|
||||
self.tips.remove(&parent);
|
||||
}
|
||||
if !self.referenced.contains(&delta.id) {
|
||||
self.tips.insert(delta.id);
|
||||
}
|
||||
self.index.insert(delta.id, self.deltas.len());
|
||||
self.deltas.push(delta);
|
||||
}
|
||||
@@ -64,66 +87,24 @@ impl History {
|
||||
self.deltas.iter()
|
||||
}
|
||||
|
||||
/// Absorb `incoming` (dedup by `Rev`) and canonically re-sort the whole combined history.
|
||||
///
|
||||
/// The sort is deterministic (topological, ties broken by `Rev`), so two peers that absorb the same
|
||||
/// delta set produce byte-identical history, not merely two different valid orderings. This is the
|
||||
/// history-convergence mechanism: arrival order is erased. Callers update the registry separately
|
||||
/// (LWW apply is commutative, so the registry converges regardless of order).
|
||||
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) {
|
||||
for delta in incoming {
|
||||
self.push(delta);
|
||||
}
|
||||
self.canonical_sort();
|
||||
}
|
||||
|
||||
/// Re-order `deltas` into the canonical topological order and rebuild the index: parents precede
|
||||
/// children, and among deltas whose parents are all emitted the lowest `Rev` goes first. O(V + E).
|
||||
fn canonical_sort(&mut self) {
|
||||
// Unsatisfied in-history parent count per delta, plus reverse edges to decrement as parents emit.
|
||||
let mut pending_parents: HashMap<Rev, usize> = HashMap::with_capacity(self.deltas.len());
|
||||
let mut children: HashMap<Rev, Vec<Rev>> = HashMap::new();
|
||||
for delta in &self.deltas {
|
||||
let in_history_parents = delta.all_parents().filter(|parent| self.index.contains_key(parent)).count();
|
||||
pending_parents.insert(delta.id, in_history_parents);
|
||||
for parent in delta.all_parents() {
|
||||
if self.index.contains_key(&parent) {
|
||||
children.entry(parent).or_default().push(delta.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ready set as a min-heap on `Rev` (via `Reverse`) so ties resolve deterministically.
|
||||
let mut ready: std::collections::BinaryHeap<std::cmp::Reverse<Rev>> = pending_parents.iter().filter(|(_, count)| **count == 0).map(|(rev, _)| std::cmp::Reverse(*rev)).collect();
|
||||
|
||||
let mut order: Vec<Rev> = Vec::with_capacity(self.deltas.len());
|
||||
while let Some(std::cmp::Reverse(rev)) = ready.pop() {
|
||||
order.push(rev);
|
||||
for child in children.get(&rev).into_iter().flatten() {
|
||||
let count = pending_parents.get_mut(child).expect("child is in history");
|
||||
*count -= 1;
|
||||
if *count == 0 {
|
||||
ready.push(std::cmp::Reverse(*child));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// `order` is a permutation of the existing revs, so reorder `deltas` to match and rebuild the index.
|
||||
let mut by_rev: HashMap<Rev, Delta> = self.deltas.drain(..).map(|delta| (delta.id, delta)).collect();
|
||||
self.index.clear();
|
||||
for (position, rev) in order.iter().enumerate() {
|
||||
if let Some(delta) = by_rev.remove(rev) {
|
||||
self.index.insert(*rev, position);
|
||||
self.deltas.push(delta);
|
||||
/// `roots` and everything reachable from them through all parent links. Unknown roots are skipped.
|
||||
pub(crate) fn ancestors(&self, roots: impl IntoIterator<Item = Rev>) -> HashSet<Rev> {
|
||||
let mut seen = HashSet::new();
|
||||
let mut stack: Vec<Rev> = roots.into_iter().filter(|rev| self.contains(*rev)).collect();
|
||||
while let Some(rev) = stack.pop() {
|
||||
if seen.insert(rev)
|
||||
&& let Some(delta) = self.get(rev)
|
||||
{
|
||||
stack.extend(delta.all_parents());
|
||||
}
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
/// The current tips: revs that no other delta lists as a parent (the divergent heads). A linear
|
||||
/// history has exactly one tip; concurrent branches have several. Sorted ascending for determinism.
|
||||
pub fn tips(&self) -> Vec<Rev> {
|
||||
let referenced: std::collections::HashSet<Rev> = self.deltas.iter().flat_map(|delta| delta.all_parents()).collect();
|
||||
let mut tips: Vec<Rev> = self.deltas.iter().map(|delta| delta.id).filter(|rev| !referenced.contains(rev)).collect();
|
||||
let mut tips: Vec<Rev> = self.tips.iter().copied().collect();
|
||||
tips.sort_unstable();
|
||||
tips
|
||||
}
|
||||
|
||||
@@ -56,6 +56,8 @@ pub const ROOT_NETWORK: NetworkId = NetworkId(0);
|
||||
/// Upper bound on a network's export slot count, guarding `SetExport` against a malicious or corrupted
|
||||
/// slot index forcing an unbounded `exports` allocation.
|
||||
pub(crate) const MAX_EXPORT_SLOTS: usize = 1 << 16;
|
||||
/// A per-slot write can bring a slot past the end of the list into being, so it is capped the same way.
|
||||
pub(crate) const MAX_INPUT_SLOTS: usize = 1 << 16;
|
||||
|
||||
/// Per-device identity. Stable per `(device, document)`. Used for CRDT tiebreaking and `NodeId`
|
||||
/// scoping. Globally unique across all peers ever in a document.
|
||||
|
||||
@@ -7,6 +7,7 @@ pub mod document;
|
||||
pub mod history;
|
||||
pub mod ids;
|
||||
pub mod model;
|
||||
mod prior;
|
||||
pub mod registry;
|
||||
pub mod resources;
|
||||
pub mod session;
|
||||
@@ -25,6 +26,7 @@ pub use document::*;
|
||||
pub use history::History;
|
||||
pub use ids::*;
|
||||
pub use model::*;
|
||||
pub use prior::{NetworkField, NodeField, Prior};
|
||||
pub use registry::*;
|
||||
pub use resources::*;
|
||||
pub use session::*;
|
||||
@@ -42,6 +44,7 @@ pub use to_runtime::Declarations;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
mod bookkeeping;
|
||||
mod crdt;
|
||||
mod round_trip;
|
||||
}
|
||||
@@ -4,6 +4,17 @@ use std::borrow::Cow;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Node {
|
||||
/// The latest addition or write, so a concurrent removal resolves by last-writer-wins rather than
|
||||
/// arrival order. See [`Registry::removed_nodes`](crate::Registry::removed_nodes).
|
||||
#[serde(default)]
|
||||
pub(crate) presence: TimeStamp,
|
||||
/// When the node was last added, which decides its network between concurrent additions of one id.
|
||||
#[serde(default)]
|
||||
pub(crate) added: TimeStamp,
|
||||
/// When the input list last changed shape, so whole-list and per-slot writes resolve the same in either
|
||||
/// order: the list follows the newer write, and a slot both lists held keeps its newer value.
|
||||
#[serde(default)]
|
||||
pub(crate) inputs_timestamp: TimeStamp,
|
||||
pub(crate) implementation: Implementation,
|
||||
/// When the implementation was last written, so a swap resolves by last-writer-wins rather than by
|
||||
/// the order ops happen to arrive in. Absent from documents written before swaps were expressible.
|
||||
@@ -11,6 +22,9 @@ pub struct Node {
|
||||
pub(crate) implementation_timestamp: TimeStamp,
|
||||
pub(crate) inputs: Vec<InputSlot>,
|
||||
pub(crate) attributes: Attributes,
|
||||
/// When `attributes` was last written whole; see [`Attributes`].
|
||||
#[serde(default)]
|
||||
pub(crate) attributes_timestamp: TimeStamp,
|
||||
pub(crate) network: NetworkId,
|
||||
}
|
||||
|
||||
@@ -47,15 +61,26 @@ impl Node {
|
||||
attributes_value_equal(&self.attributes, &other.attributes)
|
||||
}
|
||||
|
||||
/// A node in `network` whose `inputs` slots are unset, for a caller that fills them in with
|
||||
/// `ChangeNodeInput`. The slot count is fixed at creation, since changing an input addresses a
|
||||
/// slot by position.
|
||||
pub fn new(network: NetworkId, implementation: Implementation, inputs: usize) -> Self {
|
||||
Self {
|
||||
presence: TimeStamp::ORIGIN,
|
||||
added: TimeStamp::ORIGIN,
|
||||
inputs_timestamp: TimeStamp::ORIGIN,
|
||||
implementation,
|
||||
implementation_timestamp: TimeStamp::ORIGIN,
|
||||
inputs: vec![InputSlot::unset(TimeStamp::ORIGIN); inputs],
|
||||
attributes: Attributes::new(),
|
||||
attributes_timestamp: TimeStamp::ORIGIN,
|
||||
network,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn dummy() -> Self {
|
||||
Self {
|
||||
implementation: Implementation::ProtoNode(ResourceId::new()),
|
||||
implementation_timestamp: TimeStamp::default(),
|
||||
inputs: vec![],
|
||||
attributes: Attributes::new(),
|
||||
network: crate::ROOT_NETWORK,
|
||||
}
|
||||
Self::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::new()), 0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,6 +91,26 @@ pub struct InputSlot {
|
||||
pub input: NodeInput,
|
||||
pub timestamp: TimeStamp,
|
||||
pub attributes: Attributes,
|
||||
/// When `attributes` was last written whole; see [`Attributes`].
|
||||
#[serde(default)]
|
||||
pub attributes_timestamp: TimeStamp,
|
||||
}
|
||||
|
||||
impl InputSlot {
|
||||
/// A slot holding nothing, stamped `at`.
|
||||
pub fn unset(at: TimeStamp) -> Self {
|
||||
// `to_runtime` reads this back as a `TaggedValue`, whose unit `None` variant encodes as this string.
|
||||
// Pinned by `unset_input_slot_deserializes_as_tagged_value_none`.
|
||||
Self {
|
||||
input: NodeInput::Value {
|
||||
value: Value::Str("None".to_string()),
|
||||
exposed: false,
|
||||
},
|
||||
timestamp: at,
|
||||
attributes: Attributes::new(),
|
||||
attributes_timestamp: at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -97,10 +142,16 @@ pub enum Implementation {
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Network {
|
||||
/// The latest addition or write; see [`Node::presence`](crate::Node).
|
||||
#[serde(default)]
|
||||
pub(crate) presence: TimeStamp,
|
||||
pub exports: Vec<ExportSlot>,
|
||||
/// Per-network `ui::*` state (navigation, previewing). Separate from `Node.attributes` so
|
||||
/// view-state edits LWW independently.
|
||||
pub attributes: Attributes,
|
||||
/// When `attributes` was last written whole; see [`Attributes`].
|
||||
#[serde(default)]
|
||||
pub attributes_timestamp: TimeStamp,
|
||||
}
|
||||
|
||||
impl Network {
|
||||
@@ -125,7 +176,7 @@ impl Network {
|
||||
|
||||
/// One positional export slot. `target == None` marks an empty/removed slot. Timestamp drives LWW
|
||||
/// on concurrent `SetExport` ops.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ExportSlot {
|
||||
pub target: Option<NodeInput>,
|
||||
pub timestamp: TimeStamp,
|
||||
@@ -159,6 +210,19 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// `to_runtime` has to read back what `Node::new` writes into an unset slot, so its literal must stay
|
||||
/// in step with how `TaggedValue::None` serializes.
|
||||
#[test]
|
||||
fn unset_input_slot_deserializes_as_tagged_value_none() {
|
||||
let node = Node::new(crate::ROOT_NETWORK, Implementation::Network(crate::ROOT_NETWORK), 1);
|
||||
let NodeInput::Value { value, .. } = &node.inputs()[0].input else {
|
||||
panic!("a fresh slot holds a value input");
|
||||
};
|
||||
|
||||
let tagged: graph_craft::document::value::TaggedValue = crate::from_value(value).expect("the unset slot value must deserialize");
|
||||
assert_eq!(tagged, graph_craft::document::value::TaggedValue::None);
|
||||
}
|
||||
|
||||
/// A `SetExport(None)` truncation leaves a trailing empty slot. Such a network is value-equal to
|
||||
/// the same network without that slot, so the soak oracle doesn't false-report drift.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
use crate::{
|
||||
AttributeValue, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, TimeStamp,
|
||||
Tombstone,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::hash::Hash;
|
||||
|
||||
/// What a slot held before a delta wrote it, with its own stamps. Undo puts these back as they were, bypassing
|
||||
/// LWW, so the registry is again exactly what folding history up to the delta's parent gives. Never sent or
|
||||
/// applied as an op.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum Prior {
|
||||
/// The whole entity, live or tombstoned. `None, None` means it didn't exist, so undoing an addition leaves no
|
||||
/// tombstone behind.
|
||||
Node {
|
||||
id: NodeId,
|
||||
live: Option<Node>,
|
||||
removed: Option<Tombstone<Node>>,
|
||||
},
|
||||
Network {
|
||||
id: NetworkId,
|
||||
live: Option<Network>,
|
||||
removed: Option<Tombstone<Network>>,
|
||||
},
|
||||
Resource {
|
||||
id: ResourceId,
|
||||
live: Option<ResourceEntry>,
|
||||
removed: Option<Tombstone<ResourceEntry>>,
|
||||
},
|
||||
/// One field of a live node, and the node's presence, which every write moves.
|
||||
NodeField {
|
||||
id: NodeId,
|
||||
presence: TimeStamp,
|
||||
field: NodeField,
|
||||
},
|
||||
/// One field of a live network, and its presence.
|
||||
NetworkField {
|
||||
id: NetworkId,
|
||||
presence: TimeStamp,
|
||||
field: NetworkField,
|
||||
},
|
||||
DocumentAttribute {
|
||||
key: String,
|
||||
previous: Option<AttributeValue>,
|
||||
},
|
||||
PeerUser {
|
||||
peer: PeerId,
|
||||
previous: Option<PeerRegistration>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum NodeField {
|
||||
/// Only the presence moved, by a reference from another entity's op.
|
||||
Presence,
|
||||
Attribute {
|
||||
key: String,
|
||||
previous: Option<AttributeValue>,
|
||||
},
|
||||
Input {
|
||||
index: u32,
|
||||
previous: InputSlot,
|
||||
},
|
||||
InputAttribute {
|
||||
index: u32,
|
||||
key: String,
|
||||
previous: Option<AttributeValue>,
|
||||
},
|
||||
Inputs {
|
||||
previous: Vec<InputSlot>,
|
||||
inputs_timestamp: TimeStamp,
|
||||
},
|
||||
Implementation {
|
||||
previous: Implementation,
|
||||
implementation_timestamp: TimeStamp,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum NetworkField {
|
||||
/// Only the presence moved, by a node added to or implemented by it.
|
||||
Presence,
|
||||
Attribute {
|
||||
key: String,
|
||||
previous: Option<AttributeValue>,
|
||||
},
|
||||
Exports {
|
||||
previous: Vec<ExportSlot>,
|
||||
},
|
||||
}
|
||||
|
||||
/// What `op` is about to write in `registry`, in write order. Taken before the op applies.
|
||||
pub(crate) fn capture(registry: &Registry, op: &RegistryDelta) -> Vec<Prior> {
|
||||
let mut priors = Vec::new();
|
||||
let node_input = |input: &NodeInput| match input {
|
||||
NodeInput::Node { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
};
|
||||
match op {
|
||||
RegistryDelta::AddNode { id, node } => {
|
||||
priors.push(network_field(registry, node.network, |_| NetworkField::Presence));
|
||||
priors.push(whole_node(registry, *id));
|
||||
}
|
||||
RegistryDelta::RemoveNode { id, .. } => priors.push(whole_node(registry, *id)),
|
||||
RegistryDelta::SetNodeInputs { id, inputs } => {
|
||||
priors.push(node_field(registry, *id, |node| NodeField::Inputs {
|
||||
previous: node.inputs.clone(),
|
||||
inputs_timestamp: node.inputs_timestamp,
|
||||
}));
|
||||
priors.extend(
|
||||
inputs
|
||||
.iter()
|
||||
.filter_map(|slot| node_input(&slot.input))
|
||||
.map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)),
|
||||
);
|
||||
}
|
||||
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
|
||||
priors.push(node_field(registry, *id, |node| {
|
||||
input_field(node, *index, |slot| NodeField::Input {
|
||||
index: *index,
|
||||
previous: slot.clone(),
|
||||
})
|
||||
}));
|
||||
priors.extend(node_input(new_input).map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)));
|
||||
}
|
||||
RegistryDelta::SetNodeImplementation { id, implementation } => {
|
||||
if let Implementation::Network(network) = implementation {
|
||||
priors.push(network_field(registry, *network, |_| NetworkField::Presence));
|
||||
}
|
||||
priors.push(node_field(registry, *id, |node| NodeField::Implementation {
|
||||
previous: node.implementation.clone(),
|
||||
implementation_timestamp: node.implementation_timestamp,
|
||||
}));
|
||||
}
|
||||
RegistryDelta::ChangeNodeAttribute { id, delta } => priors.push(node_field(registry, *id, |node| NodeField::Attribute {
|
||||
key: delta.key.clone(),
|
||||
previous: node.attributes.get(&delta.key).cloned(),
|
||||
})),
|
||||
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => priors.push(node_field(registry, *id, |node| {
|
||||
input_field(node, *index, |slot| NodeField::InputAttribute {
|
||||
index: *index,
|
||||
key: delta.key.clone(),
|
||||
previous: slot.attributes.get(&delta.key).cloned(),
|
||||
})
|
||||
})),
|
||||
RegistryDelta::SetNetworkExport { id, export, .. } => {
|
||||
priors.push(network_field(registry, *id, |network| NetworkField::Exports { previous: network.exports.clone() }));
|
||||
priors.extend(export.as_ref().and_then(node_input).map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)));
|
||||
}
|
||||
RegistryDelta::AddNetwork { id, .. } | RegistryDelta::RemoveNetwork { id, .. } => priors.push(whole_network(registry, *id)),
|
||||
RegistryDelta::ChangeNetworkAttribute { id, delta } => {
|
||||
priors.push(network_field(registry, *id, |network| NetworkField::Attribute {
|
||||
key: delta.key.clone(),
|
||||
previous: network.attributes.get(&delta.key).cloned(),
|
||||
}));
|
||||
}
|
||||
RegistryDelta::AddResource { id, .. }
|
||||
| RegistryDelta::RemoveResource { id, .. }
|
||||
| RegistryDelta::SetResourceHash { id, .. }
|
||||
| RegistryDelta::AddSource { id, .. }
|
||||
| RegistryDelta::RemoveSource { id, .. } => priors.push(Prior::Resource {
|
||||
id: *id,
|
||||
live: registry.resources.get(id).cloned(),
|
||||
removed: registry.removed_resources.get(id).cloned(),
|
||||
}),
|
||||
RegistryDelta::RegisterPeer { peer, .. } => priors.push(Prior::PeerUser {
|
||||
peer: *peer,
|
||||
previous: registry.peer_users.get(peer).copied(),
|
||||
}),
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => priors.push(Prior::DocumentAttribute {
|
||||
key: delta.key.clone(),
|
||||
previous: registry.attributes.get(&delta.key).cloned(),
|
||||
}),
|
||||
RegistryDelta::Merge { .. } | RegistryDelta::EndTransaction | RegistryDelta::Other(_) => {}
|
||||
}
|
||||
priors
|
||||
}
|
||||
|
||||
/// Puts back what `priors` recorded, newest write first.
|
||||
pub(crate) fn restore(registry: &mut Registry, priors: &[Prior]) {
|
||||
for prior in priors.iter().rev() {
|
||||
match prior {
|
||||
Prior::Node { id, live, removed } => put_whole(&mut registry.node_instances, &mut registry.removed_nodes, *id, live.as_ref(), removed.as_ref()),
|
||||
Prior::Network { id, live, removed } => put_whole(&mut registry.networks, &mut registry.removed_networks, *id, live.as_ref(), removed.as_ref()),
|
||||
Prior::Resource { id, live, removed } => put_whole(&mut registry.resources, &mut registry.removed_resources, *id, live.as_ref(), removed.as_ref()),
|
||||
Prior::NodeField { id, presence, field } => {
|
||||
let Some(node) = registry.node_instances.get_mut(id) else {
|
||||
debug_assert!(false, "a field prior is taken from a live node, which the later priors put back");
|
||||
continue;
|
||||
};
|
||||
node.presence = *presence;
|
||||
match field {
|
||||
NodeField::Presence => {}
|
||||
NodeField::Attribute { key, previous } => put_attribute(&mut node.attributes, key, previous.as_ref()),
|
||||
NodeField::Input { index, previous } => {
|
||||
if let Some(slot) = node.inputs.get_mut(*index as usize) {
|
||||
*slot = previous.clone();
|
||||
}
|
||||
}
|
||||
NodeField::InputAttribute { index, key, previous } => {
|
||||
if let Some(slot) = node.inputs.get_mut(*index as usize) {
|
||||
put_attribute(&mut slot.attributes, key, previous.as_ref());
|
||||
}
|
||||
}
|
||||
NodeField::Inputs { previous, inputs_timestamp } => {
|
||||
node.inputs = previous.clone();
|
||||
node.inputs_timestamp = *inputs_timestamp;
|
||||
}
|
||||
NodeField::Implementation { previous, implementation_timestamp } => {
|
||||
node.implementation = previous.clone();
|
||||
node.implementation_timestamp = *implementation_timestamp;
|
||||
}
|
||||
}
|
||||
}
|
||||
Prior::NetworkField { id, presence, field } => {
|
||||
let Some(network) = registry.networks.get_mut(id) else {
|
||||
debug_assert!(false, "a field prior is taken from a live network, which the later priors put back");
|
||||
continue;
|
||||
};
|
||||
network.presence = *presence;
|
||||
match field {
|
||||
NetworkField::Presence => {}
|
||||
NetworkField::Attribute { key, previous } => put_attribute(&mut network.attributes, key, previous.as_ref()),
|
||||
NetworkField::Exports { previous } => network.exports = previous.clone(),
|
||||
}
|
||||
}
|
||||
Prior::DocumentAttribute { key, previous } => put_attribute(&mut registry.attributes, key, previous.as_ref()),
|
||||
Prior::PeerUser { peer, previous } => match previous {
|
||||
Some(registration) => _ = registry.peer_users.insert(*peer, *registration),
|
||||
None => _ = registry.peer_users.remove(peer),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn whole_node(registry: &Registry, id: NodeId) -> Prior {
|
||||
Prior::Node {
|
||||
id,
|
||||
live: registry.node_instances.get(&id).cloned(),
|
||||
removed: registry.removed_nodes.get(&id).cloned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn whole_network(registry: &Registry, id: NetworkId) -> Prior {
|
||||
Prior::Network {
|
||||
id,
|
||||
live: registry.networks.get(&id).cloned(),
|
||||
removed: registry.removed_networks.get(&id).cloned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// One field of a live node; anything else, a write that lands on a tombstone or a placeholder, records the
|
||||
/// whole entity.
|
||||
fn node_field(registry: &Registry, id: NodeId, field: impl FnOnce(&Node) -> NodeField) -> Prior {
|
||||
match registry.node_instances.get(&id) {
|
||||
Some(node) => Prior::NodeField {
|
||||
id,
|
||||
presence: node.presence,
|
||||
field: field(node),
|
||||
},
|
||||
None => whole_node(registry, id),
|
||||
}
|
||||
}
|
||||
|
||||
fn network_field(registry: &Registry, id: NetworkId, field: impl FnOnce(&Network) -> NetworkField) -> Prior {
|
||||
match registry.networks.get(&id) {
|
||||
Some(network) => Prior::NetworkField {
|
||||
id,
|
||||
presence: network.presence,
|
||||
field: field(network),
|
||||
},
|
||||
None => whole_network(registry, id),
|
||||
}
|
||||
}
|
||||
|
||||
/// A write to one slot, or to the whole list when the slot doesn't exist yet, since writing past the end grows it.
|
||||
fn input_field(node: &Node, index: u32, field: impl FnOnce(&InputSlot) -> NodeField) -> NodeField {
|
||||
match node.inputs.get(index as usize) {
|
||||
Some(slot) => field(slot),
|
||||
None => NodeField::Inputs {
|
||||
previous: node.inputs.clone(),
|
||||
inputs_timestamp: node.inputs_timestamp,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn put_whole<K: Hash + Eq + Copy, T: Clone>(live: &mut HashMap<K, T>, dead: &mut HashMap<K, Tombstone<T>>, id: K, was_live: Option<&T>, was_removed: Option<&Tombstone<T>>) {
|
||||
match was_live {
|
||||
Some(content) => _ = live.insert(id, content.clone()),
|
||||
None => _ = live.remove(&id),
|
||||
}
|
||||
match was_removed {
|
||||
Some(mark) => _ = dead.insert(id, mark.clone()),
|
||||
None => _ = dead.remove(&id),
|
||||
}
|
||||
}
|
||||
|
||||
fn put_attribute(attributes: &mut crate::Attributes, key: &str, previous: Option<&AttributeValue>) {
|
||||
match previous {
|
||||
Some(value) => _ = attributes.insert(key.to_string(), value.clone()),
|
||||
None => _ = attributes.remove(key),
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,13 @@
|
||||
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
|
||||
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceEntry, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// The live document: what exists and what it holds.
|
||||
///
|
||||
/// Every field is last-writer-wins on a timestamp, including whether an entity exists, so the registry
|
||||
/// depends on the set of ops applied and not their order. A removed entity keeps a tombstone stamped with
|
||||
/// the removal: an op stamped earlier is dropped in either arrival order, and one stamped later revives the
|
||||
/// entity from it. The live maps hold only what exists.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Registry {
|
||||
pub node_instances: HashMap<NodeId, Node>,
|
||||
@@ -9,13 +15,55 @@ pub struct Registry {
|
||||
/// Content-addressable resources (images, fonts, eventually proto-node declarations) referenced
|
||||
/// by `ResourceId`. See [`ResourceStore`].
|
||||
pub resources: ResourceStore,
|
||||
/// Append-only mapping from per-device `PeerId` to per-human `UserId`.
|
||||
/// Registered by each device's first contribution via `RegistryDelta::RegisterPeer`.
|
||||
pub peer_users: HashMap<PeerId, UserId>,
|
||||
/// Which person each device is, registered via `RegistryDelta::RegisterPeer` by a device's first
|
||||
/// contribution and whenever its user changes. Lets undo and history authorship scope by person across
|
||||
/// the peer ids one person accumulates.
|
||||
pub peer_users: HashMap<PeerId, PeerRegistration>,
|
||||
pub attributes: Attributes,
|
||||
/// Tombstones of removed nodes, so an op on one is ordered against its removal whichever arrives first.
|
||||
#[serde(default)]
|
||||
pub removed_nodes: HashMap<NodeId, Tombstone<Node>>,
|
||||
/// Tombstones of removed networks; see [`removed_nodes`](Self::removed_nodes).
|
||||
#[serde(default)]
|
||||
pub removed_networks: HashMap<NetworkId, Tombstone<Network>>,
|
||||
/// Tombstones of removed resources; see [`removed_nodes`](Self::removed_nodes).
|
||||
#[serde(default)]
|
||||
pub removed_resources: HashMap<ResourceId, Tombstone<ResourceEntry>>,
|
||||
}
|
||||
|
||||
/// A device's registration to a person, and when it was made.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PeerRegistration {
|
||||
pub user: UserId,
|
||||
pub at: TimeStamp,
|
||||
}
|
||||
|
||||
/// A removed entity: its content, for reviving it, and when it was removed, for ordering later-arriving
|
||||
/// ops against the removal.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Tombstone<T> {
|
||||
pub content: T,
|
||||
pub at: TimeStamp,
|
||||
/// Nothing has added the entity yet, so it stays dead until an addition folds in; the content only holds
|
||||
/// writes that arrived ahead of it. See [`Registry::removed_nodes`].
|
||||
#[serde(default)]
|
||||
pub placeholder: bool,
|
||||
}
|
||||
|
||||
impl Registry {
|
||||
/// The node under `id`, live or as it was when removed. For a reference to a node the runtime cannot
|
||||
/// hold, which still needs the id the node had there.
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub(crate) fn node_or_removed(&self, id: NodeId) -> Option<&Node> {
|
||||
self.node_instances.get(&id).or_else(|| self.removed_nodes.get(&id).map(|mark| &mark.content))
|
||||
}
|
||||
|
||||
/// The network under `id`, live or as it was when removed.
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub(crate) fn network_or_removed(&self, id: NetworkId) -> Option<&Network> {
|
||||
self.networks.get(&id).or_else(|| self.removed_networks.get(&id).map(|mark| &mark.content))
|
||||
}
|
||||
|
||||
/// True if both registries agree on every value-bearing field, ignoring per-slot and
|
||||
/// per-attribute timestamps. Mirrors `compute_deltas`'s value-only semantics, so unchanged
|
||||
/// state at a stamped slot doesn't count as drift. `peer_users` is excluded: it isn't diffed by
|
||||
@@ -85,10 +133,10 @@ impl Registry {
|
||||
}
|
||||
|
||||
pub(crate) fn attributes_value_equal(a: &Attributes, b: &Attributes) -> bool {
|
||||
if a.len() != b.len() {
|
||||
if crate::attributes::live(a).count() != crate::attributes::live(b).count() {
|
||||
return false;
|
||||
}
|
||||
a.iter().all(|(key, value)| b.get(key).is_some_and(|other| value.value == other.value))
|
||||
crate::attributes::live(a).all(|(key, value)| b.get(key).is_some_and(|other| !other.deleted && value.value == other.value))
|
||||
}
|
||||
|
||||
/// Value-level resource comparison: same resolved hashes and same source chains (keyed by
|
||||
@@ -100,8 +148,8 @@ pub(crate) fn resources_value_equal(a: &ResourceStore, b: &ResourceStore) -> boo
|
||||
a.iter().all(|(id, entry)| {
|
||||
b.get(id).is_some_and(|other| {
|
||||
entry.hash == other.hash
|
||||
&& entry.sources.len() == other.sources.len()
|
||||
&& entry.sources.iter().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
|
||||
&& entry.live_sources().count() == other.live_sources().count()
|
||||
&& entry.live_sources().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -18,6 +18,21 @@ pub struct SourceKey {
|
||||
pub struct SourceValue {
|
||||
pub source: Value,
|
||||
pub timestamp: TimeStamp,
|
||||
/// A removed source stays as a stamped tombstone, so an older addition loses in either arrival order;
|
||||
/// readers see it as absent.
|
||||
#[serde(default)]
|
||||
pub deleted: bool,
|
||||
}
|
||||
|
||||
impl SourceValue {
|
||||
/// The tombstone of a source removed at `timestamp`.
|
||||
pub fn deleted(timestamp: TimeStamp) -> Self {
|
||||
Self {
|
||||
source: Value::None,
|
||||
timestamp,
|
||||
deleted: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A single content-addressable resource: an ordered, conflict-mergeable chain of fallback sources
|
||||
@@ -26,8 +41,13 @@ pub struct SourceValue {
|
||||
/// resource agree by construction, since the hash is content-derived).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
|
||||
pub struct ResourceEntry {
|
||||
/// The latest addition or write; see [`Node::presence`](crate::Node).
|
||||
pub(crate) presence: TimeStamp,
|
||||
/// Fallback chain kept sorted by `SourceKey`, so iteration yields highest-priority first.
|
||||
pub sources: Vec<(SourceKey, SourceValue)>,
|
||||
/// When `sources` was last written whole, by an addition of the entry. A key the chain does not hold is
|
||||
/// deleted as of then, as with [`Attributes`](crate::Attributes).
|
||||
pub sources_timestamp: TimeStamp,
|
||||
pub hash: Option<ResourceHash>,
|
||||
pub hash_timestamp: TimeStamp,
|
||||
}
|
||||
@@ -39,12 +59,22 @@ impl<'de> Deserialize<'de> for ResourceEntry {
|
||||
// collapse any duplicate keys, keeping the higher-timestamp value (LWW).
|
||||
#[derive(Deserialize)]
|
||||
struct Raw {
|
||||
#[serde(default)]
|
||||
presence: TimeStamp,
|
||||
sources: Vec<(SourceKey, SourceValue)>,
|
||||
#[serde(default)]
|
||||
sources_timestamp: TimeStamp,
|
||||
hash: Option<ResourceHash>,
|
||||
hash_timestamp: TimeStamp,
|
||||
}
|
||||
|
||||
let Raw { mut sources, hash, hash_timestamp } = Raw::deserialize(deserializer)?;
|
||||
let Raw {
|
||||
presence,
|
||||
mut sources,
|
||||
sources_timestamp,
|
||||
hash,
|
||||
hash_timestamp,
|
||||
} = Raw::deserialize(deserializer)?;
|
||||
sources.sort_by_key(|(a, _)| *a);
|
||||
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
|
||||
// `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW.
|
||||
@@ -57,7 +87,13 @@ impl<'de> Deserialize<'de> for ResourceEntry {
|
||||
true
|
||||
});
|
||||
|
||||
Ok(Self { sources, hash, hash_timestamp })
|
||||
Ok(Self {
|
||||
presence,
|
||||
sources,
|
||||
sources_timestamp,
|
||||
hash,
|
||||
hash_timestamp,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,77 +104,105 @@ impl ResourceEntry {
|
||||
pub fn embedded(hash: ResourceHash, peer: PeerId, timestamp: TimeStamp) -> Self {
|
||||
let embedded = to_value(&graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
|
||||
let priority = Priority::new(0.).expect("0. is finite");
|
||||
let sources = vec![(SourceKey { priority, peer }, SourceValue { source: embedded, timestamp })];
|
||||
let sources = vec![(
|
||||
SourceKey { priority, peer },
|
||||
SourceValue {
|
||||
source: embedded,
|
||||
timestamp,
|
||||
deleted: false,
|
||||
},
|
||||
)];
|
||||
|
||||
Self {
|
||||
presence: timestamp,
|
||||
sources,
|
||||
sources_timestamp: timestamp,
|
||||
hash: Some(hash),
|
||||
hash_timestamp: timestamp,
|
||||
}
|
||||
}
|
||||
|
||||
/// The source body and timestamp stored under `key`, if any.
|
||||
/// The live source stored under `key`, if any; a tombstone is absent.
|
||||
pub fn source(&self, key: &SourceKey) -> Option<&SourceValue> {
|
||||
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)).ok().map(|index| &self.sources[index].1)
|
||||
self.find(key).ok().map(|index| &self.sources[index].1).filter(|value| !value.deleted)
|
||||
}
|
||||
|
||||
/// Insert or LWW-overwrite the entry at `key`. A re-set at an existing key wins only if `value`'s
|
||||
/// timestamp is strictly newer; a fresh key is inserted in sorted position.
|
||||
pub fn set_source(&mut self, key: SourceKey, value: SourceValue) {
|
||||
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
|
||||
Ok(index) => {
|
||||
if value.timestamp > self.sources[index].1.timestamp {
|
||||
self.sources[index].1 = value;
|
||||
}
|
||||
}
|
||||
Err(index) => self.sources.insert(index, (key, value)),
|
||||
}
|
||||
/// The live sources in precedence order, tombstones skipped.
|
||||
pub(crate) fn live_sources(&self) -> impl Iterator<Item = (&SourceKey, &SourceValue)> {
|
||||
self.sources.iter().filter(|(_, value)| !value.deleted).map(|(key, value)| (key, value))
|
||||
}
|
||||
|
||||
/// Like [`set_source`](Self::set_source) but assigns unconditionally (silent-zone rewind), where the
|
||||
/// precomputed reverse/forward value is authoritative even if its timestamp ties what it replaces.
|
||||
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
|
||||
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
|
||||
fn find(&self, key: &SourceKey) -> Result<usize, usize> {
|
||||
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key))
|
||||
}
|
||||
|
||||
/// The stamp that decides a write to `key`: its entry's, tombstone included, or the chain's floor.
|
||||
fn decided(&self, key: &SourceKey) -> TimeStamp {
|
||||
self.find(key).map_or(self.sources_timestamp, |index| self.sources[index].1.timestamp)
|
||||
}
|
||||
|
||||
fn put(&mut self, key: SourceKey, value: SourceValue) {
|
||||
match self.find(&key) {
|
||||
Ok(index) => self.sources[index].1 = value,
|
||||
Err(index) => self.sources.insert(index, (key, value)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the entry at `key` if its timestamp is strictly older than `timestamp` (LWW). Returns
|
||||
/// whether anything was removed.
|
||||
pub fn remove_source(&mut self, key: &SourceKey, timestamp: TimeStamp) -> bool {
|
||||
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) {
|
||||
Ok(index) if timestamp > self.sources[index].1.timestamp => {
|
||||
self.sources.remove(index);
|
||||
true
|
||||
/// Writes the chain whole at `at`: the floor deletes every other key without a tombstone per key.
|
||||
pub(crate) fn stamp_sources(&mut self, at: TimeStamp) {
|
||||
self.sources.retain(|(_, value)| !value.deleted);
|
||||
self.sources.iter_mut().for_each(|(_, value)| value.timestamp = at);
|
||||
self.sources_timestamp = at;
|
||||
}
|
||||
|
||||
/// Folds another chain in key by key, the way attribute maps merge: a key only one chain holds is
|
||||
/// dead when the other chain's floor is newer than it, and the newer entry wins where both hold a key.
|
||||
pub(crate) fn merge_sources(&mut self, other: Vec<(SourceKey, SourceValue)>, other_floor: TimeStamp) {
|
||||
self.sources.retain(|(_, value)| value.timestamp >= other_floor);
|
||||
for (key, value) in other {
|
||||
match self.find(&key) {
|
||||
Ok(index) if value.timestamp > self.sources[index].1.timestamp => self.sources[index].1 = value,
|
||||
Err(index) if value.timestamp >= self.sources_timestamp => self.sources.insert(index, (key, value)),
|
||||
_ => {}
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
self.sources_timestamp = self.sources_timestamp.max(other_floor);
|
||||
}
|
||||
|
||||
/// Insert or LWW-overwrite the entry at `key`. A re-set at an existing key wins only if `value`'s
|
||||
/// timestamp is strictly newer; a fresh key is inserted in sorted position.
|
||||
pub fn set_source(&mut self, key: SourceKey, value: SourceValue) {
|
||||
if value.timestamp > self.decided(&key) {
|
||||
self.put(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
/// Like [`remove_source`](Self::remove_source) but removes unconditionally (silent-zone rewind).
|
||||
pub fn force_remove_source(&mut self, key: &SourceKey) -> bool {
|
||||
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) {
|
||||
Ok(index) => {
|
||||
self.sources.remove(index);
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
/// Like [`set_source`](Self::set_source) but assigns unconditionally, for building an entry.
|
||||
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
|
||||
self.put(key, value);
|
||||
}
|
||||
|
||||
/// Remove the source at `key` if what decides it is strictly older than `timestamp` (LWW), leaving a
|
||||
/// tombstone. Returns whether the removal landed.
|
||||
pub fn remove_source(&mut self, key: &SourceKey, timestamp: TimeStamp) -> bool {
|
||||
if timestamp <= self.decided(key) {
|
||||
return false;
|
||||
}
|
||||
self.put(*key, SourceValue::deleted(timestamp));
|
||||
true
|
||||
}
|
||||
|
||||
/// True if the chain already carries a `DataSource::Embedded` source. Decodes each source body into
|
||||
/// `DataSource` so a shape change in the serialized form can't slip an embedded source past detection.
|
||||
pub fn has_embedded_source(&self) -> bool {
|
||||
self.sources
|
||||
.iter()
|
||||
self.live_sources()
|
||||
.any(|(_, value)| matches!(from_value::<graphene_resource::DataSource>(&value.source), Ok(graphene_resource::DataSource::Embedded)))
|
||||
}
|
||||
|
||||
/// A `SourceKey` ordered strictly ahead of every current source, so an inserted entry becomes the
|
||||
/// highest-precedence fallback.
|
||||
pub fn highest_precedence_key(&self, peer: PeerId) -> SourceKey {
|
||||
let min_priority = self.sources.first().map(|(key, _)| key.priority.value()).unwrap_or(0.);
|
||||
let min_priority = self.live_sources().next().map(|(key, _)| key.priority.value()).unwrap_or(0.);
|
||||
SourceKey {
|
||||
priority: Priority::new(min_priority - 1.).expect("finite priority minus one is finite"),
|
||||
peer,
|
||||
@@ -247,12 +311,15 @@ mod tests {
|
||||
SourceValue {
|
||||
source: Value::Float(priority),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
deleted: false,
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
// Build a deliberately unsorted chain as a literal (bypassing the sorted-insert API), then round-trip it through `Value`.
|
||||
let unsorted = ResourceEntry {
|
||||
presence: TimeStamp::ORIGIN,
|
||||
sources_timestamp: TimeStamp::ORIGIN,
|
||||
sources: vec![source(2.), source(0.), source(1.)],
|
||||
hash: None,
|
||||
hash_timestamp: TimeStamp::ORIGIN,
|
||||
@@ -277,11 +344,14 @@ mod tests {
|
||||
SourceValue {
|
||||
source: Value::Str(body.into()),
|
||||
timestamp: TimeStamp { counter, peer: PeerId(1) },
|
||||
deleted: false,
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
let with_duplicates = ResourceEntry {
|
||||
presence: TimeStamp::ORIGIN,
|
||||
sources_timestamp: TimeStamp::ORIGIN,
|
||||
sources: vec![entry(5, "newer"), entry(1, "older")],
|
||||
hash: None,
|
||||
hash_timestamp: TimeStamp::ORIGIN,
|
||||
|
||||
@@ -29,22 +29,17 @@ impl Session {
|
||||
Self::with_peer(PeerId(core_types::uuid::generate_uuid()))
|
||||
}
|
||||
|
||||
/// Construct a session bound to a specific `PeerId`. Used by tests; production code wants
|
||||
/// `Session::new`.
|
||||
/// A session for `peer` standing for itself as a person. For tests and tools without a stored identity;
|
||||
/// a working copy wants [`with_identity`](Self::with_identity).
|
||||
pub fn with_peer(peer: PeerId) -> Self {
|
||||
Self::with_identity(peer, UserId(peer.0))
|
||||
}
|
||||
|
||||
/// A session for device `peer` used by person `user`. The user is what the peer's registration records,
|
||||
/// and what undo and history authorship scope by.
|
||||
pub fn with_identity(peer: PeerId, user: UserId) -> Self {
|
||||
Self {
|
||||
document: Document {
|
||||
working_registry: Registry::default(),
|
||||
retired_snapshot: Registry::default(),
|
||||
history: History::new(),
|
||||
hot_log: Vec::new(),
|
||||
head: None,
|
||||
redo_stack: Vec::new(),
|
||||
clock: LamportClock::new(peer),
|
||||
peer,
|
||||
last_broadcast_rev: None,
|
||||
next_node_counter: 0,
|
||||
},
|
||||
document: Document::empty(peer, user),
|
||||
remote_tips: HashMap::new(),
|
||||
}
|
||||
}
|
||||
@@ -53,6 +48,22 @@ impl Session {
|
||||
self.document.peer
|
||||
}
|
||||
|
||||
pub fn user(&self) -> UserId {
|
||||
self.document.user
|
||||
}
|
||||
|
||||
/// The person a peer is registered to, if its registration has landed here.
|
||||
pub fn user_of(&self, peer: PeerId) -> Option<UserId> {
|
||||
let registered = || self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user);
|
||||
(peer == self.document.peer).then_some(self.document.user).or_else(registered)
|
||||
}
|
||||
|
||||
/// Whether `peer` is this person: this device, or another registered to the same user. Undo in a
|
||||
/// session scopes by this, so a fresh copy of a document still undoes what its user did from another.
|
||||
pub fn is_mine(&self, peer: PeerId) -> bool {
|
||||
self.user_of(peer) == Some(self.document.user)
|
||||
}
|
||||
|
||||
pub fn registry(&self) -> &Registry {
|
||||
&self.document.working_registry
|
||||
}
|
||||
@@ -142,25 +153,45 @@ impl Session {
|
||||
///
|
||||
/// The peer's first contribution is preceded by a `RegisterPeer` op, so the device's
|
||||
/// `PeerId → UserId` mapping is established (and, under causal delivery, observed by other peers)
|
||||
/// before any of its edits. A no-op batch doesn't register — registration rides a real edit.
|
||||
fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
/// before any of its edits. A no-op batch doesn't register, since registration rides a real edit.
|
||||
pub(crate) fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
// A batch is staged whole or not at all: a refused op takes back the ones before it, which reached nothing yet.
|
||||
let mut pending: Vec<RegistryDelta> = ops.into_iter().collect();
|
||||
if pending.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
if !self.document.working_registry.peer_users.contains_key(&self.document.peer) {
|
||||
let user = UserId(self.document.peer.0);
|
||||
pending.insert(0, RegistryDelta::RegisterPeer { peer: self.document.peer, user });
|
||||
let (peer, user) = (self.document.peer, self.document.user);
|
||||
if self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user) != Some(user) {
|
||||
pending.insert(0, RegistryDelta::RegisterPeer { peer, user });
|
||||
}
|
||||
|
||||
// Reusing a sequence would let retirement marks drop the new op, so a batch that would run past the end is refused whole.
|
||||
if self.document.last_hot_sequence.0.checked_add(pending.len() as u64).is_none() {
|
||||
return Err(CrdtError::SequencesExhausted);
|
||||
}
|
||||
|
||||
let sequence_before = self.document.last_hot_sequence;
|
||||
let mut staged = Vec::with_capacity(pending.len());
|
||||
for op in pending {
|
||||
let sequence = HotSequence(self.document.last_hot_sequence.0 + 1);
|
||||
let hot_op = HotOp {
|
||||
op,
|
||||
timestamp: self.document.clock.tick(),
|
||||
sequence,
|
||||
};
|
||||
self.document.apply_hot_op(hot_op.clone())?;
|
||||
if let Err(error) = self.document.apply_hot_op(hot_op.clone(), ApplyMode::Live) {
|
||||
// The run continues where it was, so no sequence goes unused.
|
||||
self.document.last_hot_sequence = sequence_before;
|
||||
if !staged.is_empty() {
|
||||
let taken: HashSet<HotOpId> = staged.iter().map(HotOp::id).collect();
|
||||
self.document.hot_log.retain(|hot_op| !taken.contains(&hot_op.id()));
|
||||
self.document.resync_hot_timestamps();
|
||||
self.document.rebuild_working();
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
self.document.last_hot_sequence = sequence;
|
||||
staged.push(hot_op);
|
||||
}
|
||||
Ok(staged)
|
||||
@@ -168,19 +199,26 @@ impl Session {
|
||||
|
||||
/// Wrap each op as a `Delta`, apply it, and chain it onto the local history. One tick per op.
|
||||
///
|
||||
/// Operates on the *retired snapshot*: reverses are computed against and forward ops applied to it,
|
||||
/// so each `reverse` captures the true pre-op value rather than the hot-polluted working state. The
|
||||
/// Operates on the *retired snapshot*: each `reverse` is captured from it and the forward op applied to it, so
|
||||
/// the reverse holds the true pre-op state rather than the hot-polluted working state. The
|
||||
/// working registry already reflects these ops (they were staged as hot ops before retirement, or
|
||||
/// equal the snapshot when there are none), so it is left untouched.
|
||||
///
|
||||
/// `idempotent`: pass `true` when the snapshot already reflects the op (retirement of an already-
|
||||
/// applied hot op) so duplicate structural inserts no-op rather than error.
|
||||
fn commit_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>, idempotent: bool) -> Result<Vec<Rev>, CrdtError> {
|
||||
self.commit_ops_authored_at(ops.into_iter().map(|op| (op, None)), idempotent)
|
||||
}
|
||||
|
||||
/// [`commit_ops`](Self::commit_ops) for ops authored elsewhere, paired with the timestamp they were
|
||||
/// authored at (`None` to mint one). The delta's timestamp is what the registry resolves LWW on, so
|
||||
/// retirement passes the op's own.
|
||||
fn commit_ops_authored_at(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Option<TimeStamp>)>, idempotent: bool) -> Result<Vec<Rev>, CrdtError> {
|
||||
let target = RegistryTarget::Snapshot;
|
||||
let ops = ops.into_iter();
|
||||
let mut produced = Vec::with_capacity(ops.size_hint().0);
|
||||
|
||||
for op in ops {
|
||||
for (op, authored_at) in ops {
|
||||
// A new edit abandons any undone-forward branch: those revs stay in the DAG but are no
|
||||
// longer reachable via redo. (Mirrors the legacy editor clearing its redo history on
|
||||
// commit.) Done on the first real op so a no-op commit doesn't silently disable redo.
|
||||
@@ -188,10 +226,10 @@ impl Session {
|
||||
self.document.redo_stack.clear();
|
||||
}
|
||||
|
||||
let reverse = self.document.compute_reverse_delta(target, &op)?;
|
||||
let timestamp = self.document.clock.tick();
|
||||
let reverse = crate::prior::capture(self.document.registry_ref(target), &op);
|
||||
let timestamp = authored_at.unwrap_or_else(|| self.document.clock.tick());
|
||||
let parent = self.document.head;
|
||||
let author = self.document.peer;
|
||||
let author = timestamp.peer;
|
||||
|
||||
let delta = Delta::new(parent, author, timestamp, op, reverse);
|
||||
let rev = delta.id;
|
||||
@@ -215,7 +253,7 @@ impl Session {
|
||||
/// Wrap an already-materialized snapshot. Trusts `registry` to match `history`; advances the
|
||||
/// clock past every observed timestamp but does not re-apply ops. `history` is taken in on-disk
|
||||
/// (topological) order.
|
||||
pub fn load(peer: PeerId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64) -> Self {
|
||||
pub fn load(peer: PeerId, user: UserId, registry: Registry, history: Vec<Delta>, head: Option<Rev>, redo_stack: Vec<Rev>, next_node_counter: u64) -> Self {
|
||||
let mut clock = LamportClock::new(peer);
|
||||
for delta in &history {
|
||||
clock.observe(delta.timestamp);
|
||||
@@ -228,13 +266,11 @@ impl Session {
|
||||
retired_snapshot: registry.clone(),
|
||||
working_registry: registry,
|
||||
history: History::from_ordered(history),
|
||||
hot_log: Vec::new(),
|
||||
head,
|
||||
redo_stack,
|
||||
clock,
|
||||
peer,
|
||||
last_broadcast_rev: None,
|
||||
next_node_counter,
|
||||
..Document::empty(peer, user)
|
||||
},
|
||||
remote_tips: HashMap::new(),
|
||||
}
|
||||
@@ -242,8 +278,8 @@ impl Session {
|
||||
|
||||
/// Rebuild the registry from scratch by applying every delta in causal order.
|
||||
/// `deltas` must be in causal order (every parent before its children).
|
||||
pub fn replay_from_history(peer: PeerId, deltas: impl IntoIterator<Item = Delta>, next_node_counter: u64) -> Result<Self, CrdtError> {
|
||||
let mut session = Self::with_peer(peer);
|
||||
pub fn replay_from_history(peer: PeerId, user: UserId, deltas: impl IntoIterator<Item = Delta>, next_node_counter: u64) -> Result<Self, CrdtError> {
|
||||
let mut session = Self::with_identity(peer, user);
|
||||
session.document.next_node_counter = next_node_counter;
|
||||
|
||||
for delta in deltas {
|
||||
@@ -258,9 +294,21 @@ impl Session {
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// Apply a hot op without going through the broadcast stream.
|
||||
/// Apply a hot op from another peer. Idempotent, and a no-op for one history already covers: a late
|
||||
/// delivery must not put a retired op back in the hot log.
|
||||
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
||||
self.document.apply_hot_op(hot_op)
|
||||
self.document.replay_hot_op(hot_op)
|
||||
}
|
||||
|
||||
/// Which hot ops are done with, for a peer catching up and for persisting. See [`SettledHotOps`].
|
||||
pub fn settled_marks(&self) -> &SettledHotOps {
|
||||
&self.document.settled
|
||||
}
|
||||
|
||||
/// Take on a peer's marks, or this peer's persisted ones: whatever they cover that the hot log still holds is
|
||||
/// dropped, and the working registry re-derived without it.
|
||||
pub fn absorb_settled_marks(&mut self, remote: &SettledHotOps) {
|
||||
self.document.absorb_settled(remote);
|
||||
}
|
||||
|
||||
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
|
||||
@@ -269,57 +317,52 @@ impl Session {
|
||||
self.document.replay_hot_op(hot_op)
|
||||
}
|
||||
|
||||
/// Integrate `incoming` retired deltas from another branch and emit a [`RegistryDelta::Merge`]
|
||||
/// joining the resulting tips, returning the new merge `Rev` (or `None` if `incoming` adds nothing).
|
||||
/// Applies each incoming op to the registry, then hands the set to [`History::merge`]. Incoming
|
||||
/// deltas must arrive in causal order.
|
||||
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) -> Result<Option<Rev>, CrdtError> {
|
||||
let mut absorbed: Vec<Delta> = Vec::new();
|
||||
for delta in incoming {
|
||||
if self.document.history.contains(delta.id) {
|
||||
continue;
|
||||
}
|
||||
self.document.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
|
||||
absorbed.push(delta);
|
||||
/// The retired snapshot as history alone produces it, independent of arrival order and the hot log.
|
||||
/// Folded over `head`'s ancestry only: an undone delta stays in the DAG for redo to find, and folding
|
||||
/// all of history would restore work the user undid.
|
||||
pub fn snapshot_from_history(&self) -> Result<Registry, CrdtError> {
|
||||
// Every op lands the same whatever order it arrives in, so applying each once is the fold.
|
||||
let reachable = self.document.history.ancestors(self.document.head);
|
||||
let mut scratch = Document::empty(self.document.peer, self.document.user);
|
||||
for delta in self.document.history.iter().filter(|delta| reachable.contains(&delta.id)) {
|
||||
scratch.apply_op_with(RegistryTarget::Working, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
|
||||
}
|
||||
if absorbed.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
self.document.history.merge(absorbed);
|
||||
let tips = self.document.history.tips();
|
||||
let timestamp = self.document.clock.tick();
|
||||
let merge = Delta::merge(tips, self.document.peer, timestamp);
|
||||
let merge_rev = merge.id;
|
||||
// The merge's parents are the current tips, so it sorts last: `push` preserves the canonical
|
||||
// order without re-sorting the whole history.
|
||||
self.document.history.push(merge);
|
||||
self.document.head = Some(merge_rev);
|
||||
|
||||
// Merge runs with an empty hot log; keep the retired snapshot in step with the working registry.
|
||||
self.document.retired_snapshot = self.document.working_registry.clone();
|
||||
Ok(Some(merge_rev))
|
||||
Ok(scratch.working_registry)
|
||||
}
|
||||
|
||||
/// Promote hot ops with timestamp `≤ up_to` into retired deltas, re-applied with fresh
|
||||
/// retirement timestamps so LWW arms bump field timestamps to `T_retire`.
|
||||
pub fn history_len(&self) -> usize {
|
||||
self.document.history.len()
|
||||
}
|
||||
|
||||
/// The hot ops stamped at or before `up_to`, which [`retire`](Self::retire) drains. Sent with the deltas,
|
||||
/// since a lagging op can arrive below the cutoff afterwards.
|
||||
pub fn hot_ops_up_to(&self, up_to: TimeStamp) -> Vec<HotOpId> {
|
||||
self.document.hot_log.iter().filter(|hot_op| hot_op.timestamp <= up_to).map(HotOp::id).collect()
|
||||
}
|
||||
|
||||
/// Promote the given hot ops into retired deltas, in hot-log order, each keeping the timestamp it was
|
||||
/// authored at. Markers commit nothing. Ops not in the log are ignored.
|
||||
///
|
||||
/// Today: one retired delta per hot op. Coarsening is a future step.
|
||||
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, CrdtError> {
|
||||
let mut drained = Vec::new();
|
||||
let mut remaining = Vec::with_capacity(self.document.hot_log.len());
|
||||
for hot_op in self.document.hot_log.drain(..) {
|
||||
if hot_op.timestamp <= up_to {
|
||||
drained.push(hot_op);
|
||||
} else {
|
||||
remaining.push(hot_op);
|
||||
}
|
||||
}
|
||||
self.document.hot_log = remaining;
|
||||
/// One retired delta per hot op.
|
||||
pub fn retire_hot_ops(&mut self, ids: &[HotOpId]) -> Result<Vec<Rev>, CrdtError> {
|
||||
let wanted: HashSet<HotOpId> = ids.iter().copied().collect();
|
||||
let (drained, kept): (Vec<HotOp>, Vec<HotOp>) = self.document.hot_log.drain(..).partition(|hot_op| wanted.contains(&hot_op.id()));
|
||||
self.document.hot_log = kept;
|
||||
self.document.resync_hot_timestamps();
|
||||
self.document.settled.extend(drained.iter().map(HotOp::id));
|
||||
|
||||
self.commit_ops(drained.into_iter().map(|hot_op| hot_op.op), true)
|
||||
let ops = drained
|
||||
.into_iter()
|
||||
.filter(|hot_op| !matches!(hot_op.op, RegistryDelta::EndTransaction))
|
||||
.map(|hot_op| (hot_op.op, Some(hot_op.timestamp)));
|
||||
self.commit_ops_authored_at(ops, true)
|
||||
}
|
||||
|
||||
/// Promote every hot op stamped at or before `up_to`, whatever its author.
|
||||
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, CrdtError> {
|
||||
let ids = self.hot_ops_up_to(up_to);
|
||||
self.retire_hot_ops(&ids)
|
||||
}
|
||||
/// Mark a retired delta as the end of a user interaction, so the undo cursor treats it as a checkpoint.
|
||||
/// Called once per interaction by the editor-facing commit path (not by resource/internal commits).
|
||||
pub fn mark_interaction_end(&mut self, rev: Rev) {
|
||||
@@ -335,33 +378,31 @@ impl Session {
|
||||
self.document.history.annotate(rev, key, value, timestamp)
|
||||
}
|
||||
|
||||
/// Whether there is a retired commit at `head` that can be undone in the silent zone (a commit
|
||||
/// after `last_broadcast_rev`). `head == 0` is the empty history; published commits aren't
|
||||
/// silently undoable (that needs a forward reverse-delta op, deferred until transport lands).
|
||||
///
|
||||
/// The earliest interaction (the document's loaded/created base) is *not* undoable: undoing it would
|
||||
/// rewind into the pre-base state, which legacy never offers (opening a document gives an empty undo
|
||||
/// history). We detect "head is on the earliest interaction" by walking `head`'s interaction back along
|
||||
/// first-parents and checking whether it bottoms out at the root with no earlier interaction boundary to
|
||||
/// land on. If so, there is nothing before this interaction to undo to, so undo is disabled.
|
||||
/// Whether the interaction at `head` can be undone in the silent zone: it is this user's own, holds no merge, and
|
||||
/// nothing in it was published, since rewinding a step peers hold would diverge from them. The document's first
|
||||
/// interaction is not undoable, as opening a document starts with an empty undo history.
|
||||
pub fn can_undo(&self) -> bool {
|
||||
let Some(head) = self.document.head else { return false };
|
||||
if self.document.last_broadcast_rev == Some(head) {
|
||||
return false;
|
||||
}
|
||||
self.interaction_start_parent(head).is_some()
|
||||
self.document.head.is_some_and(|head| self.interaction_start_parent(head, true).is_some())
|
||||
}
|
||||
|
||||
/// Walk the interaction containing `rev` back along first-parents to its first delta, returning the
|
||||
/// rev the cursor would rest on after undoing this interaction, or `None` if that is the root (the
|
||||
/// earliest interaction, which is not undoable). Mirrors the boundary condition in [`undo`](Self::undo):
|
||||
/// stop when the parent is an `interaction_end` boundary or the root.
|
||||
fn interaction_start_parent(&self, rev: Rev) -> Option<Rev> {
|
||||
let mut current = rev;
|
||||
/// The rev the cursor rests on once the interaction ending at `end` is undone: the parent where the previous
|
||||
/// interaction ended, a merge, or another user's delta begins. `None` when `end` is a merge, the interaction starts
|
||||
/// at the root, or, for a `silent` undo, it is not this user's or holds a published delta.
|
||||
fn interaction_start_parent(&self, end: Rev, silent: bool) -> Option<Rev> {
|
||||
let history = &self.document.history;
|
||||
let mut current = history.get(end)?;
|
||||
let user = self.user_of(current.author);
|
||||
if matches!(current.kind, RegistryDelta::Merge { .. }) || (silent && user != Some(self.document.user)) {
|
||||
return None;
|
||||
}
|
||||
let boundary = |delta: &Delta| delta.is_interaction_end() || matches!(delta.kind, RegistryDelta::Merge { .. }) || self.user_of(delta.author) != user;
|
||||
loop {
|
||||
let parent = self.document.history.get(current)?.parent?;
|
||||
if self.document.history.get(parent).is_some_and(|d| d.is_interaction_end()) {
|
||||
return Some(parent);
|
||||
if silent && self.document.last_broadcast_rev == Some(current.id) {
|
||||
return None;
|
||||
}
|
||||
let parent = history.get(current.parent?)?;
|
||||
if boundary(parent) {
|
||||
return Some(parent.id);
|
||||
}
|
||||
current = parent;
|
||||
}
|
||||
@@ -371,37 +412,22 @@ impl Session {
|
||||
!self.document.redo_stack.is_empty()
|
||||
}
|
||||
|
||||
/// Silent-zone undo of one *interaction*: revert deltas walking `head` back along first-parents until
|
||||
/// it reaches the previous interaction boundary (a delta marked `interaction_end`) or the empty root. One
|
||||
/// interaction spans several deltas (one `commit_from_runtime` batch), so undo reverts the whole run,
|
||||
/// not a single delta — matching the legacy per-interaction undo granularity. The undone interaction's
|
||||
/// `head` rev is pushed onto the redo stack. Reflog semantics: the DAG is never rewritten.
|
||||
/// Silent-zone undo of one interaction: put back what its deltas overwrote, newest first, until `head` rests where it
|
||||
/// began (see [`can_undo`](Self::can_undo)). Its `head` rev goes on the redo stack; the DAG is not rewritten.
|
||||
pub fn undo(&mut self) -> Result<Rev, CrdtError> {
|
||||
if !self.can_undo() {
|
||||
return Err(CrdtError::NothingToUndo);
|
||||
}
|
||||
let checkpoint = self.document.head.ok_or(CrdtError::NothingToUndo)?;
|
||||
let base = self.interaction_start_parent(checkpoint, true).ok_or(CrdtError::NothingToUndo)?;
|
||||
|
||||
// Revert this interaction's last delta, then keep going back until `head` rests on the previous
|
||||
// interaction's boundary (its `interaction_end` delta) or the root.
|
||||
loop {
|
||||
let rev = self.document.head.ok_or(CrdtError::NothingToUndo)?;
|
||||
while let Some(rev) = self.document.head.filter(|&rev| rev != base) {
|
||||
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
|
||||
let parent = delta.parent;
|
||||
|
||||
self.document.revert_delta(RegistryTarget::Working, delta)?;
|
||||
self.document.head = parent;
|
||||
|
||||
match parent {
|
||||
None => break,
|
||||
Some(parent) if self.document.history.get(parent).is_some_and(|d| d.is_interaction_end()) => break,
|
||||
Some(_) => {}
|
||||
}
|
||||
self.document.revert_delta(&delta);
|
||||
self.document.head = delta.parent;
|
||||
}
|
||||
|
||||
// Undo runs with an empty hot log, so keep the retired snapshot in lockstep with the rewound
|
||||
// working registry (the next interaction's reverses are computed against it).
|
||||
self.document.retired_snapshot = self.document.working_registry.clone();
|
||||
// With ops hot, working is the rewound snapshot plus them.
|
||||
if !self.document.hot_log.is_empty() {
|
||||
self.document.rebuild_working();
|
||||
}
|
||||
self.document.redo_stack.push(checkpoint);
|
||||
Ok(checkpoint)
|
||||
}
|
||||
@@ -421,23 +447,28 @@ impl Session {
|
||||
forward.push(delta);
|
||||
}
|
||||
|
||||
// Force-apply so each forward value wins the LWW tie against the reverse that undo force-applied
|
||||
// at the same timestamp. Symmetric with `revert_delta`.
|
||||
// Undo left the snapshot exactly at the fold up to `head`, so applying the deltas as retirement did folds
|
||||
// them in again, a newer write merged in before them still winning over theirs.
|
||||
let hot = !self.document.hot_log.is_empty();
|
||||
for delta in forward.into_iter().rev() {
|
||||
self.document.force_apply_op(delta.kind.clone(), delta.timestamp)?;
|
||||
self.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
|
||||
if !hot {
|
||||
self.document.apply_op_with(RegistryTarget::Working, delta.kind, delta.timestamp, ApplyMode::Idempotent)?;
|
||||
}
|
||||
}
|
||||
if hot {
|
||||
self.document.rebuild_working();
|
||||
}
|
||||
self.document.head = Some(checkpoint);
|
||||
|
||||
// Redo runs with an empty hot log; keep the retired snapshot in lockstep with the working registry.
|
||||
self.document.retired_snapshot = self.document.working_registry.clone();
|
||||
Ok(checkpoint)
|
||||
}
|
||||
|
||||
/// Build a synthetic linear history whose replay reproduces `registry`. Each op gets a
|
||||
/// freshly-ticked clock timestamp and chains to the previous op's `Rev`.
|
||||
pub fn bootstrap_from_registry(peer: PeerId, registry: Registry) -> Result<Self, CrdtError> {
|
||||
pub fn bootstrap_from_registry(peer: PeerId, user: UserId, registry: Registry) -> Result<Self, CrdtError> {
|
||||
let ops = crate::delta::compute_deltas(&Registry::default(), ®istry);
|
||||
let mut session = Self::with_peer(peer);
|
||||
let mut session = Self::with_identity(peer, user);
|
||||
session.commit_ops(ops, false)?;
|
||||
// No hot ops on this path, so the working registry must mirror the freshly-built snapshot.
|
||||
session.document.working_registry = session.document.retired_snapshot.clone();
|
||||
@@ -468,15 +499,7 @@ impl Session {
|
||||
/// bytes. Walks current resources plus each delta's `AddResource`/`RemoveResource` snapshot.
|
||||
pub fn all_referenced_resource_hashes(&self) -> HashSet<ResourceHash> {
|
||||
let mut hashes: HashSet<ResourceHash> = self.document.working_registry.resources.values().filter_map(|entry| entry.hash).collect();
|
||||
|
||||
for delta in self.document.history.iter() {
|
||||
match &delta.kind {
|
||||
RegistryDelta::AddResource { entry, .. } => hashes.extend(entry.hash),
|
||||
RegistryDelta::RemoveResource { snapshot, .. } => hashes.extend(snapshot.hash),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
hashes.extend(self.document.history.resource_hashes());
|
||||
hashes
|
||||
}
|
||||
|
||||
@@ -542,7 +565,7 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Test-only: commit a single op as a retired delta on the local chain, returning the result so a
|
||||
/// test can observe a resurrection failure (e.g. `NotFoundInHistory`).
|
||||
/// test can observe a failure (e.g. `NotFoundInHistory`).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn commit_op_for_test(&mut self, op: RegistryDelta) -> Result<(), CrdtError> {
|
||||
self.commit_ops(std::iter::once(op), false).map(|_| ())
|
||||
@@ -555,6 +578,29 @@ impl Session {
|
||||
pub fn next_node_counter(&self) -> u64 {
|
||||
self.document.next_node_counter
|
||||
}
|
||||
|
||||
/// The sequence of the last hot op this peer authored, which is how many it has. Carried across a reload, so no
|
||||
/// sequence is spent twice.
|
||||
pub fn last_hot_sequence(&self) -> HotSequence {
|
||||
self.document.last_hot_sequence
|
||||
}
|
||||
|
||||
/// The Lamport counter, persisted so a reopen never mints a stamp it already spent, even one no op in history or
|
||||
/// the hot log carries any more.
|
||||
pub fn clock_counter(&self) -> u64 {
|
||||
self.document.clock.counter
|
||||
}
|
||||
|
||||
/// Continue the Lamport clock after a load. Raises only, like observing an op.
|
||||
pub fn restore_clock(&mut self, counter: u64) {
|
||||
self.document.clock.counter = self.document.clock.counter.max(counter);
|
||||
}
|
||||
|
||||
/// Restore the authored-op count after a load, keeping a fresh op off a spent sequence. Raises only:
|
||||
/// replaying a persisted hot log afterwards cannot lower it.
|
||||
pub fn restore_hot_sequence(&mut self, sequence: HotSequence) {
|
||||
self.document.last_hot_sequence = self.document.last_hot_sequence.max(sequence);
|
||||
}
|
||||
}
|
||||
|
||||
/// Errors from `Session::commit_from_runtime`.
|
||||
@@ -580,10 +626,122 @@ impl Default for Session {
|
||||
pub struct HotOp {
|
||||
pub op: RegistryDelta,
|
||||
pub timestamp: TimeStamp,
|
||||
/// Position in its author's run. See [`HotSequence`].
|
||||
pub sequence: HotSequence,
|
||||
}
|
||||
|
||||
impl HotOp {
|
||||
/// Identifies the op in the settled marks, which track a contiguous prefix per author.
|
||||
pub fn id(&self) -> HotOpId {
|
||||
HotOpId {
|
||||
peer: self.timestamp.peer,
|
||||
sequence: self.sequence,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Position in one author's run of hot ops, counting from 1 with no gaps. Kept apart from the Lamport
|
||||
/// counter, which skips on observing a higher remote timestamp and so cannot bound a contiguous prefix.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct HotSequence(pub u64);
|
||||
|
||||
impl HotSequence {
|
||||
/// Before this author has written anything, covering no op.
|
||||
pub const NONE: Self = Self(0);
|
||||
|
||||
/// The position after this one, for adjacency. Saturates: a run ending at the last position has no successor.
|
||||
pub fn next(self) -> Self {
|
||||
Self(self.0.saturating_add(1))
|
||||
}
|
||||
}
|
||||
|
||||
/// One hot op's author and position in its run. Retirement names promoted ops by these, which tells a
|
||||
/// receiver which prefix history covers.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct HotOpId {
|
||||
pub peer: PeerId,
|
||||
pub sequence: HotSequence,
|
||||
}
|
||||
|
||||
/// Which hot ops are retired into history: `settled_up_to` is each author's gap-free prefix, and `settled_beyond`
|
||||
/// the settled ops past it. Gaps exist only while ops are in flight, so an author collapses to its prefix. Replicated and persisted, so a
|
||||
/// late copy of a settled op is dropped wherever it lands.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SettledHotOps {
|
||||
pub settled_up_to: HashMap<PeerId, HotSequence>,
|
||||
/// Settled ops past their author's prefix, as inclusive runs, one per gap in flight.
|
||||
pub settled_beyond: HashMap<PeerId, Vec<(HotSequence, HotSequence)>>,
|
||||
}
|
||||
|
||||
/// Sort and coalesce runs, joining any that touch or abut.
|
||||
fn coalesce(runs: &mut Vec<(HotSequence, HotSequence)>) {
|
||||
runs.sort_unstable();
|
||||
runs.dedup_by(|(start, end), (_, last_end)| {
|
||||
let joins = *start <= last_end.next();
|
||||
if joins {
|
||||
*last_end = (*last_end).max(*end);
|
||||
}
|
||||
joins
|
||||
});
|
||||
}
|
||||
|
||||
impl SettledHotOps {
|
||||
/// Whether history already holds this hot op.
|
||||
pub fn covers(&self, id: HotOpId) -> bool {
|
||||
self.settled_up_to.get(&id.peer).is_some_and(|&through| id.sequence <= through)
|
||||
|| self
|
||||
.settled_beyond
|
||||
.get(&id.peer)
|
||||
.is_some_and(|runs| runs.iter().any(|&(start, end)| (start..=end).contains(&id.sequence)))
|
||||
}
|
||||
|
||||
/// Take on `remote`'s coverage as well as this one's.
|
||||
pub(crate) fn absorb(&mut self, remote: &Self) {
|
||||
for (&peer, &remote_through) in &remote.settled_up_to {
|
||||
let through = self.settled_up_to.entry(peer).or_default();
|
||||
*through = (*through).max(remote_through);
|
||||
}
|
||||
for (&peer, runs) in &remote.settled_beyond {
|
||||
self.settled_beyond.entry(peer).or_default().extend(runs.iter().copied());
|
||||
}
|
||||
self.compact();
|
||||
}
|
||||
|
||||
/// Record newly settled ops.
|
||||
pub fn extend(&mut self, retired: impl IntoIterator<Item = HotOpId>) {
|
||||
for id in retired {
|
||||
self.settled_beyond.entry(id.peer).or_default().push((id.sequence, id.sequence));
|
||||
}
|
||||
self.compact();
|
||||
}
|
||||
|
||||
/// Fold runs that continue their author's prefix into `settled_up_to`, leaving only those past a gap.
|
||||
fn compact(&mut self) {
|
||||
for (&peer, runs) in &mut self.settled_beyond {
|
||||
coalesce(runs);
|
||||
let mut through = self.settled_up_to.get(&peer).copied().unwrap_or(HotSequence::NONE);
|
||||
let joined = runs.iter().take_while(|&&(start, end)| {
|
||||
let joins = start <= through.next();
|
||||
if joins {
|
||||
through = through.max(end);
|
||||
}
|
||||
joins
|
||||
});
|
||||
let joined = joined.count();
|
||||
runs.drain(..joined);
|
||||
if through != HotSequence::NONE {
|
||||
self.settled_up_to.insert(peer, through);
|
||||
}
|
||||
}
|
||||
self.settled_beyond.retain(|_, runs| !runs.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum CrdtError {
|
||||
#[error("This peer has authored every hot op sequence there is")]
|
||||
SequencesExhausted,
|
||||
#[error("Target node {0} does not exist")]
|
||||
TargetNodeDoesNotExist(NodeId),
|
||||
#[error("Network {0} does not exist")]
|
||||
@@ -594,10 +752,6 @@ pub enum CrdtError {
|
||||
ExportSlotOutOfBounds(u32),
|
||||
#[error("Delta {0} not found in history")]
|
||||
NotFoundInHistory(Rev),
|
||||
#[error("No history entry resurrects node {0}")]
|
||||
NodeNotInHistory(NodeId),
|
||||
#[error("No history entry resurrects network {0}")]
|
||||
NetworkNotInHistory(NetworkId),
|
||||
#[error("Nothing to undo")]
|
||||
NothingToUndo,
|
||||
#[error("Nothing to redo")]
|
||||
@@ -606,9 +760,6 @@ pub enum CrdtError {
|
||||
NodeAlreadyExists(NodeId),
|
||||
#[error("Network {0} already exists")]
|
||||
NetworkAlreadyExists(NetworkId),
|
||||
/// PeerId is already registered to a different UserId.
|
||||
#[error("Peer {0:?} is already registered to a different user")]
|
||||
PeerRegistrationConflict(PeerId),
|
||||
#[error("Delta stored under {stored} hashes to {expected}")]
|
||||
RevMismatch { stored: Rev, expected: Rev },
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
use crate::{AttributeDelta, CrdtError, HotOpId, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, RegistryDelta, Session, UserId, Value};
|
||||
|
||||
pub(super) fn set_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: AttributeDelta {
|
||||
key: key.to_string(),
|
||||
value: Some(Value::from(serde_json::json!(value))),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn add_network(id: u64) -> RegistryDelta {
|
||||
RegistryDelta::AddNetwork {
|
||||
id: NetworkId(id),
|
||||
network: Network::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Retirement takes the ops under the cutoff in any log order: every op commutes, so the snapshot folds to
|
||||
/// the working registry's values with a later-stamped op left hot.
|
||||
#[test]
|
||||
fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
// A guest's late-stamped op sits ahead of an earlier-stamped one: the log is in arrival order, stamps
|
||||
// are the authors' clocks.
|
||||
let hot = |op, counter, peer| crate::HotOp {
|
||||
op,
|
||||
timestamp: crate::TimeStamp { counter, peer: PeerId(peer) },
|
||||
sequence: crate::HotSequence(1),
|
||||
};
|
||||
let (late, own) = (hot(add_network(9), 50, 2), hot(set_attribute("x", 1), 20, 3));
|
||||
host.apply_hot_op(late.clone()).expect("the late-stamped op lands first");
|
||||
host.apply_hot_op(own.clone()).expect("the earlier-stamped op lands second");
|
||||
assert_eq!(host.hot_ops_up_to(own.timestamp).len(), 1, "only the op under the cutoff retires");
|
||||
|
||||
host.retire(own.timestamp).expect("retire");
|
||||
assert_eq!(host.hot_log().len(), 1, "the later-stamped op stays hot");
|
||||
assert!(!host.retired_registry().networks.contains_key(&NetworkId(9)));
|
||||
assert!(host.registry().networks.contains_key(&NetworkId(9)));
|
||||
assert!(host.retired_registry().attributes.get("x").is_some_and(|value| !value.deleted));
|
||||
|
||||
host.retire(late.timestamp).expect("retire the rest");
|
||||
assert!(host.hot_log().is_empty());
|
||||
assert!(host.registry().value_equal(host.retired_registry()));
|
||||
}
|
||||
|
||||
/// A device's registration to a person is a write like any other: a later one replaces it, and a peer that
|
||||
/// receives the two in the other order ends up with the same mapping.
|
||||
#[test]
|
||||
fn a_peers_registration_is_the_newest_by_stamp_whatever_order_it_lands() {
|
||||
// Registration rides the staging path, so the steps go through the hot log and retire.
|
||||
fn stage_and_retire(session: &mut Session, op: RegistryDelta) {
|
||||
let hot = session.stage_ops([op]).expect("stage");
|
||||
let ids: Vec<crate::HotOpId> = hot.iter().map(crate::HotOp::id).collect();
|
||||
session.retire_hot_ops(&ids).expect("retire");
|
||||
}
|
||||
let mut device = Session::with_identity(PeerId(1), UserId(10));
|
||||
stage_and_retire(&mut device, set_attribute("first", 1));
|
||||
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(10));
|
||||
|
||||
// The person at the device changes: the next batch registers again, and the newer registration wins.
|
||||
device.document.user = UserId(20);
|
||||
stage_and_retire(&mut device, set_attribute("second", 2));
|
||||
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(20));
|
||||
let registrations = device.history().filter(|delta| matches!(delta.kind, RegistryDelta::RegisterPeer { .. })).count();
|
||||
assert_eq!(registrations, 2, "one registration per person the device stood for");
|
||||
|
||||
let mut other = Session::with_peer(PeerId(2));
|
||||
for delta in device.cloned_deltas().into_iter().rev() {
|
||||
other.document.apply_op_idempotent(delta.kind, delta.timestamp).unwrap();
|
||||
}
|
||||
assert_eq!(other.user_of(PeerId(1)), Some(UserId(20)), "the newest registration wins in any order");
|
||||
assert_eq!(other.user_of(PeerId(3)), None, "a peer never registered has no user");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_batch_past_the_last_sequence_is_refused_whole() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
session.restore_hot_sequence(crate::HotSequence(u64::MAX - 1));
|
||||
assert!(matches!(session.stage_ops([set_attribute("k", 1)]), Err(crate::CrdtError::SequencesExhausted)));
|
||||
assert!(session.hot_log().is_empty());
|
||||
}
|
||||
|
||||
/// The settled marks carry over a reopen, so a late copy of a retired op is dropped rather than retired again.
|
||||
#[test]
|
||||
fn a_reopened_session_drops_a_late_copy_of_a_retired_op() {
|
||||
let op = crate::HotOp {
|
||||
op: set_attribute("k", 1),
|
||||
timestamp: crate::TimeStamp { counter: 3, peer: PeerId(2) },
|
||||
sequence: crate::HotSequence(1),
|
||||
};
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
host.apply_hot_op(op.clone()).unwrap();
|
||||
host.retire(op.timestamp).unwrap();
|
||||
|
||||
let mut reopened = Session::load(PeerId(1), UserId(1), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
|
||||
reopened.absorb_settled_marks(host.settled_marks());
|
||||
reopened.apply_hot_op(op.clone()).unwrap();
|
||||
assert!(reopened.hot_log().is_empty());
|
||||
assert!(reopened.retire(op.timestamp).unwrap().is_empty());
|
||||
assert_eq!(reopened.history_len(), host.history_len());
|
||||
}
|
||||
|
||||
/// A local op naming a node never seen is refused before it writes anything, its target included, so the working
|
||||
/// registry stays the snapshot plus the hot log.
|
||||
#[test]
|
||||
fn a_refused_local_op_leaves_the_working_registry_unchanged() {
|
||||
let mut s = Session::with_peer(PeerId(1));
|
||||
let node = Node::new(NetworkId(1), Implementation::Network(NetworkId(1)), 1);
|
||||
s.stage_ops([
|
||||
RegistryDelta::AddNetwork {
|
||||
id: NetworkId(1),
|
||||
network: Network::default(),
|
||||
},
|
||||
RegistryDelta::AddNode { id: NodeId(1), node },
|
||||
])
|
||||
.unwrap();
|
||||
let before = s.registry().clone();
|
||||
|
||||
let refused = s.stage_ops([RegistryDelta::ChangeNodeInput {
|
||||
id: NodeId(1),
|
||||
index: 0,
|
||||
new_input: NodeInput::Node { id: NodeId(404), index: 0 },
|
||||
}]);
|
||||
assert!(matches!(refused, Err(CrdtError::TargetNodeDoesNotExist(_))));
|
||||
assert_eq!(s.registry(), &before, "the refused op's write to node 1 stayed in the working registry");
|
||||
}
|
||||
|
||||
/// A batch refused partway stages nothing: the caller only gets the error, so ops left staged would never be persisted
|
||||
/// or sent.
|
||||
#[test]
|
||||
fn a_refused_batch_stages_nothing() {
|
||||
let mut s = Session::with_peer(PeerId(1));
|
||||
s.stage_ops([RegistryDelta::AddNetwork {
|
||||
id: NetworkId(1),
|
||||
network: Network::default(),
|
||||
}])
|
||||
.unwrap();
|
||||
let hot_before = s.hot_log().len();
|
||||
let refused = s.stage_ops([
|
||||
set_attribute("lands", 1),
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id: NodeId(404),
|
||||
index: 0,
|
||||
new_input: NodeInput::Value {
|
||||
value: Value::from(serde_json::json!(1)),
|
||||
exposed: false,
|
||||
},
|
||||
},
|
||||
]);
|
||||
assert!(refused.is_err());
|
||||
assert_eq!(s.hot_log().len(), hot_before, "a refused batch stages nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settled_marks_round_trip_through_json() {
|
||||
let mut marks = crate::SettledHotOps::default();
|
||||
let id = |peer: u64, sequence: u64| HotOpId {
|
||||
peer: PeerId(peer),
|
||||
sequence: crate::HotSequence(sequence),
|
||||
};
|
||||
marks.extend([id(1, 1), id(1, 2), id(1, 5), id(u64::MAX, 3)]);
|
||||
let json = serde_json::to_string(&marks).unwrap();
|
||||
assert_eq!(serde_json::from_str::<crate::SettledHotOps>(&json).unwrap(), marks);
|
||||
}
|
||||
@@ -4,7 +4,7 @@ use graph_craft::concrete;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
|
||||
|
||||
use crate::InputSlot;
|
||||
use crate::{Delta, Document, HotOp, Network, NetworkId, NoMetadata, Node, NodeId, PeerId, ROOT_NETWORK, RegistryDelta, RegistryTarget, Session, TimeStamp, Value};
|
||||
use crate::{Delta, Document, HotOp, Network, NetworkId, NoMetadata, Node, NodeId, PeerId, ROOT_NETWORK, RegistryDelta, Session, TimeStamp, Value};
|
||||
|
||||
fn fresh_document(peer: PeerId) -> Document {
|
||||
Session::with_peer(peer).document
|
||||
@@ -20,7 +20,7 @@ fn remove_node_op(node_id: NodeId) -> RegistryDelta {
|
||||
/// Commit a single op to a document as a retired delta. Mints a fresh timestamp, links to
|
||||
/// current head, applies, records in history, advances head.
|
||||
fn commit_op(document: &mut Document, op: RegistryDelta) {
|
||||
let reverse = document.compute_reverse_delta(RegistryTarget::Working, &op).expect("compute_reverse_delta failed");
|
||||
let reverse = crate::prior::capture(&document.working_registry, &op);
|
||||
let timestamp = document.clock.tick();
|
||||
let delta = Delta::new(document.head, document.peer, timestamp, op, reverse);
|
||||
let rev = delta.id;
|
||||
@@ -40,9 +40,12 @@ fn apply_hot_op_advances_clock_past_observed_timestamp() {
|
||||
let hot_op = HotOp {
|
||||
op: remove_node_op(NodeId(99)),
|
||||
timestamp: observed,
|
||||
sequence: crate::HotSequence(1),
|
||||
};
|
||||
|
||||
document.apply_hot_op(hot_op).expect("RemoveNode on absent node is a no-op, not an error");
|
||||
document
|
||||
.apply_hot_op(hot_op, crate::document::ApplyMode::Live)
|
||||
.expect("RemoveNode on absent node is a no-op, not an error");
|
||||
|
||||
assert!(
|
||||
document.clock.counter >= observed.counter,
|
||||
@@ -157,7 +160,7 @@ fn history_is_causal_and_deterministic() {
|
||||
}
|
||||
}
|
||||
|
||||
fn set_document_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
pub(super) fn set_document_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: crate::AttributeDelta {
|
||||
key: key.to_string(),
|
||||
@@ -166,73 +169,6 @@ fn set_document_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
}
|
||||
}
|
||||
|
||||
/// Two peers that each integrate the other's concurrent branch converge to byte-identical history:
|
||||
/// the merge commit is parent-set-addressed (same `Rev` on both) and the canonical sort erases the
|
||||
/// arrival-order difference. Exercises `Session::merge`, the `Merge` variant, and `canonical_sort`.
|
||||
#[test]
|
||||
fn merge_converges_to_identical_history() {
|
||||
// Shared base commit, then a concurrent edit on each peer's own clone of that base.
|
||||
let mut session_a = Session::with_peer(PeerId(1));
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::base", 0)).expect("base commit");
|
||||
let mut session_b = session_a.clone();
|
||||
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::a", 1)).expect("A edit");
|
||||
session_b.commit_op_for_test(set_document_attribute("compute::b", 2)).expect("B edit");
|
||||
|
||||
// Cross-merge: feed each peer the other's full delta set. The shared base dedups by `Rev`.
|
||||
let deltas_a = session_a.cloned_deltas();
|
||||
let deltas_b = session_b.cloned_deltas();
|
||||
let merge_a = session_a.merge(deltas_b).expect("merge into A failed").expect("A produced a merge");
|
||||
let merge_b = session_b.merge(deltas_a).expect("merge into B failed").expect("B produced a merge");
|
||||
|
||||
assert_eq!(merge_a, merge_b, "same tips must mint the identical parent-set-addressed merge commit");
|
||||
|
||||
let order_a: Vec<crate::Rev> = session_a.history().map(|d| d.id).collect();
|
||||
let order_b: Vec<crate::Rev> = session_b.history().map(|d| d.id).collect();
|
||||
assert_eq!(order_a, order_b, "both peers must converge to byte-identical history order");
|
||||
assert_eq!(session_a.head_rev(), session_b.head_rev(), "both peers land on the same merge head");
|
||||
}
|
||||
|
||||
/// Resurrection must reach into a merged-in branch: a network added then removed on the other peer's
|
||||
/// branch lives only under the merge's secondary parent, so a `SetNetworkExport` targeting it after
|
||||
/// the merge can only restore it by traversing all ancestors (not the primary-parent chain).
|
||||
#[test]
|
||||
fn resurrection_reaches_across_a_merge() {
|
||||
let network_id = NetworkId(7);
|
||||
|
||||
// Shared base, then peer B adds and removes network 7 on its own branch.
|
||||
let mut session_a = Session::with_peer(PeerId(1));
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::base", 0)).expect("base commit");
|
||||
let mut session_b = session_a.clone();
|
||||
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::a", 1)).expect("A edit");
|
||||
session_b
|
||||
.commit_op_for_test(RegistryDelta::AddNetwork {
|
||||
id: network_id,
|
||||
network: Network::default(),
|
||||
})
|
||||
.expect("B AddNetwork");
|
||||
session_b
|
||||
.commit_op_for_test(RegistryDelta::RemoveNetwork {
|
||||
id: network_id,
|
||||
snapshot: Network::default(),
|
||||
})
|
||||
.expect("B RemoveNetwork");
|
||||
|
||||
// A merges B's branch: 7's AddNetwork now lives only under the merge's secondary parent.
|
||||
session_a.merge(session_b.cloned_deltas()).expect("merge failed");
|
||||
|
||||
// A SetNetworkExport on 7 must resurrect it by walking into the merged-in branch. Before the
|
||||
// all-ancestors fix this failed with NetworkNotInHistory (the primary-parent walk missed B's branch).
|
||||
session_a
|
||||
.commit_op_for_test(RegistryDelta::SetNetworkExport {
|
||||
id: network_id,
|
||||
index: 0,
|
||||
export: None,
|
||||
})
|
||||
.expect("resurrection must find the AddNetwork on the merged-in branch");
|
||||
}
|
||||
|
||||
/// Committing the same NodeNetwork twice must produce zero history entries on the second commit.
|
||||
/// Without value-only diffing in compute_deltas, the second commit would emit spurious
|
||||
/// ChangeNodeInput / ChangeNodeAttribute ops because self.registry has real timestamps while the
|
||||
@@ -263,7 +199,11 @@ fn first_contribution_registers_the_peer() {
|
||||
let registrations = first.iter().filter(|hot_op| matches!(hot_op.op, RegistryDelta::RegisterPeer { .. })).count();
|
||||
assert_eq!(registrations, 1, "exactly one RegisterPeer on first contribution");
|
||||
assert!(matches!(first[0].op, RegistryDelta::RegisterPeer { .. }), "RegisterPeer must precede the edit ops");
|
||||
assert_eq!(session.registry().peer_users.get(&PeerId(7)), Some(&crate::UserId(7)), "peer mapped to its UserId");
|
||||
assert_eq!(
|
||||
session.registry().peer_users.get(&PeerId(7)).map(|registration| registration.user),
|
||||
Some(crate::UserId(7)),
|
||||
"peer mapped to its UserId"
|
||||
);
|
||||
|
||||
// A second, distinct contribution must not re-register.
|
||||
let mut other_network = tiny_network();
|
||||
@@ -284,9 +224,9 @@ fn first_contribution_registers_the_peer() {
|
||||
assert_eq!(fresh.registry().peer_users, peers_before, "a no-op batch must not add a registration");
|
||||
}
|
||||
|
||||
/// A SetExport against a removed network must restore the network from history rather than error.
|
||||
/// A SetExport newer than a network's removal revives the network from its tombstone instead of erroring.
|
||||
#[test]
|
||||
fn set_export_resurrects_absent_network() {
|
||||
fn set_export_revives_a_removed_network() {
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
let network_id = NetworkId(7);
|
||||
|
||||
@@ -304,7 +244,7 @@ fn set_export_resurrects_absent_network() {
|
||||
snapshot: Network::default(),
|
||||
},
|
||||
);
|
||||
assert!(!document.working_registry.networks.contains_key(&network_id), "network should be removed before the resurrection test");
|
||||
assert!(!document.working_registry.networks.contains_key(&network_id), "network should be removed before the revival");
|
||||
|
||||
commit_op(
|
||||
&mut document,
|
||||
@@ -315,12 +255,12 @@ fn set_export_resurrects_absent_network() {
|
||||
},
|
||||
);
|
||||
|
||||
assert!(document.working_registry.networks.contains_key(&network_id), "SetExport should have resurrected the network");
|
||||
assert!(document.working_registry.networks.contains_key(&network_id), "SetExport should have revived the network");
|
||||
}
|
||||
|
||||
/// Cascading resurrection: bringing a node back must also restore its owning network when absent.
|
||||
/// An addition into a removed network is evidence the network exists, so it brings the network back.
|
||||
#[test]
|
||||
fn add_node_resurrects_owning_network() {
|
||||
fn add_node_revives_its_removed_network() {
|
||||
use crate::Node;
|
||||
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
@@ -345,18 +285,14 @@ fn add_node_resurrects_owning_network() {
|
||||
let node = Node { network: network_id, ..Node::dummy() };
|
||||
commit_op(&mut document, RegistryDelta::AddNode { id: node_id, node });
|
||||
|
||||
assert!(
|
||||
document.working_registry.networks.contains_key(&network_id),
|
||||
"AddNode should have cascaded a resurrection of the owning network"
|
||||
);
|
||||
assert!(document.working_registry.networks.contains_key(&network_id), "AddNode should have revived the owning network");
|
||||
assert!(document.working_registry.node_instances.contains_key(&node_id), "the node itself should also be present");
|
||||
}
|
||||
|
||||
/// Reverting the same removal twice (the moral equivalent of two peers concurrently resurrecting
|
||||
/// the same node) must not error on the second apply. Today the second revert hits
|
||||
/// `apply_op(AddNode, false)` against a present node and returns `NodeAlreadyExists`.
|
||||
/// The same revival arriving twice, from two peers reverting one removal, lands once: the second copy
|
||||
/// is not newer than what the first wrote.
|
||||
#[test]
|
||||
fn concurrent_resurrection_via_revert_is_idempotent() {
|
||||
fn the_same_revival_arriving_twice_lands_once() {
|
||||
use crate::Node;
|
||||
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
@@ -373,40 +309,19 @@ fn concurrent_resurrection_via_revert_is_idempotent() {
|
||||
let node = Node { network: network_id, ..Node::dummy() };
|
||||
commit_op(&mut document, RegistryDelta::AddNode { id: node_id, node: node.clone() });
|
||||
commit_op(&mut document, RegistryDelta::RemoveNode { id: node_id, snapshot: node });
|
||||
assert!(!document.working_registry.node_instances.contains_key(&node_id), "node should be removed before the resurrection test");
|
||||
assert!(!document.working_registry.node_instances.contains_key(&node_id), "node should be removed before the revival");
|
||||
|
||||
document.restore_node_from_history(RegistryTarget::Working, node_id).expect("first resurrection should succeed");
|
||||
assert!(document.working_registry.node_instances.contains_key(&node_id), "first resurrection should bring the node back");
|
||||
let revive = RegistryDelta::AddNode {
|
||||
id: node_id,
|
||||
node: Node { network: network_id, ..Node::dummy() },
|
||||
};
|
||||
let at = document.clock.tick();
|
||||
document.apply_op_idempotent(revive.clone(), at).expect("first revival");
|
||||
assert!(document.working_registry.node_instances.contains_key(&node_id), "the first revival brings the node back");
|
||||
|
||||
let second = document.restore_node_from_history(RegistryTarget::Working, node_id);
|
||||
assert!(second.is_ok(), "second resurrection of an already-present node should be a no-op, got {second:?}");
|
||||
}
|
||||
|
||||
/// History-based resurrection must work when the matching delta is the *root* commit. The history
|
||||
/// walk used to drop the root (its empty parent list short-circuited the iterator before yielding
|
||||
/// it), so a node removed by the very first commit could not be restored.
|
||||
#[test]
|
||||
fn restore_node_from_root_commit() {
|
||||
use crate::Node;
|
||||
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
let node_id = NodeId(42);
|
||||
|
||||
let node = Node::dummy();
|
||||
|
||||
// Seed the working state so the root commit can remove the node (its reverse is the `AddNode` the
|
||||
// resurrection looks for). This `RemoveNode` is the only commit, so the match sits at the root.
|
||||
document.working_registry.networks.insert(ROOT_NETWORK, Network::default());
|
||||
document.retired_snapshot.networks.insert(ROOT_NETWORK, Network::default());
|
||||
document.working_registry.node_instances.insert(node_id, node.clone());
|
||||
document.retired_snapshot.node_instances.insert(node_id, node.clone());
|
||||
commit_op(&mut document, RegistryDelta::RemoveNode { id: node_id, snapshot: node });
|
||||
assert!(!document.working_registry.node_instances.contains_key(&node_id), "node should be removed by the root commit");
|
||||
|
||||
document
|
||||
.restore_node_from_history(RegistryTarget::Working, node_id)
|
||||
.expect("resurrection from the root commit should succeed");
|
||||
assert!(document.working_registry.node_instances.contains_key(&node_id), "node must be restored from the root commit");
|
||||
let second = document.apply_op_idempotent(revive, at);
|
||||
assert!(second.is_ok(), "the same revival again is a no-op, got {second:?}");
|
||||
assert!(document.working_registry.node_instances.contains_key(&node_id));
|
||||
}
|
||||
|
||||
/// Erroring ops still bump the clock: we observed the timestamp on the wire, the fact that the
|
||||
@@ -439,6 +354,11 @@ fn source_key(priority: f64, peer: u64) -> SourceKey {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the map holds a live value under `key`: a deleted key stays as a tombstone.
|
||||
fn holds(attributes: &crate::Attributes, key: &str) -> bool {
|
||||
crate::attributes::live(attributes).any(|(held, _)| held == key)
|
||||
}
|
||||
|
||||
fn ts(counter: u64, peer: u64) -> TimeStamp {
|
||||
TimeStamp { counter, peer: PeerId(peer) }
|
||||
}
|
||||
@@ -538,82 +458,147 @@ fn register_resource_hash_is_last_writer_wins() {
|
||||
assert_eq!(document.working_registry.resources.get(&id).unwrap().hash, Some(hash_b), "later resolve wins");
|
||||
}
|
||||
|
||||
/// The reverse delta of a RemoveSource restores the prior source body, and applying op-then-reverse
|
||||
/// round-trips the source chain.
|
||||
/// Undo puts back exactly what an op overwrote, stamps, tombstones and placeholders included, for every kind of
|
||||
/// op and wherever it lands: on a live entity, a removed one, or one never seen.
|
||||
#[test]
|
||||
fn remove_source_reverse_restores_prior() {
|
||||
fn restoring_what_an_op_overwrote_gives_back_the_registry_exactly() {
|
||||
use crate::{AttributeDelta, Implementation, Network, NodeInput, ROOT_NETWORK};
|
||||
let attribute = |key: &str, value: i64| AttributeDelta {
|
||||
key: key.into(),
|
||||
value: Some(Value::Int(value.into())),
|
||||
};
|
||||
let reference = |id: u64| NodeInput::Node { id: NodeId(id), index: 0 };
|
||||
let (live, removed, unseen, network, resource) = (NodeId(1), NodeId(2), NodeId(3), NetworkId(7), ResourceId::new());
|
||||
let node = || Node::new(ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(1)), 2);
|
||||
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
let id = ResourceId::new();
|
||||
let key = source_key(0.5, 1);
|
||||
|
||||
commit_op(
|
||||
&mut document,
|
||||
RD::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: Value::Str("kept".into()),
|
||||
},
|
||||
);
|
||||
|
||||
// Compute the reverse while the body is still present, then apply the removal.
|
||||
let reverse = document.compute_reverse_delta(RegistryTarget::Working, &RD::RemoveSource { id, key }).unwrap();
|
||||
match &reverse {
|
||||
RD::AddSource { source, .. } => assert_eq!(*source, Value::Str("kept".into()), "reverse of removal re-adds the body"),
|
||||
other => panic!("expected AddSource reverse, got {other:?}"),
|
||||
for (op, at) in [
|
||||
(
|
||||
RD::AddNetwork {
|
||||
id: ROOT_NETWORK,
|
||||
network: Network::default(),
|
||||
},
|
||||
1,
|
||||
),
|
||||
(
|
||||
RD::AddNetwork {
|
||||
id: network,
|
||||
network: Network::default(),
|
||||
},
|
||||
1,
|
||||
),
|
||||
(RD::AddNode { id: live, node: node() }, 2),
|
||||
(RD::AddNode { id: removed, node: node() }, 2),
|
||||
(RD::RemoveNode { id: removed, snapshot: node() }, 3),
|
||||
(
|
||||
RD::ChangeNodeAttribute {
|
||||
id: live,
|
||||
delta: attribute("kept", 1),
|
||||
},
|
||||
4,
|
||||
),
|
||||
(
|
||||
RD::AddSource {
|
||||
id: resource,
|
||||
key: source_key(0.5, 1),
|
||||
source: Value::Str("kept".into()),
|
||||
},
|
||||
4,
|
||||
),
|
||||
(RD::ChangeDocumentAttribute { delta: attribute("kept", 1) }, 4),
|
||||
(
|
||||
RD::SetNetworkExport {
|
||||
id: network,
|
||||
index: 0,
|
||||
export: Some(reference(1)),
|
||||
},
|
||||
4,
|
||||
),
|
||||
] {
|
||||
document.apply_op_idempotent(op, ts(at, 2)).unwrap();
|
||||
}
|
||||
|
||||
document.apply_op(RD::RemoveSource { id, key }, ts(5, 1)).unwrap();
|
||||
assert!(document.working_registry.resources.get(&id).unwrap().sources.is_empty(), "source removed");
|
||||
|
||||
// Applying the reverse restores the chain.
|
||||
document.apply_op(reverse, ts(6, 1)).unwrap();
|
||||
assert_eq!(document.working_registry.resources.get(&id).unwrap().source(&key).unwrap().source, Value::Str("kept".into()));
|
||||
}
|
||||
|
||||
/// AddSource on a fresh slot reverses to a RemoveSource; on an occupied slot it restores the prior body.
|
||||
#[test]
|
||||
fn add_source_reverse_depends_on_prior_state() {
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
let id = ResourceId::new();
|
||||
let key = source_key(0.5, 1);
|
||||
|
||||
// Fresh slot: reverse removes.
|
||||
let reverse_fresh = document
|
||||
.compute_reverse_delta(
|
||||
RegistryTarget::Working,
|
||||
&RD::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: Value::Str("first".into()),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(reverse_fresh, RD::RemoveSource { .. }), "reverse of add-to-empty is remove, got {reverse_fresh:?}");
|
||||
|
||||
// Occupy the slot, then reverse of a new add restores the existing body.
|
||||
document
|
||||
.apply_op(
|
||||
RD::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: Value::Str("existing".into()),
|
||||
},
|
||||
ts(1, 1),
|
||||
)
|
||||
.unwrap();
|
||||
let reverse_overwrite = document
|
||||
.compute_reverse_delta(
|
||||
RegistryTarget::Working,
|
||||
&RD::AddSource {
|
||||
id,
|
||||
key,
|
||||
source: Value::Str("overwrite".into()),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
match reverse_overwrite {
|
||||
RD::AddSource { source, .. } => assert_eq!(source, Value::Str("existing".into()), "reverse restores prior body"),
|
||||
other => panic!("expected AddSource reverse, got {other:?}"),
|
||||
let ops = [
|
||||
RD::AddNode { id: live, node: node() },
|
||||
RD::AddNode { id: unseen, node: node() },
|
||||
RD::RemoveNode { id: live, snapshot: node() },
|
||||
RD::ChangeNodeAttribute {
|
||||
id: live,
|
||||
delta: attribute("kept", 2),
|
||||
},
|
||||
RD::ChangeNodeAttribute { id: live, delta: attribute("new", 2) },
|
||||
RD::ChangeNodeAttribute {
|
||||
id: removed,
|
||||
delta: attribute("new", 2),
|
||||
},
|
||||
RD::ChangeNodeAttribute {
|
||||
id: unseen,
|
||||
delta: attribute("new", 2),
|
||||
},
|
||||
RD::ChangeNodeInput {
|
||||
id: live,
|
||||
index: 1,
|
||||
new_input: reference(2),
|
||||
},
|
||||
RD::ChangeNodeInput {
|
||||
id: live,
|
||||
index: 5,
|
||||
new_input: reference(3),
|
||||
},
|
||||
RD::ChangeNodeInputAttribute {
|
||||
id: live,
|
||||
index: 0,
|
||||
delta: attribute("name", 2),
|
||||
},
|
||||
RD::SetNodeInputs {
|
||||
id: live,
|
||||
inputs: vec![crate::InputSlot::unset(TimeStamp::ORIGIN); 3],
|
||||
},
|
||||
RD::SetNodeImplementation {
|
||||
id: live,
|
||||
implementation: Implementation::Network(NetworkId(8)),
|
||||
},
|
||||
RD::SetNetworkExport {
|
||||
id: network,
|
||||
index: 3,
|
||||
export: Some(reference(3)),
|
||||
},
|
||||
RD::ChangeNetworkAttribute {
|
||||
id: network,
|
||||
delta: attribute("new", 2),
|
||||
},
|
||||
RD::RemoveNetwork {
|
||||
id: network,
|
||||
snapshot: Network::default(),
|
||||
},
|
||||
RD::AddSource {
|
||||
id: resource,
|
||||
key: source_key(0.5, 1),
|
||||
source: Value::Str("new".into()),
|
||||
},
|
||||
RD::RemoveSource {
|
||||
id: resource,
|
||||
key: source_key(0.5, 1),
|
||||
},
|
||||
RD::SetResourceHash { id: ResourceId::new(), hash: None },
|
||||
RD::RemoveResource {
|
||||
id: resource,
|
||||
snapshot: Default::default(),
|
||||
},
|
||||
RD::ChangeDocumentAttribute { delta: attribute("kept", 2) },
|
||||
RD::RegisterPeer {
|
||||
peer: PeerId(5),
|
||||
user: crate::UserId(5),
|
||||
},
|
||||
];
|
||||
for op in ops {
|
||||
let before = document.working_registry.clone();
|
||||
let priors = crate::prior::capture(&before, &op);
|
||||
let mut after = document.clone();
|
||||
after.apply_op_idempotent(op.clone(), ts(10, 2)).unwrap();
|
||||
assert_ne!(after.working_registry, before, "{op:?} should change something for this to check anything");
|
||||
crate::prior::restore(&mut after.working_registry, &priors);
|
||||
assert_eq!(after.working_registry, before, "restoring {op:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -623,7 +608,16 @@ use crate::{ResourceEntry, ResourceStore, SourceValue};
|
||||
|
||||
fn entry_with_source(priority: f64, peer: u64, body: Value, hash: Option<ResourceHash>) -> ResourceEntry {
|
||||
ResourceEntry {
|
||||
sources: vec![(source_key(priority, peer), SourceValue { source: body, timestamp: ts(1, peer) })],
|
||||
presence: ts(1, peer),
|
||||
sources: vec![(
|
||||
source_key(priority, peer),
|
||||
SourceValue {
|
||||
source: body,
|
||||
timestamp: ts(1, peer),
|
||||
deleted: false,
|
||||
},
|
||||
)],
|
||||
sources_timestamp: TimeStamp::ORIGIN,
|
||||
hash,
|
||||
hash_timestamp: ts(1, peer),
|
||||
}
|
||||
@@ -674,6 +668,7 @@ fn compute_deltas_diffs_resources_and_round_trips() {
|
||||
SourceValue {
|
||||
source: Value::Str("url".into()),
|
||||
timestamp: ts(1, 1),
|
||||
deleted: false,
|
||||
},
|
||||
);
|
||||
to.insert(kept, kept_entry);
|
||||
@@ -699,6 +694,8 @@ fn compute_deltas_diffs_resources_and_round_trips() {
|
||||
// Apply the diff to a document seeded with `from`, then check it matches `to` by value.
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
document.working_registry = registry_with_resources(from);
|
||||
// A clock is past every stamp in the registry it edits, as a session's persisted clock is.
|
||||
document.clock.observe(ts(1, 1));
|
||||
for op in deltas {
|
||||
let timestamp = document.clock.tick();
|
||||
document.apply_op(op, timestamp).expect("apply resource delta");
|
||||
@@ -833,13 +830,18 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
||||
input: crate::NodeInput::Import { index: 0 },
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
attributes: input_attributes,
|
||||
attributes_timestamp: TimeStamp::ORIGIN,
|
||||
}];
|
||||
|
||||
Node {
|
||||
presence: Default::default(),
|
||||
added: Default::default(),
|
||||
inputs_timestamp: Default::default(),
|
||||
implementation: implementation.clone(),
|
||||
implementation_timestamp: Default::default(),
|
||||
inputs,
|
||||
attributes,
|
||||
attributes_timestamp: Default::default(),
|
||||
network: ROOT_NETWORK,
|
||||
}
|
||||
};
|
||||
@@ -859,10 +861,7 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
||||
id: NodeId(9),
|
||||
node: make_node(&forward),
|
||||
},
|
||||
RegistryDelta::AddNode {
|
||||
id: NodeId(9),
|
||||
node: make_node(&forward),
|
||||
},
|
||||
Vec::new(),
|
||||
);
|
||||
let delta_reversed = Delta::new(
|
||||
parent,
|
||||
@@ -872,11 +871,402 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
||||
id: NodeId(9),
|
||||
node: make_node(&reversed),
|
||||
},
|
||||
RegistryDelta::AddNode {
|
||||
id: NodeId(9),
|
||||
node: make_node(&reversed),
|
||||
},
|
||||
Vec::new(),
|
||||
);
|
||||
|
||||
assert_eq!(delta_forward.id, delta_reversed.id, "Rev must not depend on attribute insertion order");
|
||||
}
|
||||
|
||||
/// Commit a retired delta and mirror it onto the working registry; `commit_op_for_test` alone only
|
||||
/// advances the snapshot zone.
|
||||
pub(super) fn commit_retired(session: &mut Session, op: RegistryDelta) {
|
||||
let before = session.history().count();
|
||||
session.commit_op_for_test(op).expect("commit failed");
|
||||
|
||||
for delta in session.cloned_deltas().into_iter().skip(before) {
|
||||
session.document.apply_op_idempotent(delta.kind, delta.timestamp).expect("mirroring onto the working registry");
|
||||
}
|
||||
}
|
||||
|
||||
fn add_network(id: u64) -> RegistryDelta {
|
||||
let network = Network::default();
|
||||
RegistryDelta::AddNetwork { id: NetworkId(id), network }
|
||||
}
|
||||
|
||||
pub(super) fn change_node_attribute(id: NodeId, key: &str, value: serde_json::Value) -> RegistryDelta {
|
||||
let delta = crate::AttributeDelta {
|
||||
key: key.into(),
|
||||
value: Some(Value::from(value)),
|
||||
};
|
||||
RegistryDelta::ChangeNodeAttribute { id, delta }
|
||||
}
|
||||
|
||||
fn hot_op(op: RegistryDelta, counter: u64, peer: u64, sequence: u64) -> HotOp {
|
||||
let sequence = crate::HotSequence(sequence);
|
||||
HotOp {
|
||||
op,
|
||||
timestamp: ts(counter, peer),
|
||||
sequence,
|
||||
}
|
||||
}
|
||||
|
||||
/// Settled marks are a per-author prefix plus runs past gaps: an op past a gap is covered without claiming
|
||||
/// the gap, a filled gap folds into the prefix, a gap that never fills stays one run, and absorbing is a union.
|
||||
#[test]
|
||||
fn retired_marks_keep_a_prefix_and_runs_past_gaps() {
|
||||
let author = PeerId(1);
|
||||
let id = |sequence: u64| crate::HotOpId {
|
||||
peer: author,
|
||||
sequence: crate::HotSequence(sequence),
|
||||
};
|
||||
let marks_of = |batches: &[&[u64]]| {
|
||||
let mut marks = crate::SettledHotOps::default();
|
||||
batches.iter().for_each(|batch| marks.extend(batch.iter().map(|&sequence| id(sequence))));
|
||||
marks
|
||||
};
|
||||
let after_a_lost_op: Vec<u64> = (2..=20).collect();
|
||||
let one_by_one: Vec<&[u64]> = after_a_lost_op.chunks(1).collect();
|
||||
|
||||
/// Batches extended in order, batches of a peer's marks absorbed, expected prefix, expected runs past it.
|
||||
type Case<'a> = (&'a [&'a [u64]], &'a [&'a [u64]], u64, Option<usize>);
|
||||
let cases: [Case; 5] = [
|
||||
(&[&[1, 2]], &[], 2, None),
|
||||
(&[&[1, 2], &[4]], &[], 2, Some(1)),
|
||||
(&[&[1, 2], &[4], &[3]], &[], 4, None),
|
||||
(one_by_one.as_slice(), &[], 0, Some(1)),
|
||||
(&[&[1, 4]], &[&[1, 2, 3, 5]], 5, None),
|
||||
];
|
||||
for (batches, absorbed, prefix, runs) in cases {
|
||||
let mut marks = marks_of(batches);
|
||||
marks.absorb(&marks_of(absorbed));
|
||||
let up_to = marks.settled_up_to.get(&author).copied().unwrap_or(crate::HotSequence::NONE);
|
||||
assert_eq!(up_to, crate::HotSequence(prefix), "{batches:?}");
|
||||
assert_eq!(marks.settled_beyond.get(&author).map(Vec::len), runs, "{batches:?}");
|
||||
for sequence in 1..=21 {
|
||||
let retired = batches.iter().chain(absorbed).any(|batch| batch.contains(&sequence));
|
||||
assert_eq!(marks.covers(id(sequence)), retired, "{batches:?}: sequence {sequence}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Retirement drains the hot log, so a retirer that never received an author's earlier op still retires the
|
||||
/// later one, past the author's prefix.
|
||||
#[test]
|
||||
fn retiring_over_a_gap_lands_beyond_the_prefix() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
// Sequence 1 was lost with the link that carried it.
|
||||
let second = hot_op(set_document_attribute("late", 1), 9, 2, 2);
|
||||
host.apply_hot_op(second.clone()).expect("apply");
|
||||
host.retire(second.timestamp).expect("retire");
|
||||
|
||||
let marks = host.settled_marks();
|
||||
assert_eq!(marks.settled_up_to.get(&PeerId(2)).copied().unwrap_or(crate::HotSequence::NONE), crate::HotSequence::NONE);
|
||||
assert_eq!(marks.settled_beyond.get(&PeerId(2)).map(Vec::len), Some(1));
|
||||
assert!(marks.covers(second.id()));
|
||||
}
|
||||
|
||||
/// Undo and redo move only the retired zone and never promote the hot tail into it, a fold skips the undone
|
||||
/// delta kept in the DAG for redo, and a published commit is not silently rewound since peers hold it.
|
||||
#[test]
|
||||
fn undo_and_redo_move_only_unpublished_retired_history() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
commit_retired(&mut session, set_document_attribute("first", 1));
|
||||
let boundary = session.history().last().expect("a committed delta").id;
|
||||
session.mark_interaction_end(boundary);
|
||||
commit_retired(&mut session, set_document_attribute("second", 2));
|
||||
session.stage_ops([set_document_attribute("hot", 3)]).expect("stage");
|
||||
|
||||
let mut published = session.clone();
|
||||
published.publish_up_to(published.head_rev().expect("a head"));
|
||||
assert!(session.can_undo() && !published.can_undo());
|
||||
|
||||
let retired = |session: &Session, key| holds(&session.retired_registry().attributes, key);
|
||||
session.undo().expect("undo");
|
||||
assert!(!retired(&session, "second") && !retired(&session, "hot"));
|
||||
let folded = session.snapshot_from_history().expect("fold");
|
||||
assert!(holds(&folded.attributes, "first") && !holds(&folded.attributes, "second"));
|
||||
|
||||
session.redo().expect("redo");
|
||||
assert!(retired(&session, "second") && !retired(&session, "hot"));
|
||||
assert!(holds(&session.registry().attributes, "hot"));
|
||||
}
|
||||
|
||||
/// A retired delta keeps its op's authoring stamp, so the snapshot and a replay of history keep the LWW winner
|
||||
/// the live view did, whether the losing straggler retires with the winner or after it.
|
||||
#[test]
|
||||
fn retirement_preserves_the_live_lww_winner() {
|
||||
for straggler_retires_alone in [false, true] {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
let winner = hot_op(set_document_attribute("k", 1), 10, 2, 1);
|
||||
host.apply_hot_op(winner.clone()).expect("apply winner");
|
||||
if straggler_retires_alone {
|
||||
host.retire(winner.timestamp).expect("retire winner");
|
||||
}
|
||||
host.apply_hot_op(hot_op(set_document_attribute("k", 2), 5, 3, 1)).expect("apply straggler");
|
||||
host.retire(winner.timestamp).expect("retire");
|
||||
|
||||
let value = |registry: &crate::Registry| registry.attributes.get("k").map(|attribute| attribute.value.clone());
|
||||
let replayed = host.snapshot_from_history().expect("refold");
|
||||
let values = [value(host.registry()), value(host.retired_registry()), value(&replayed)];
|
||||
assert_eq!(values, [(); 3].map(|_| Some(Value::from(serde_json::json!(1)))), "straggler retires alone: {straggler_retires_alone}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every registry field, entity existence included, is last-writer-wins on a timestamp, so a set of ops
|
||||
/// folds to one registry in any order. Random structural and field ops, attribute deletions included, over
|
||||
/// a few ids so they collide, folded in random orders.
|
||||
/// Removal snapshots are either constant or, as a remover would send them, a fold of some of the ops before.
|
||||
/// Along the way, restoring what each op overwrote gives back the registry it applied to.
|
||||
#[test]
|
||||
fn a_set_of_ops_folds_to_one_registry_in_any_order() {
|
||||
use crate::{Implementation, Priority, ResourceEntry, SourceKey, SourceValue, UserId};
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
struct Lcg(u64);
|
||||
impl Lcg {
|
||||
fn below(&mut self, bound: u64) -> u64 {
|
||||
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
(self.0 >> 33) % bound
|
||||
}
|
||||
}
|
||||
|
||||
/// Folds the ops in the order given; an op naming an entity not yet seen lands on a placeholder, so every op lands.
|
||||
/// `check_restore` also restores each op's priors on a copy and compares it with the registry the op applied to.
|
||||
fn fold(ops: &[(RegistryDelta, TimeStamp)], check_restore: bool) -> crate::Registry {
|
||||
let mut document = fresh_document(PeerId(9));
|
||||
for (op, at) in ops {
|
||||
let before = check_restore.then(|| (document.working_registry.clone(), crate::prior::capture(&document.working_registry, op)));
|
||||
document.apply_op_idempotent(op.clone(), *at).unwrap_or_else(|error| panic!("{op:?} at {at:?}: {error}"));
|
||||
if let Some((registry, priors)) = before {
|
||||
let mut restored = document.working_registry.clone();
|
||||
crate::prior::restore(&mut restored, &priors);
|
||||
assert_eq!(restored, registry, "restoring what {op:?} overwrote");
|
||||
}
|
||||
}
|
||||
document.working_registry
|
||||
}
|
||||
|
||||
fn random_op(rng: &mut Lcg, at: TimeStamp, seen: &[(RegistryDelta, TimeStamp)], real_snapshots: bool) -> RegistryDelta {
|
||||
let node_id = NodeId(1 + rng.below(4));
|
||||
let network_id = NetworkId(1 + rng.below(3));
|
||||
let resource_id = ResourceId::from(1 + rng.below(2));
|
||||
let input = |rng: &mut Lcg| match rng.below(3) {
|
||||
0 => crate::NodeInput::Node {
|
||||
id: NodeId(1 + rng.below(4)),
|
||||
index: 0,
|
||||
},
|
||||
_ => crate::NodeInput::Value {
|
||||
value: Value::from(serde_json::json!(rng.below(100))),
|
||||
exposed: false,
|
||||
},
|
||||
};
|
||||
// A write, or a deletion one time in four.
|
||||
let attribute = |rng: &mut Lcg, key: &str| crate::AttributeDelta {
|
||||
key: key.into(),
|
||||
value: (rng.below(4) > 0).then(|| Value::from(serde_json::json!(rng.below(100)))),
|
||||
};
|
||||
let key = |rng: &mut Lcg| SourceKey {
|
||||
priority: Priority::new(rng.below(2) as f64).expect("finite"),
|
||||
peer: PeerId(1 + rng.below(2).min(at.peer.0)),
|
||||
};
|
||||
// What a remover saw: some of the ops before it. Two snapshots agreeing on a stamp then agree on the value,
|
||||
// which a fabricated snapshot only does by being constant.
|
||||
let saw = |rng: &mut Lcg| fold(&seen.iter().filter(|_| rng.below(2) == 0).cloned().collect::<Vec<_>>(), false);
|
||||
match rng.below(22) {
|
||||
0 => RegistryDelta::AddNetwork {
|
||||
id: network_id,
|
||||
network: Network::default(),
|
||||
},
|
||||
1 => {
|
||||
let snapshot = if real_snapshots { saw(rng).networks.get(&network_id).cloned() } else { Some(Network::default()) };
|
||||
snapshot.map_or(RegistryDelta::EndTransaction, |snapshot| RegistryDelta::RemoveNetwork { id: network_id, snapshot })
|
||||
}
|
||||
2 | 3 => RegistryDelta::AddNode {
|
||||
id: node_id,
|
||||
node: Node::new(network_id, Implementation::ProtoNode(ResourceId::from(7)), 1 + rng.below(2) as usize),
|
||||
},
|
||||
4 => {
|
||||
let fabricated = || Node::new(NetworkId(1), Implementation::ProtoNode(ResourceId::from(7)), 2);
|
||||
let snapshot = if real_snapshots { saw(rng).node_instances.get(&node_id).cloned() } else { Some(fabricated()) };
|
||||
snapshot.map_or(RegistryDelta::EndTransaction, |snapshot| RegistryDelta::RemoveNode { id: node_id, snapshot })
|
||||
}
|
||||
5 | 6 => RegistryDelta::ChangeNodeInput {
|
||||
id: node_id,
|
||||
index: rng.below(3) as u32,
|
||||
new_input: input(rng),
|
||||
},
|
||||
7 => RegistryDelta::SetNodeInputs {
|
||||
id: node_id,
|
||||
inputs: (0..1 + rng.below(3))
|
||||
.map(|_| InputSlot {
|
||||
input: input(rng),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
attributes: Default::default(),
|
||||
attributes_timestamp: TimeStamp::ORIGIN,
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
8 => {
|
||||
let key = ["name", "lock"][rng.below(2) as usize];
|
||||
RegistryDelta::ChangeNodeAttribute {
|
||||
id: node_id,
|
||||
delta: attribute(rng, key),
|
||||
}
|
||||
}
|
||||
9 => RegistryDelta::SetNodeImplementation {
|
||||
id: node_id,
|
||||
implementation: match rng.below(2) {
|
||||
0 => Implementation::Network(network_id),
|
||||
_ => Implementation::ProtoNode(ResourceId::from(rng.below(3))),
|
||||
},
|
||||
},
|
||||
10 => RegistryDelta::SetNetworkExport {
|
||||
id: network_id,
|
||||
index: rng.below(2) as u32,
|
||||
export: match rng.below(2) {
|
||||
0 => None,
|
||||
_ => Some(input(rng)),
|
||||
},
|
||||
},
|
||||
11 => RegistryDelta::AddResource {
|
||||
id: resource_id,
|
||||
entry: ResourceEntry::default(),
|
||||
},
|
||||
12 => {
|
||||
let snapshot = if real_snapshots {
|
||||
saw(rng).resources.get(&resource_id).cloned()
|
||||
} else {
|
||||
Some(ResourceEntry::default())
|
||||
};
|
||||
snapshot.map_or(RegistryDelta::EndTransaction, |snapshot| RegistryDelta::RemoveResource { id: resource_id, snapshot })
|
||||
}
|
||||
13 => RegistryDelta::SetResourceHash {
|
||||
id: resource_id,
|
||||
hash: Some(ResourceHash::from([rng.below(2) as u8; 32])),
|
||||
},
|
||||
14 => RegistryDelta::AddSource {
|
||||
id: resource_id,
|
||||
key: key(rng),
|
||||
source: Value::from(serde_json::json!(rng.below(100))),
|
||||
},
|
||||
15 => RegistryDelta::ChangeNodeInputAttribute {
|
||||
id: node_id,
|
||||
index: rng.below(3) as u32,
|
||||
delta: attribute(rng, "label"),
|
||||
},
|
||||
16 => RegistryDelta::ChangeNetworkAttribute {
|
||||
id: network_id,
|
||||
delta: attribute(rng, "name"),
|
||||
},
|
||||
17 => RegistryDelta::RemoveSource { id: resource_id, key: key(rng) },
|
||||
18 => RegistryDelta::RegisterPeer {
|
||||
peer: PeerId(1 + rng.below(2)),
|
||||
user: UserId(rng.below(3)),
|
||||
},
|
||||
19 => RegistryDelta::ChangeDocumentAttribute { delta: attribute(rng, "doc") },
|
||||
_ => {
|
||||
// A resource added whole, with content.
|
||||
let mut entry = ResourceEntry {
|
||||
hash: Some(ResourceHash::from([rng.below(2) as u8; 32])),
|
||||
..Default::default()
|
||||
};
|
||||
let source = SourceValue {
|
||||
source: Value::from(serde_json::json!(rng.below(100))),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
deleted: false,
|
||||
};
|
||||
entry.set_source(key(rng), source);
|
||||
RegistryDelta::AddResource { id: resource_id, entry }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for real_snapshots in [false, true] {
|
||||
for seed in 0..300u64 {
|
||||
let mut rng = Lcg(seed);
|
||||
let mut ops: Vec<(RegistryDelta, TimeStamp)> = Vec::new();
|
||||
for i in 0..8 + rng.below(24) {
|
||||
let at = TimeStamp {
|
||||
counter: 1 + i,
|
||||
peer: PeerId(1 + rng.below(3)),
|
||||
};
|
||||
let op = random_op(&mut rng, at, &ops, real_snapshots);
|
||||
ops.push((op, at));
|
||||
}
|
||||
|
||||
let reference = fold(&ops, true);
|
||||
for _ in 0..6 {
|
||||
let mut shuffled = ops.clone();
|
||||
for i in (1..shuffled.len()).rev() {
|
||||
shuffled.swap(i, rng.below(i as u64 + 1) as usize);
|
||||
}
|
||||
let order: Vec<u64> = shuffled.iter().map(|(_, at)| at.counter).collect();
|
||||
assert_eq!(
|
||||
fold(&shuffled, false),
|
||||
reference,
|
||||
"seed {seed}, real snapshots {real_snapshots}: folded differently in the order {order:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A removal's snapshot carries the addition's stamps, and an entry stamped at its map's floor was written by
|
||||
/// the op that set the floor, so folding the snapshot keeps it. Pins a revived node losing `reflection_metadata`.
|
||||
#[test]
|
||||
fn a_removal_snapshot_keeps_the_attributes_the_addition_wrote() {
|
||||
use crate::{AttributesRead, AttributesWrite};
|
||||
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
let id = NodeId(4);
|
||||
let mut node = Node::new(ROOT_NETWORK, crate::Implementation::ProtoNode(graphene_resource::ResourceId::from(7)), 1);
|
||||
node.attributes.set("ui::name", Value::from(serde_json::json!("Layer")), TimeStamp::ORIGIN);
|
||||
node.inputs[0].attributes.set("reflection_metadata", Value::from(serde_json::json!("meta")), TimeStamp::ORIGIN);
|
||||
commit_op(&mut document, add_network(ROOT_NETWORK.0));
|
||||
commit_op(&mut document, RegistryDelta::AddNode { id, node });
|
||||
|
||||
// A removal and a newer write, which revives the node from the tombstone.
|
||||
let removal = RegistryDelta::RemoveNode {
|
||||
id,
|
||||
snapshot: document.working_registry.node_instances[&id].clone(),
|
||||
};
|
||||
let removed_at = document.clock.tick();
|
||||
document.apply_op_idempotent(removal.clone(), removed_at).expect("removal");
|
||||
let written_at = document.clock.tick();
|
||||
document.apply_op_idempotent(change_node_attribute(id, "ui::lock", serde_json::json!(true)), written_at).expect("write");
|
||||
|
||||
let revived = &document.working_registry.node_instances[&id];
|
||||
assert_eq!(revived.attributes.get_typed::<String>("ui::name").as_deref(), Some("Layer"));
|
||||
assert_eq!(revived.inputs()[0].attributes.get_typed::<String>("reflection_metadata").as_deref(), Some("meta"));
|
||||
|
||||
// The same removal replayed into the live node is too old to land and changes nothing.
|
||||
let mut replayed = document.clone();
|
||||
replayed.apply_op_idempotent(removal, removed_at).expect("a replayed removal");
|
||||
assert_eq!(replayed.working_registry, document.working_registry);
|
||||
}
|
||||
|
||||
/// An op rejected partway leaves the registry as it was, including the nodes it references, which a landed op
|
||||
/// would bring back.
|
||||
#[test]
|
||||
fn a_rejected_op_changes_nothing() {
|
||||
use crate::{Implementation, NodeInput};
|
||||
let mut document = fresh_document(PeerId(1));
|
||||
let node = Node::new(NetworkId(1), Implementation::Network(NetworkId(1)), 1);
|
||||
for (op, counter) in [
|
||||
(add_network(1), 1),
|
||||
(RegistryDelta::AddNode { id: NodeId(1), node: node.clone() }, 2),
|
||||
(RegistryDelta::AddNode { id: NodeId(2), node: node.clone() }, 3),
|
||||
(RegistryDelta::RemoveNode { id: NodeId(2), snapshot: node }, 4),
|
||||
] {
|
||||
document.apply_op_idempotent(op, ts(counter, 5)).unwrap();
|
||||
}
|
||||
let before = document.working_registry.clone();
|
||||
|
||||
let out_of_bounds = RegistryDelta::ChangeNodeInput {
|
||||
id: NodeId(1),
|
||||
index: 1 << 20,
|
||||
new_input: NodeInput::Node { id: NodeId(2), index: 0 },
|
||||
};
|
||||
assert!(document.apply_op_idempotent(out_of_bounds, ts(5, 5)).is_err());
|
||||
assert_eq!(document.working_registry, before);
|
||||
}
|
||||
@@ -757,20 +757,28 @@ fn cyclic_network_reference_is_rejected() {
|
||||
registry.node_instances.insert(
|
||||
crate::NodeId(0),
|
||||
Node {
|
||||
presence: Default::default(),
|
||||
added: Default::default(),
|
||||
inputs_timestamp: Default::default(),
|
||||
implementation: Implementation::Network(child_network_id),
|
||||
implementation_timestamp: Default::default(),
|
||||
inputs: Vec::new(),
|
||||
attributes: crate::Attributes::default(),
|
||||
attributes_timestamp: Default::default(),
|
||||
network: crate::ROOT_NETWORK,
|
||||
},
|
||||
);
|
||||
registry.node_instances.insert(
|
||||
crate::NodeId(1),
|
||||
Node {
|
||||
presence: Default::default(),
|
||||
added: Default::default(),
|
||||
inputs_timestamp: Default::default(),
|
||||
implementation: Implementation::Network(crate::ROOT_NETWORK),
|
||||
implementation_timestamp: Default::default(),
|
||||
inputs: Vec::new(),
|
||||
attributes: crate::Attributes::default(),
|
||||
attributes_timestamp: Default::default(),
|
||||
network: child_network_id,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -51,19 +51,7 @@ impl Registry {
|
||||
let mut node_metadata = Some(Vec::new());
|
||||
let mut network_metadata = Some(Vec::new());
|
||||
|
||||
// Group nodes by their owning network in one pass, so each `convert_network` call (one per
|
||||
// network, including nested ones) takes its node list by lookup instead of rescanning the whole
|
||||
// flat `node_instances` map, which would be quadratic on graphs with many networks.
|
||||
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
|
||||
for (&global_id, node) in &self.node_instances {
|
||||
nodes_by_network.entry(node.network).or_default().push((global_id, node));
|
||||
}
|
||||
|
||||
let context = ConversionContext {
|
||||
registry: self,
|
||||
declarations,
|
||||
nodes_by_network,
|
||||
};
|
||||
let context = ConversionContext::new(self, declarations);
|
||||
|
||||
// Reject cycles up front so the recursive conversion below can assume the network reference
|
||||
// graph is acyclic and never blow the stack on a self-referential `Implementation::Network`.
|
||||
@@ -82,7 +70,7 @@ impl Registry {
|
||||
let mut registry = graphene_resource::ResourceRegistry::new();
|
||||
|
||||
for (id, entry) in &self.resources {
|
||||
for (_, source) in &entry.sources {
|
||||
for (_, source) in entry.live_sources() {
|
||||
let decoded: graphene_resource::DataSource = from_value(&source.source).map_err(|error| ConversionError::DeserializationError(error.to_string()))?;
|
||||
registry.push_source_back(id, decoded);
|
||||
}
|
||||
@@ -104,6 +92,26 @@ struct ConversionContext<'a> {
|
||||
nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &'a Node)>>,
|
||||
}
|
||||
|
||||
impl<'a> ConversionContext<'a> {
|
||||
fn new(registry: &'a Registry, declarations: &'a Declarations) -> Self {
|
||||
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
|
||||
for (&global_id, node) in ®istry.node_instances {
|
||||
nodes_by_network.entry(node.network).or_default().push((global_id, node));
|
||||
}
|
||||
Self {
|
||||
registry,
|
||||
declarations,
|
||||
nodes_by_network,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The id the node had in the runtime it was converted from, kept as an attribute so a conversion back
|
||||
/// lands it under the id the editor's metadata is keyed by.
|
||||
fn runtime_node_id(global_id: NodeId, node: &Node) -> RuntimeNodeId {
|
||||
RuntimeNodeId(node.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(global_id.0))
|
||||
}
|
||||
|
||||
/// Converts a single network. Recurses through `Implementation::Network` owning nodes.
|
||||
///
|
||||
/// **ID remapping:** Registry uses globally hashed IDs; runtime networks need local IDs. We pull
|
||||
@@ -166,7 +174,7 @@ fn convert_network(
|
||||
node_collector: &mut Option<Vec<NodeMetadataEntry>>,
|
||||
network_collector: &mut Option<Vec<NetworkMetadataEntry>>,
|
||||
) -> Result<NodeNetwork, ConversionError> {
|
||||
let network = context.registry.networks.get(&network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
|
||||
let network = context.registry.network_or_removed(network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
|
||||
|
||||
if let Some(collector) = network_collector.as_mut() {
|
||||
collector.push(extract_network_metadata(context.registry, &network.attributes, metadata_path, network_id));
|
||||
@@ -174,8 +182,8 @@ fn convert_network(
|
||||
|
||||
let mut nodes: FxHashMap<RuntimeNodeId, DocumentNode> = FxHashMap::default();
|
||||
for &(global_id, node) in context.nodes_by_network.get(&network_id).map(Vec::as_slice).unwrap_or_default() {
|
||||
let local_id = node.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(global_id.0);
|
||||
let runtime_id = RuntimeNodeId(local_id);
|
||||
let runtime_id = runtime_node_id(global_id, node);
|
||||
let local_id = runtime_id.0;
|
||||
|
||||
if let Some(collector) = node_collector.as_mut() {
|
||||
collector.push(extract_ui_metadata(node, global_id, metadata_path, runtime_id));
|
||||
@@ -232,8 +240,7 @@ fn read_scope_injections(registry: &Registry, network_id: NetworkId, attributes:
|
||||
});
|
||||
};
|
||||
|
||||
let local_id = referenced.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(storage_id.0);
|
||||
Ok((key, (RuntimeNodeId(local_id), ty)))
|
||||
Ok((key, (runtime_node_id(storage_id, referenced), ty)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -271,8 +278,7 @@ fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[R
|
||||
fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry {
|
||||
let to_runtime_id = |storage_id: NodeId| {
|
||||
let node = registry.node_instances.get(&storage_id).filter(|node| node.network == network_id)?;
|
||||
let local_id = node.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(storage_id.0);
|
||||
Some(RuntimeNodeId(local_id))
|
||||
Some(runtime_node_id(storage_id, node))
|
||||
};
|
||||
|
||||
let pinned_order = attributes
|
||||
@@ -292,8 +298,7 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes,
|
||||
|
||||
/// Reassembles `input_data` by scanning every attribute under `ui::input_data::` and stripping the prefix.
|
||||
fn extract_input_metadata(attributes: &crate::Attributes) -> InputMetadataEntry {
|
||||
let input_data: HashMap<String, Value> = attributes
|
||||
.iter()
|
||||
let input_data: HashMap<String, Value> = crate::attributes::live(attributes)
|
||||
.filter_map(|(key, value)| key.strip_prefix(node::input::ui::DATA_PREFIX).map(|sub_key| (sub_key.to_owned(), value.value.clone())))
|
||||
.collect();
|
||||
|
||||
@@ -335,7 +340,9 @@ fn convert_node(
|
||||
fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput, input_attributes: &crate::Attributes) -> Result<GraphCraftNodeInput, ConversionError> {
|
||||
Ok(match input {
|
||||
NodeInput::Node { id: node_id, index: output_index } => {
|
||||
let referenced = registry.node_instances.get(node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
|
||||
// A node removed concurrently keeps its id, as the editor holds a dangling input; only a node
|
||||
// never seen has no id to map to.
|
||||
let referenced = registry.node_or_removed(*node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
|
||||
|
||||
// Runtime references are local to one network. A cross-network reference would remap to a
|
||||
// local ID that doesn't exist in the current runtime network, so reject it.
|
||||
@@ -346,9 +353,8 @@ fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput,
|
||||
});
|
||||
}
|
||||
|
||||
let local_id = referenced.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(node_id.0);
|
||||
GraphCraftNodeInput::Node {
|
||||
node_id: RuntimeNodeId(local_id),
|
||||
node_id: runtime_node_id(*node_id, referenced),
|
||||
output_index: *output_index as usize,
|
||||
}
|
||||
}
|
||||
|
||||
+25
-4
@@ -233,6 +233,7 @@ impl EditorDelta {
|
||||
input: context.resolver.convert_input_at(input, network_path)?,
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
attributes: convert_input_attributes(input)?,
|
||||
attributes_timestamp: TimeStamp::ORIGIN,
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>, ConversionError>>()?;
|
||||
@@ -381,15 +382,35 @@ fn construct_structural_additions(
|
||||
// A node the registry already holds is updated rather than rebuilt: rebuilding would clear the
|
||||
// `ui::*` attributes it carries, and restating those would clobber whatever a concurrent peer
|
||||
// wrote to its name, lock or pin.
|
||||
match batch.node(id).is_some() {
|
||||
true => {
|
||||
match batch.node(id) {
|
||||
Some(held) => {
|
||||
// The swap did not write the slots' `ui::*` attributes; a whole-slot assignment would drop the
|
||||
// names and descriptions held for the slots that survive it.
|
||||
let inputs = node
|
||||
.inputs()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, slot)| {
|
||||
let mut slot = slot.clone();
|
||||
if let Some(previous) = held.inputs().get(index) {
|
||||
slot.attributes.extend(
|
||||
previous
|
||||
.attributes
|
||||
.iter()
|
||||
.filter(|(key, value)| key.starts_with("ui::") && !value.deleted)
|
||||
.map(|(key, value)| (key.clone(), value.clone())),
|
||||
);
|
||||
}
|
||||
slot
|
||||
})
|
||||
.collect();
|
||||
ops.push(RegistryDelta::SetNodeImplementation {
|
||||
id,
|
||||
implementation: node.implementation().clone(),
|
||||
});
|
||||
ops.push(RegistryDelta::SetNodeInputs { id, inputs: node.inputs().to_vec() });
|
||||
ops.push(RegistryDelta::SetNodeInputs { id, inputs });
|
||||
}
|
||||
false => ops.push(RegistryDelta::AddNode { id, node: node.clone() }),
|
||||
None => ops.push(RegistryDelta::AddNode { id, node: node.clone() }),
|
||||
}
|
||||
batch.record_addition(id, node);
|
||||
}
|
||||
|
||||
+20
@@ -611,4 +611,24 @@ async fn swapping_an_implementation_leaves_the_node_in_place() {
|
||||
!deltas.iter().any(|delta| matches!(delta, EditorDelta::NodeMetadataSnapshot { node_id, .. } if *node_id == node)),
|
||||
"the node's own metadata should not be restated by a swap that did not write it"
|
||||
);
|
||||
|
||||
// The slots that survive the swap keep the names and descriptions the registry holds for them.
|
||||
let Some((id, inputs)) = ops.iter().find_map(|op| match op {
|
||||
RegistryDelta::SetNodeInputs { id, inputs } => Some((id, inputs)),
|
||||
_ => None,
|
||||
}) else {
|
||||
panic!("the swap should restate the slots")
|
||||
};
|
||||
let held: Vec<_> = working.node_instances[id]
|
||||
.inputs()
|
||||
.iter()
|
||||
.take(inputs.len())
|
||||
.flat_map(|slot| document_graph_storage::attributes::live(&slot.attributes).filter(|(key, _)| key.starts_with("ui::")))
|
||||
.collect();
|
||||
assert!(!held.is_empty(), "the surviving slots should hold ui attributes for this to check anything");
|
||||
for (index, slot) in inputs.iter().enumerate() {
|
||||
for (key, value) in document_graph_storage::attributes::live(&working.node_instances[id].inputs()[index].attributes).filter(|(key, _)| key.starts_with("ui::")) {
|
||||
assert_eq!(slot.attributes.get(key), Some(value), "slot {index} lost {key}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,26 +26,37 @@ pub struct Registry {
|
||||
pub node_instances: HashMap<NodeId, Node>, // all nodes, flat
|
||||
pub networks: HashMap<NetworkId, Network>, // exports + per-network attrs
|
||||
pub resources: ResourceStore, // content-addressable resources (images, fonts, declarations)
|
||||
pub peer_users: HashMap<PeerId, UserId>, // per-device → per-human identity
|
||||
pub peer_users: HashMap<PeerId, PeerRegistration>, // per-device → per-human identity, LWW
|
||||
pub attributes: Attributes, // document-level metadata
|
||||
pub removed_nodes: HashMap<NodeId, Tombstone<Node>>, // removed content and the removal's stamp
|
||||
pub removed_networks: HashMap<NetworkId, Tombstone<Network>>,
|
||||
pub removed_resources: HashMap<ResourceId, Tombstone<ResourceEntry>>,
|
||||
}
|
||||
|
||||
pub struct Node {
|
||||
pub implementation: Implementation, // ProtoNode(ResourceId) or Network(net)
|
||||
pub inputs: Vec<InputSlot>,
|
||||
pub attributes: Attributes,
|
||||
pub network: NetworkId,
|
||||
presence: TimeStamp, // latest addition or write
|
||||
added: TimeStamp, // decides `network` between concurrent additions
|
||||
implementation: Implementation, // ProtoNode(ResourceId) or Network(net)
|
||||
implementation_timestamp: TimeStamp,
|
||||
inputs: Vec<InputSlot>,
|
||||
inputs_timestamp: TimeStamp, // when the list last changed shape
|
||||
attributes: Attributes,
|
||||
attributes_timestamp: TimeStamp, // floor of the last whole-map write
|
||||
network: NetworkId,
|
||||
}
|
||||
|
||||
pub struct InputSlot {
|
||||
pub input: NodeInput,
|
||||
pub timestamp: TimeStamp,
|
||||
pub attributes: Attributes, // per-input metadata, LWW per key
|
||||
pub attributes_timestamp: TimeStamp,
|
||||
}
|
||||
|
||||
pub struct Network {
|
||||
presence: TimeStamp,
|
||||
pub exports: Vec<ExportSlot>,
|
||||
pub attributes: Attributes, // per-network ui::* (navigation, previewing)
|
||||
pub attributes_timestamp: TimeStamp,
|
||||
}
|
||||
|
||||
pub struct ExportSlot {
|
||||
@@ -56,7 +67,7 @@ pub struct ExportSlot {
|
||||
pub const ROOT_NETWORK: NetworkId = NetworkId(0);
|
||||
```
|
||||
|
||||
`peer_users` records the append-only `PeerId → UserId` mapping written by each device's first contribution (see [Concurrency model](#concurrency-model-cmrdt)).
|
||||
`peer_users` records the `PeerId → UserId` mapping each device registers with its first contribution (see [Concurrency model](#concurrency-model-cmrdt)).
|
||||
|
||||
The renderable graph lives in `networks[&ROOT_NETWORK]`. By convention the renderer consumes slot 0 of its exports. The editor can pick a different slot via type-based heuristics or user choice.
|
||||
|
||||
@@ -131,7 +142,7 @@ pub struct Delta {
|
||||
pub author: PeerId,
|
||||
pub timestamp: TimeStamp,
|
||||
pub kind: RegistryDelta,
|
||||
pub reverse: RegistryDelta, // precomputed for undo; excluded from id
|
||||
pub reverse: Vec<Prior>, // what the op overwrote, stamps included; excluded from id
|
||||
pub attributes: Attributes, // mutable local annotations; excluded from id
|
||||
}
|
||||
```
|
||||
@@ -165,7 +176,7 @@ History has two tiers:
|
||||
- **Hot ops** are speculative, intended to be broadcast per-keystroke for live collaboration (broadcast transport is not yet implemented, so today they stay local). They carry only a Lamport timestamp, with no parents and no content-addressed `Rev`. They live in `Document.hot_log`, are GC'd at retirement, and are persisted as a sidecar for crash recovery. They may pass through non-compiling intermediate states.
|
||||
- **Retired commits** are `Delta`s produced by retirement. Every retired commit compiles in the retiring peer's local view. They are content-addressed, durable, browseable, and replayable.
|
||||
|
||||
Retirement promotes a window of hot ops (those with timestamp at or before a cutoff) into retired deltas, re-applied with a single fresh retirement timestamp per field so LWW arms bump to `T_retire` and the original hot-op timestamps are discarded. Today retirement is one retired delta per hot op. The interfaces are in place for coarsening a window into fewer, semantically-equivalent commits (one per logical `(node, field)` group), but that grouping is not yet implemented.
|
||||
Retirement promotes a window of hot ops (those with timestamp at or before a cutoff) into retired deltas, each keeping the timestamp it was authored at, so retiring changes no field's stamp and a peer's concurrent write still orders against it the same way. Each hot op also carries its author's `HotSequence`, a gap-free count; the ops a peer knows are done with form its `SettledHotOps`, a per-author prefix plus runs for gaps still in flight, persisted in `session.json` so a late copy of a retired op is dropped rather than retired again. Today retirement is one retired delta per hot op. The interfaces are in place for coarsening a window into fewer, semantically-equivalent commits (one per logical `(node, field)` group), but that grouping is not yet implemented.
|
||||
|
||||
In a collaborative session a leader-elected peer would own retirement. That election is designed to be gossip-based (the lowest `PeerId` among peers whose `retirement_tip` matches the session max) and best-effort, needing no quorum because content-addressed `Rev`s make concurrent retirements that converge dedupe by construction. The `retirement_tip` heartbeat field exists but is inert until broadcast transport lands. Today every session retires its own hot ops (see solo retirement below).
|
||||
|
||||
@@ -178,25 +189,25 @@ Solo retirement is the same mechanism with a session of one, so history compacti
|
||||
Undo/redo operate on the delta history rather than full-interface snapshots. A commit's undo behavior depends on whether it has been broadcast to other peers, tracked by `last_broadcast_rev: Option<Rev>` on `Document` (the latest commit shared with at least one peer, or `None`, and thus the entire history, during solo editing):
|
||||
|
||||
- **Silent zone:** commits after `last_broadcast_rev`. No other peer has seen them, so they can be rewound in place.
|
||||
- **Published zone:** commits at or before `last_broadcast_rev`. Shared history is never rewound. Undoing one is a *new* forward commit applying the inverse with a fresh timestamp, so concurrent peers converge by LWW.
|
||||
- **Published zone:** commits at or before `last_broadcast_rev`, which another peer holds. Shared history is never rewound in place; undoing a published step is a collaboration operation on the shared head and lands with the transport.
|
||||
|
||||
The silent zone is the implemented path (solo editing has no transport yet). The published-zone forward-undo lands with collaboration.
|
||||
The silent zone is the implemented path (solo editing has no transport yet).
|
||||
|
||||
**Silent-zone cursor.** `head: Option<Rev>` is a movable pointer into the append-only DAG (`None` on an empty document with no commits yet). Undo/redo move it but never delete deltas (that would make redo impossible and discard branch history). The extra state is a redo stack `Vec<Rev>`, the checkpoints the user has undone past, because the DAG alone cannot say which child a `head` was undone *from*. New state persists in `session.json` alongside `head`, so redo survives reopen. A new edit while the redo stack is non-empty clears it (the undone-forward branch stays physically in the DAG but is no longer reachable via redo).
|
||||
|
||||
**Interactions, not deltas.** One user action diffs into several deltas (one per changed field, slot, or attribute), so undo steps per *interaction* rather than per delta. The last delta of each interaction is tagged with the `interaction_end` attribute, and undo reverts deltas walking the first-parent chain until the parent is an `interaction_end` boundary or the root. The starting `head` (the checkpoint) is pushed to the redo stack, and redo re-applies forward to it.
|
||||
**Interactions, not deltas.** One user action diffs into several deltas (one per changed field, slot, or attribute), so undo steps per *interaction* rather than per delta. The last delta of each interaction is tagged with the `interaction_end` attribute, and undo reverts deltas walking the first-parent chain until the parent is an `interaction_end` boundary, a merge, another user's delta, or the root. The starting `head` (the checkpoint) is pushed to the redo stack, and redo re-applies forward to it.
|
||||
|
||||
**Force-apply.** Rewinding re-applies each delta's precomputed `reverse` (for redo, the forward `kind`). These carry the *original* timestamp, which would tie (and so lose) the LWW arms' strict `>` comparison, since the forward op already stamped each field at that timestamp. In the single-writer silent zone the rewind value is authoritative, so silent undo/redo apply in a **force** mode where LWW arms assign unconditionally and structural ops are idempotent. Undo and redo are symmetric (force-reverse, force-forward), so no clock advances and identities are unchanged.
|
||||
**Restore, not reverse ops.** A delta's `reverse` is a list of `Prior`s: the state of every slot the op wrote, as it was just before, stamps included (a whole node, network, or resource where the op added, removed, or landed on a tombstone; otherwise one field plus the entity's presence stamp). Undo writes these back as they were, bypassing LWW, so the registry is again exactly the fold of history up to the new `head`. An op applied at its own timestamp could not express that: it can only write a value or a tombstone at that timestamp, while the prior state may be an older stamp or no entry at all, and a stamp the history does not account for decides later concurrent writes differently on different peers. Redo re-applies the forward ops with plain LWW, which folds them in exactly as retirement did. Both are O(steps moved), no clock advances, and identities are unchanged. Undo only takes this user's own interactions and never one containing a merge, since restoring past another peer's write would rewind it.
|
||||
|
||||
**Two registries.** Computing a correct `reverse` for an LWW field means reading the field's *pre-op* value. But staged edits apply to the live registry immediately (for responsiveness), so by retirement time it already holds the *post*-op value. `Document` therefore keeps two registries: a **working** registry (committed state plus live un-retired ops, what reads and the cursor see) and a **retired snapshot** (committed deltas only). Retirement computes reverses against, and forward-applies to, the snapshot, so the reverse captures the true prior value, and the working registry already reflects the ops and is left as-is. When there are no un-retired ops the two are equal *by value* (their LWW field timestamps can differ, since retirement re-stamps the snapshot at a fresh time), and undo/redo restore that equality by resyncing the snapshot to the rewound working registry.
|
||||
**Two registries.** Computing a correct `reverse` for an LWW field means reading the field's *pre-op* value. But staged edits apply to the live registry immediately (for responsiveness), so by retirement time it already holds the *post*-op value. `Document` therefore keeps two registries: a **working** registry (committed state plus live un-retired ops, what reads and the cursor see) and a **retired snapshot** (committed deltas only). Retirement computes reverses against, and forward-applies to, the snapshot, so the reverse captures the true prior value, and the working registry already reflects the ops and is left as-is. When there are no un-retired ops the two are equal, and undo/redo restore both; with ops still hot, the working registry is rebuilt as the rewound snapshot plus them.
|
||||
|
||||
## Concurrency model: CmRDT
|
||||
|
||||
The format uses an operation-based CRDT. The transport layer delivers ops in causal order exactly once (TCP plus the parent links threading the `Delta` DAG). The storage layer assumes this and requires only that concurrent op pairs commute. It does not need idempotency, state-merge, or out-of-order replay.
|
||||
The format uses an operation-based CRDT. The transport layer delivers ops in causal order exactly once (TCP plus the parent links threading the `Delta` DAG). Every registry field, an entity's existence included, is last-writer-wins on the op's timestamp, so the same ops fold to the same registry in any order and replaying an op changes nothing; causal order matters only for the parent links of history.
|
||||
|
||||
Graph-shape invariants (the graph remaining a DAG, the result compiling) are best-effort. Conflicts that produce a non-compiling graph surface as wiring or type errors rather than being masked by the CRDT.
|
||||
|
||||
Identity is two-tier. `PeerId` is per-device (stable per `(device, document)`, used for CRDT tiebreaking and `NodeId` scoping). `UserId` is per-human (stable across devices, used for identity display and undo-chain walking). Each device's first contribution emits `RegisterPeer { peer, user }`, which writes an append-only entry to `Registry.peer_users`. Causal delivery guarantees the registration arrives before any of that peer's other ops. The mapping is permanent (first write wins, a conflicting re-registration errors, and an identical one is a no-op), so `RegisterPeer` is its own reverse: replaying it during undo is a no-op rather than needing a distinct removal variant.
|
||||
Identity is two-tier. `PeerId` is per-device (stable per `(device, document)`, used for CRDT tiebreaking and `NodeId` scoping). `UserId` is per-human (stable across devices, used for identity display and undo-chain walking). Each device's first contribution emits `RegisterPeer { peer, user }`, which writes the peer's entry in `Registry.peer_users` along with its timestamp. Causal delivery guarantees the registration arrives before any of that peer's other ops. A device that changes person registers again, and the entry is last-writer-wins by timestamp, so every peer settles on the newest registration whatever order they arrive in. Registrations aren't undoable: `RegisterPeer` is its own reverse, so undo leaves the entry standing.
|
||||
|
||||
## Editor pipeline
|
||||
|
||||
@@ -346,15 +357,15 @@ Because inputs are stamped, `NodeInput::Node` references are set directly via `C
|
||||
- **Timestamps.** `TimeStamp { counter: u64, peer: PeerId }` is a Lamport counter with a peer-ID tiebreak. Comparison is lexicographic (counter first, then peer). Wall-clock time is not used.
|
||||
- **NodeId identity.** Every new `AddNode` issues a peer-scoped ID, so concurrent creates cannot collide.
|
||||
- **Causal delivery.** `apply_delta` requires that every parent of the delta (its `parent` plus any `Merge` extra parents) is already in local history. The storage layer does not buffer, and out-of-order delivery is a transport concern. New peers initialize via snapshot transfer (`Registry` plus history) before streaming deltas.
|
||||
- **Removal.** Physical, with no tombstones. If a later op targets an absent node or network, the receiver searches its ancestry (from `head`, following all parents) for the delta that removed the entity, the one whose `reverse` is the matching `AddNode` or `AddNetwork`, and re-applies that reverse before applying the incoming op. `RemoveNode` and `RemoveNetwork` each carry a `snapshot` of the removed entity inside that reverse so the rebuild is O(1) and needs no further history walk. The snapshot is required because retirement recomputes an op's reverse *after* the hot op already applied the removal, when the live entity is gone. Removal is therefore non-durable under concurrent edits, since any concurrent reference to a removed node revives it.
|
||||
- **LWW primitives.** Per-input (`InputSlot.timestamp`), per-export-slot (`ExportSlot.timestamp`), and per-attribute-value (the `TimeStamp` in `Attributes`). The exported-nodes list is one such attribute value (the `exported_nodes` document attribute), so it inherits per-key LWW with no separate machinery. The timestamp driving every LWW arm comes from the wrapping `Delta`. `AttributeDelta` carries `value: Option<_>` so a single shape covers both `Set` (`Some`) and `Remove` (`None`), and `Set` versus `Remove` has a defined winner.
|
||||
- **Resources.** A resource's `hash` is LWW (content-derived, so concurrent resolves agree). Its source chain is an ordered LWW-element-set keyed by `SourceKey` (fractional priority plus peer tiebreak): concurrent `AddSource`s at distinct keys all survive, and a re-add or a remove at the same key is LWW on the per-`Delta` timestamp (no tombstones, so a same-key add/remove is order-sensitive only without causal delivery). Whole-resource `AddResource`/`RemoveResource` mirror the node/network add-remove pairs (`RemoveResource` snapshots the entry for O(1) reverse).
|
||||
- **Existence.** Last-writer-wins like any field. Each node, network and resource carries a `presence` stamp, its latest addition or write. A removal moves the entity into a tombstone map (`removed_nodes`, `removed_networks`, `removed_resources`) holding its content and the removal's stamp: an op stamped earlier lands on the tombstone, and an addition, write or reference stamped later revives the entity from it. A write to an entity never seen lands on a placeholder tombstone that stays dead until its addition folds in, so ops land the same in any order and nothing is buffered. `RemoveNode`, `RemoveNetwork` and `RemoveResource` carry the removed content, which folds in like any write, so a removal of an entity this peer never saw still lands.
|
||||
- **LWW primitives.** Per-input (`InputSlot.timestamp`), per-export-slot (`ExportSlot.timestamp`), and per-attribute-value (the `TimeStamp` in `Attributes`). The exported-nodes list is one such attribute value (the `exported_nodes` document attribute), so it inherits per-key LWW with no separate machinery. The timestamp driving every LWW arm comes from the wrapping `Delta`. A whole-map write (an addition) also stamps the map's floor (`attributes_timestamp`), deleting every key it does not hold without a tombstone per key. `AttributeDelta` carries `value: Option<_>` so a single shape covers both `Set` (`Some`) and `Remove` (`None`), and `Set` versus `Remove` has a defined winner.
|
||||
- **Resources.** A resource's `hash` is LWW (content-derived, so concurrent resolves agree). Its source chain is an ordered LWW-element-set keyed by `SourceKey` (fractional priority plus peer tiebreak): concurrent `AddSource`s at distinct keys all survive, and a re-add or a remove at the same key is LWW on the per-`Delta` timestamp, a removal leaving a `deleted` tombstone so either order resolves alike. Whole-resource `AddResource`/`RemoveResource` mirror the node/network add-remove pairs.
|
||||
|
||||
The CRDT does not mask graph-shape conflicts. Concurrent same-slot `SetNetworkExport`s with different targets resolve by LWW, but the resulting wiring may be wrong, and downstream consumers see it as a compile or wiring error.
|
||||
|
||||
## History storage
|
||||
|
||||
`History` is a `Vec<Delta>` in topological order (parents before children) with a `HashMap<Rev, usize>` index for lookup. The append order is canonical, which is what lets history serialize byte-identically across peers that absorbed the same delta set. `Document` adds a `head: Option<Rev>` (the local cursor, which advances only on local commits, `None` until the first commit) and a `hot_log: Vec<HotOp>` (in-flight unretired ops). Walking history follows each delta's `parent`, and this default first-parent walk reconstructs a single peer's local chain. Branches are siblings under a shared parent, and a `Merge` delta rejoins them, its extra parents naming the other tips it folds in.
|
||||
`History` is a `Vec<Delta>` in topological order (parents before children) with a `HashMap<Rev, usize>` index for lookup. The append order is canonical, which is what lets history serialize byte-identically across peers that absorbed the same delta set. `Document` adds a `head: Option<Rev>` (the local cursor, `None` until the first commit) and a `hot_log: Vec<HotOp>` (in-flight unretired ops). Walking history follows each delta's `parent`, and this default first-parent walk reconstructs a single peer's local chain. Branches are siblings under a shared parent, and a `Merge` delta rejoins them, its extra parents naming the other tips it folds in.
|
||||
|
||||
## Editor metadata
|
||||
|
||||
@@ -378,7 +389,7 @@ Document-scoped editor settings (viewport view, render mode, overlay/ruler visib
|
||||
|
||||
**Merkle `Rev` (parent in the hash) vs. a position-independent content id.** A `Rev` hashes `(parent, author, timestamp, kind)`, and since `parent` is itself a `Rev`, every `Rev` transitively commits to its whole ancestry. This is the Git commit-hash model: a Git commit folds its parent SHA, tree, author, committer, and message into its own SHA, so changing any ancestor rewrites every descendant hash. We keep that model for the same two reasons Git gets value from it. First, tamper-evidence: rehashing detects any rewrite of history (see [Deltas](#deltas)). Second, the chain doubles as the causal structure the CRDT already needs. We then diverge from Git in one deliberate place: a `Merge` is hashed over its sorted parent set alone, with author and timestamp excluded, so two peers merging the same tips mint the *identical* `Rev` and it dedups into one shared node. Git does the opposite (its merge commits carry author/time/message and so never converge), because Git reconciles through a human pushing and pulling rather than through automatic DAG convergence. The cost of parent-in-hash is the one Git also pays: reordering or rebasing an op rewrites every descendant `Rev`, so identity is not stable across [history linearization](#future-possibilities). A pure content-derived id (no parent) would survive reordering but would forfeit both convergence-by-construction and free tamper-evidence, so it is the wrong primary identity. The position-independent use case is better served by a separate, computed id (see the patch-id analogue under [Future possibilities](#future-possibilities)) rather than by weakening `Rev`.
|
||||
|
||||
**Ad-hoc resurrection vs. tombstones.** Tombstones add a permanent footprint to the data model and a GC policy question. Resurrection reuses the history log already needed for undo as the recovery mechanism, keeping the live `Registry` lean. The cost is that `RemoveNode` is not durable under concurrent edits.
|
||||
**Tombstones vs. resurrection from history.** Reviving a removed entity from the history log keeps the live `Registry` lean, but a removal and a concurrent write then fold differently depending on which arrives first, and a reference anywhere revives what was removed. Tombstones cost a permanent entry per removed entity (collecting them is future work) and buy order-independence: every field, existence included, is last-writer-wins.
|
||||
|
||||
**Type-erased attributes vs. typed metadata fields.** Migrations operate on attribute values without keeping old Rust struct shapes alive. The cost is per-value overhead, mitigable without changing the model.
|
||||
|
||||
|
||||
Reference in new issue
Block a user