diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs index 66882dab2..64b18f413 100644 --- a/native/aetherlight/src/action.rs +++ b/native/aetherlight/src/action.rs @@ -1015,13 +1015,13 @@ mod tests { }; use crate::tests::{ ADMIT_KIND, COMMAND_KIND, Civic, LEVY_KIND, OPENING_BALANCE, SEIZURE_GRIEVANCE, Topology, - WARDEN_OFFICE, act, act_command, affordance_named, authority_kind, civic_world, + WARDEN_OFFICE, act, affordance_named, authority_kind, civic_world, command, custody_world, grant_to, grievance, office, operations, over_place, - over_subject, play_caller, reject_play, submit_play, + over_subject, play_caller, reject_play, submit_play, tick_body, }; use crate::{ AffordanceKindName, AuthenticatedCaller, AuthoredSource, CommandBody, Confidence, - Declaration, EffectSlot, EntityKind, ProposedEffect, RoleBinding, Statement, SubmitReceipt, + Declaration, EffectSlot, EntityKind, ProposedEffect, RoleBinding, Statement, CommitReceipt, WorldEffect, WorldKernel, WorldPatch, WorldSnapshot, apply_effect, }; use std::collections::BTreeSet; @@ -1069,6 +1069,40 @@ mod tests { exercise(state, command_id, actor, &granted, invocation) } + /// Commit `invocation` as the first command whose derived id draws `band`. + /// A band is a pure function of the pre-commit state and the command id, + /// and a command's id derives from the revision it targets, so a test + /// reaches a band by committing ordinary ticks until the id it would + /// carry draws it. + fn act_drawing( + kernel: &mut WorldKernel, + actor: SubjectId, + invocation: &DecisionInvocation, + band: usize, + ) -> CommitReceipt { + for _ in 0..256 { + let snapshot = kernel.snapshot().unwrap(); + let envelope = command( + &snapshot, + play_caller(), + CommandBody::Act { + actor, + invocation: invocation.clone(), + }, + ); + let draws = draw_once(&kernel.state, envelope.id(), actor, invocation) + .expect("the invocation is admissible") + .band; + if draws == band { + return kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .expect("the invocation commits"); + } + submit_play(kernel, &snapshot, tick_body(1)); + } + panic!("a two-band entry reaches both bands within 256 revisions"); + } + fn binding(role: &str, target: Target) -> RoleBinding { RoleBinding { role: Role(role.into()), @@ -1120,7 +1154,7 @@ mod tests { } } - fn commit(&mut self, invocation: DecisionInvocation) -> SubmitReceipt { + fn commit(&mut self, invocation: DecisionInvocation) -> CommitReceipt { act(&mut self.kernel, self.clerk, invocation).expect("the invocation commits") } @@ -1324,7 +1358,7 @@ mod tests { let clerk_before = bench.held(bench.clerk); let keeper_before = bench.held(bench.keeper); let receipt = bench.commit(bench.carry(3, bench.yard)); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); assert_eq!(bench.held(bench.clerk), clerk_before - 3); assert_eq!(bench.held(bench.keeper), keeper_before + 3); assert_eq!( @@ -1470,7 +1504,7 @@ mod tests { assert!(event.effects.is_empty()); let receipt = bench.commit(idle); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); assert_eq!(bench.kernel.state.holdings, holdings); assert_eq!(bench.kernel.state.positions, positions); assert_eq!(bench.kernel.state.edges, edges); @@ -1483,7 +1517,7 @@ mod tests { let directory = tempfile::tempdir().unwrap(); let mut bench = bench(directory.path(), "Lowering"); let receipt = bench.commit(bench.carry(2, bench.yard)); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); let event = bench .kernel .state @@ -1539,30 +1573,12 @@ mod tests { let mut seen: BTreeSet = BTreeSet::new(); for wanted in [0usize, 1] { - // The draw is a pure function of the pre-commit revision and the - // command id, so the command id that reaches a band is findable - // before the envelope is built rather than hunted by retrying. - let command_id = (0..256) - .map(|_| CommandId::issue()) - .find(|candidate| { - draw_once(&bench.kernel.state, *candidate, bench.clerk, &split) - .expect("the invocation is admissible") - .band - == wanted - }) - .expect("a two-band entry reaches both bands over 256 command ids"); - + // The draw is a pure function of the pre-commit state and the + // command id; `act_drawing` finds the revision whose id reaches it. let before_clerk = bench.held(bench.clerk); let before_keeper = bench.held(bench.keeper); - let receipt = act_command( - &mut bench.kernel, - command_id, - play_caller(), - bench.clerk, - split.clone(), - ) - .expect("the invocation commits"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let receipt = act_drawing(&mut bench.kernel, bench.clerk, &split, wanted); + assert!(receipt.resulting_revision > 0); bench.refresh(); let event = bench .kernel @@ -1743,7 +1759,7 @@ mod tests { }, ) .expect("the Speak entry commits"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); let event = kernel.state.events.last().unwrap(); assert_eq!(event.band, 0); // The two the speech lowering prepends, and nothing from a slot. @@ -1890,7 +1906,7 @@ mod tests { } } - fn commit_as(&mut self, actor: SubjectId, invocation: DecisionInvocation) -> SubmitReceipt { + fn commit_as(&mut self, actor: SubjectId, invocation: DecisionInvocation) -> CommitReceipt { let receipt = act(&mut self.kernel, actor, invocation).expect("the invocation commits"); self.refresh(); receipt @@ -1899,7 +1915,7 @@ mod tests { fn admit(&mut self, ops: Vec) { let before = self.kernel.snapshot().unwrap(); let receipt = submit_play(&mut self.kernel, &before, operations(ops)); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); self.refresh(); } @@ -2094,10 +2110,7 @@ mod tests { // The chamber is inside it, so the same act commits and the deputy can // then levy there. let inside = bench.delegate(outsider, bench.civic.chamber); - assert!(matches!( - bench.commit_as(treasury, inside), - SubmitReceipt::Applied(_) - )); + assert!(bench.commit_as(treasury, inside).resulting_revision > 0); assert!( bench .try_as(outsider, &bench.levy(bench.civic.farmer, 1)) @@ -2151,10 +2164,7 @@ mod tests { // The treasury's own `levy` grant over the hall covers the hall, so // the treasury may strip its own grant, and the ledger loses it. - assert!(matches!( - bench.commit_as(treasury, bench.revoke(treasury, hall)), - SubmitReceipt::Applied(_) - )); + assert!(bench.commit_as(treasury, bench.revoke(treasury, hall)).resulting_revision > 0); assert!( !bench .kernel @@ -2202,10 +2212,7 @@ mod tests { .map(|position| position.place), Some(chamber) ); - assert!(matches!( - bench.commit_as(treasury, bench.deploy(farmer, passage)), - SubmitReceipt::Applied(_) - )); + assert!(bench.commit_as(treasury, bench.deploy(farmer, passage)).resulting_revision > 0); assert_eq!( bench .kernel @@ -2235,10 +2242,7 @@ mod tests { ); let farmer = bench.civic.farmer; - assert!(matches!( - bench.commit_as(farmer, petition.clone()), - SubmitReceipt::Applied(_) - )); + assert!(bench.commit_as(farmer, petition.clone()).resulting_revision > 0); let event = bench .kernel .state @@ -2351,24 +2355,8 @@ mod tests { // The treasury commands the hall, and the passage has both endpoints // under it. The draw decides whether the interdiction lands. - let closing = (0..256) - .map(|_| CommandId::issue()) - .find(|candidate| { - draw_once(&bench.kernel.state, *candidate, treasury, &sanction) - .expect("the invocation is admissible") - .band - == 0 - }) - .expect("a two-band entry reaches its first band over 256 command ids"); - let receipt = act_command( - &mut bench.kernel, - closing, - play_caller(), - treasury, - sanction, - ) - .expect("the sanction commits"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let receipt = act_drawing(&mut bench.kernel, treasury, &sanction, 0); + assert!(receipt.resulting_revision > 0); bench.refresh(); assert!(!bench.kernel.state.edges[&passage].is_open()); @@ -2386,10 +2374,7 @@ mod tests { }], None, ); - assert!(matches!( - bench.commit_as(treasury, appoint), - SubmitReceipt::Applied(_) - )); + assert!(bench.commit_as(treasury, appoint).resulting_revision > 0); assert_eq!( bench.kernel.state.selection[&treasury][&office("bailiff")].incumbent, Some(farmer) @@ -2404,7 +2389,7 @@ mod tests { bench: &mut Civics, actor: SubjectId, invocation: DecisionInvocation, - ) -> Result { + ) -> Result { act(&mut bench.kernel, actor, invocation) } @@ -2587,7 +2572,6 @@ mod tests { let caller = play_caller(); let envelope = command( &bench.active, - CommandId::new(), caller.clone(), CommandBody::Act { actor: treasury, @@ -2601,7 +2585,7 @@ mod tests { .kernel .submit(envelope, &AuthenticatedCaller::fixture(caller)) .expect("the act commits"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); bench.refresh(); let WorldEffect::Acted { event, .. } = first else { panic!("an acted effect"); diff --git a/native/aetherlight/src/grammar/tests.rs b/native/aetherlight/src/grammar/tests.rs index 9c31ff39d..3743f2a9a 100644 --- a/native/aetherlight/src/grammar/tests.rs +++ b/native/aetherlight/src/grammar/tests.rs @@ -5,7 +5,7 @@ use crate::patch::{ }; use crate::tests::{auth_principal, command, creation, owner}; use crate::{ - CallerId, CommandBody, CommandId, CreateWorld, KernelError, SubjectKind, SubmitReceipt, + CallerId, CommandBody, CommandId, CreateWorld, KernelError, SubjectKind, CommitReceipt, WorldKernel, WorldPatch, }; @@ -38,7 +38,7 @@ fn grammar_with(extra: &[(&str, GrammarVerb)]) -> GrammarBinding { } fn bound(grammar: Option, title: &str) -> CreateWorld { - let mut world = creation(CommandId::new(), title); + let mut world = creation(title); world.grammar = grammar; world } @@ -96,12 +96,11 @@ fn create(world: CreateWorld) -> (tempfile::TempDir, Result Result { +fn admit(kernel: &mut WorldKernel, patch: WorldPatch) -> Result { let snapshot = kernel.snapshot().unwrap(); kernel.submit( command( &snapshot, - CommandId::new(), CallerId::Play, CommandBody::AdmitPatch { patch, @@ -151,7 +150,7 @@ fn grammar_world_refuses_an_affordance_kind_outside_the_grammar() { not_in_grammar("wave") ); let receipt = admit(&mut kernel, patch_of(vec![declare("hail", "hail", &[])])).unwrap(); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); } #[test] @@ -203,7 +202,7 @@ fn grammar_world_refuses_a_role_signature_the_grammar_does_not_carry() { )]), ) .unwrap(); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); } #[test] @@ -235,7 +234,7 @@ fn each_grammar_referent_kind_admits_exactly_its_own_kernel_kind() { ); if offered == own { assert!( - matches!(result, Ok(SubmitReceipt::Applied(_))), + matches!(result, Ok(_)), "{referent:?} refused its own kind" ); } else { @@ -298,7 +297,7 @@ fn unbound_world_keeps_the_open_catalog() { patch_of(vec![declare("beacon", "beacon", &[])]), ) .unwrap(); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); let snapshot = kernel.snapshot().unwrap(); assert!(snapshot.grammar.is_none()); assert!(snapshot.affordances.len() >= 4); @@ -487,12 +486,11 @@ fn submit_as( kernel: &mut WorldKernel, caller: CallerId, patch: WorldPatch, -) -> Result { +) -> Result { let snapshot = kernel.snapshot().unwrap(); kernel.submit( command( &snapshot, - CommandId::new(), caller.clone(), CommandBody::AdmitPatch { patch }, ), @@ -576,7 +574,7 @@ fn play_refuses_outside_the_grammar_after_the_revision_has_moved() { patch_of(vec![declare("hail", "hail", &[])]), ) .unwrap(); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); } #[test] @@ -636,7 +634,7 @@ fn an_effect_resolved_elsewhere_cannot_install_an_entry_outside_the_grammar() { let resolve = |kind: &str, roles: &[(&str, RefKind)]| { crate::patch::resolve_patch( &twin, - CommandId::new(), + CommandId::issue(), &patch_of(vec![declare("probe", kind, roles)]), ) .expect("the unbound twin admits any canonical kind") @@ -650,7 +648,7 @@ fn an_effect_resolved_elsewhere_cannot_install_an_entry_outside_the_grammar() { let catalog = state.affordance_catalog.len(); let result = crate::apply_effect( &mut state, - CommandId::new(), + CommandId::issue(), &CallerId::Play, &crate::WorldEffect::PatchAdmitted { resolved, diff --git a/native/aetherlight/src/import_key_tests.rs b/native/aetherlight/src/import_key_tests.rs index 85149e51e..5c5e28340 100644 --- a/native/aetherlight/src/import_key_tests.rs +++ b/native/aetherlight/src/import_key_tests.rs @@ -9,7 +9,7 @@ use crate::patch::{ use crate::tests::{auth_principal, command, creation, owner}; use crate::{ CallerId, CommandBody, CommandId, CreateWorld, EntityId, KernelError, - SubjectDeclaration, SubjectKind, SubmitReceipt, + SubjectDeclaration, SubjectKind, CommitReceipt, WorldKernel, WorldPatch, }; use std::collections::BTreeSet; @@ -24,7 +24,7 @@ fn alpha() -> ImportKey { /// The fixture genesis with its witness imported from `alpha()`. fn keyed_creation(title: &str) -> CreateWorld { - let mut world = creation(CommandId::new(), title); + let mut world = creation(title); for declaration in &mut world.patch.declarations { if let Declaration::Subject(subject) = declaration && subject.handle == DraftHandle::new("persona") @@ -71,12 +71,11 @@ fn submit_as( kernel: &mut WorldKernel, caller: CallerId, patch: WorldPatch, -) -> Result { +) -> Result { let snapshot = kernel.snapshot().unwrap(); kernel.submit( command( &snapshot, - CommandId::new(), caller.clone(), CommandBody::AdmitPatch { patch }, ), @@ -132,7 +131,7 @@ fn keys_in(kernel: &WorldKernel) -> Vec { #[test] fn one_patch_cannot_declare_two_subjects_with_one_import_key() { // At genesis. - let mut world = creation(CommandId::new(), "Twins"); + let mut world = creation("Twins"); for declaration in &mut world.patch.declarations { if let Declaration::Subject(subject) = declaration && (subject.handle == DraftHandle::new("persona") @@ -236,7 +235,7 @@ fn a_held_import_key_is_refused_at_every_door_after_the_revision_has_moved() { patch_of(vec![keyed("fresh", Some(fresh.clone()), dead_end)]), ) .unwrap(); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); let again = submit_as( &mut kernel, CallerId::Play, @@ -404,7 +403,7 @@ fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_else let resolve = |handle: &str| { crate::patch::resolve_patch( &kernel.state, - CommandId::new(), + CommandId::issue(), &patch_of(vec![keyed( handle, Some(key("aetheria.ship", "Omega")), @@ -421,7 +420,7 @@ fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_else }; crate::apply_effect( &mut state, - CommandId::new(), + CommandId::issue(), &CallerId::Play, &effect(first), ) @@ -429,7 +428,7 @@ fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_else assert_eq!(state.subjects.len(), before + 1); let result = crate::apply_effect( &mut state, - CommandId::new(), + CommandId::issue(), &CallerId::Play, &effect(second), ); @@ -452,7 +451,7 @@ fn contains(haystack: &[u8], needle: &[u8]) -> bool { fn keyless_world_digests_unchanged() { // A subject nobody imported serialises without the field at all, so every // digest written before keys existed is the digest of the same bytes. - let (_dir, kernel) = create(creation(CommandId::new(), "Keyless")); + let (_dir, kernel) = create(creation("Keyless")); let kernel = kernel.unwrap(); let state = rmp_serde::to_vec_named(&kernel.state).unwrap(); assert!( @@ -616,7 +615,7 @@ fn admitting_a_resolved_effect_refuses_two_subjects_with_one_key() { let resolve = || { crate::patch::resolve_patch( &kernel.state, - CommandId::new(), + CommandId::issue(), &patch_of(vec![ keyed("first", Some(key("aetheria.ship", "Beta")), place), keyed("second", Some(key("aetheria.ship", "Gamma")), place), diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs index fa4e8303f..96efb340f 100644 --- a/native/aetherlight/src/journal.rs +++ b/native/aetherlight/src/journal.rs @@ -911,7 +911,7 @@ fn apply_committed_command( } apply_effect( state, - command.id, + command.id(), &commit.command.caller(), &expected_effect, ) @@ -983,6 +983,15 @@ mod tests { value: u8, } + /// The commit a forgery test rewrites: the one the test just committed. + pub(super) fn last_commit(commits: &mut BTreeMap) -> &mut WorldCommit { + commits.values_mut().max_by_key(|commit| commit.resulting_revision).unwrap() + } + + pub(super) fn genesis_commit(commits: &mut BTreeMap) -> &mut WorldCommit { + commits.values_mut().min_by_key(|commit| commit.resulting_revision).unwrap() + } + fn owner_patch(subject: SubjectDeclaration) -> WorldPatch { WorldPatch { declarations: vec![Declaration::Subject(subject)], @@ -1010,7 +1019,6 @@ mod tests { let owner = PrincipalId::new("owner@example.test"); let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); let creation = CreateWorld { - id: CommandId::new(), owner: owner.clone(), title: "Before".into(), patch: owner_patch(SubjectDeclaration { @@ -1025,11 +1033,9 @@ mod tests { }; let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); let snapshot = kernel.snapshot().unwrap(); - let command_id = CommandId::new(); kernel .submit( CommandEnvelope { - id: command_id, world_id: snapshot.world_id, expected_revision: snapshot.revision, caller: CallerId::Play, @@ -1043,7 +1049,7 @@ mod tests { let mut command_forged_head = kernel.state.clone(); let mut command_forged_commits = kernel.journal.commits.clone(); - let command_forged = command_forged_commits.get_mut(&command_id).unwrap(); + let command_forged = last_commit(&mut command_forged_commits); let CommittedCommand::WorldCommand(command) = &mut command_forged.command else { panic!("expected a world command"); }; @@ -1060,7 +1066,7 @@ mod tests { let mut caller_forged_head = kernel.state.clone(); let mut caller_forged_commits = kernel.journal.commits.clone(); - let caller_forged = caller_forged_commits.get_mut(&command_id).unwrap(); + let caller_forged = last_commit(&mut caller_forged_commits); let CommittedCommand::WorldCommand(command) = &mut caller_forged.command else { panic!("expected a world command"); }; @@ -1075,7 +1081,7 @@ mod tests { let mut effect_forged_head = kernel.state.clone(); let mut effect_forged_commits = kernel.journal.commits.clone(); - let effect_forged = effect_forged_commits.get_mut(&command_id).unwrap(); + let effect_forged = last_commit(&mut effect_forged_commits); let WorldEffect::TimeAdvanced { to, .. } = &mut effect_forged.effect else { panic!("expected a time effect"); }; @@ -1096,7 +1102,6 @@ mod tests { let owner = PrincipalId::new("owner@example.test"); let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); let creation = CreateWorld { - id: CommandId::new(), owner: owner.clone(), title: "Kharad".into(), patch: owner_patch(SubjectDeclaration { @@ -1111,11 +1116,9 @@ mod tests { }; let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); let snapshot = kernel.snapshot().unwrap(); - let command_id = CommandId::new(); kernel .submit( CommandEnvelope { - id: command_id, world_id: snapshot.world_id, expected_revision: snapshot.revision, caller: CallerId::Play, @@ -1148,7 +1151,7 @@ mod tests { let mut forged_head = kernel.state.clone(); let mut forged_commits = kernel.journal.commits.clone(); - let forged = forged_commits.get_mut(&command_id).unwrap(); + let forged = last_commit(&mut forged_commits); let WorldEffect::PatchAdmitted { resolved, .. } = &mut forged.effect else { panic!("expected an admitted patch effect"); }; @@ -1255,7 +1258,7 @@ mod tests { let directory = tempfile::tempdir().unwrap(); let (mut kernel, _) = WorldKernel::create( directory.path().join("world.cc"), - creation(CommandId::new(), "Clock History"), + creation("Clock History"), &auth_principal(owner()), ) .unwrap(); @@ -1392,18 +1395,16 @@ mod tests { let authenticated = auth_principal(owner()); let (mut kernel, _) = WorldKernel::create( &path, - crate::tests::creation(CommandId::new(), "Chronicle"), + crate::tests::creation("Chronicle"), &authenticated, ) .unwrap(); let active = kernel.snapshot().unwrap(); - let command_id = CommandId::new(); let caller = CallerId::Play; kernel .submit( command( &active, - command_id, caller.clone(), CommandBody::AdvanceTime { minutes: TickMinutes::new(30).unwrap(), @@ -1415,7 +1416,7 @@ mod tests { let mut forged_head = kernel.state.clone(); let mut forged_commits = kernel.journal.commits.clone(); - let forged = forged_commits.get_mut(&command_id).unwrap(); + let forged = last_commit(&mut forged_commits); let WorldEffect::TimeAdvanced { to, .. } = &mut forged.effect else { panic!("expected a time-advanced effect"); }; @@ -1440,18 +1441,16 @@ mod tests { let authenticated = auth_principal(owner()); let (mut kernel, _) = WorldKernel::create( &path, - crate::tests::creation(CommandId::new(), "Kharad"), + crate::tests::creation("Kharad"), &authenticated, ) .unwrap(); let topology = admit_topology(&mut kernel); let active = kernel.snapshot().unwrap(); - let command_id = CommandId::new(); kernel .submit( command( &active, - command_id, CallerId::Play, CommandBody::AdmitPatch { patch: WorldPatch { @@ -1470,7 +1469,7 @@ mod tests { let mut forged_head = kernel.state.clone(); let mut forged_commits = kernel.journal.commits.clone(); - let forged = forged_commits.get_mut(&command_id).unwrap(); + let forged = last_commit(&mut forged_commits); let WorldEffect::PatchAdmitted { resolved, .. } = &mut forged.effect else { panic!("expected an admitted patch effect"); }; @@ -1511,7 +1510,7 @@ mod tests { let authenticated = auth_principal(owner()); let (mut kernel, _) = WorldKernel::create( &path, - crate::tests::creation(CommandId::new(), "ForgedDecision"), + crate::tests::creation("ForgedDecision"), &authenticated, ) .unwrap(); @@ -1520,7 +1519,6 @@ mod tests { let active = kernel.snapshot().unwrap(); let entry = affordance_named(&active, kind); let caller = play_caller(); - let command_id = CommandId::new(); let role = |name: &str, target| RoleBinding { role: crate::Role(name.into()), target, @@ -1529,7 +1527,6 @@ mod tests { .submit( command( &active, - command_id, caller.clone(), CommandBody::Act { actor: custody.holder, @@ -1559,7 +1556,7 @@ mod tests { let mut forged_head = kernel.state.clone(); let mut forged_commits = kernel.journal.commits.clone(); - let forged = forged_commits.get_mut(&command_id).unwrap(); + let forged = last_commit(&mut forged_commits); let WorldEffect::Acted { event, .. } = &mut forged.effect else { panic!("expected an acted effect"); }; @@ -1602,9 +1599,7 @@ mod tests { let path = directory.path().join("world.cc"); let owner = PrincipalId::new("owner@example.test"); let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); - let creation_id = CommandId::new(); let creation = CreateWorld { - id: creation_id, owner: owner.clone(), title: "Admitted".into(), patch: owner_patch(SubjectDeclaration { @@ -1620,7 +1615,7 @@ mod tests { let (kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); let mut forged_head = kernel.state.clone(); let mut forged_commits = kernel.journal.commits.clone(); - let forged = forged_commits.get_mut(&creation_id).unwrap(); + let forged = genesis_commit(&mut forged_commits); let CommittedCommand::CreateWorld(command) = &mut forged.command else { panic!("expected genesis creation command"); }; @@ -1635,7 +1630,7 @@ mod tests { let mut binding_forged_head = kernel.state.clone(); let mut binding_forged_commits = kernel.journal.commits.clone(); - let binding_forged = binding_forged_commits.get_mut(&creation_id).unwrap(); + let binding_forged = genesis_commit(&mut binding_forged_commits); let WorldEffect::WorldCreated { resolved, .. } = &mut binding_forged.effect else { panic!("expected genesis effect"); }; @@ -1662,7 +1657,7 @@ mod tests { let path = directory.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - crate::tests::creation(CommandId::new(), "Forged Rows"), + crate::tests::creation("Forged Rows"), &auth_principal(owner()), ) .unwrap(); @@ -1743,7 +1738,7 @@ mod tests { let path = directory.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - crate::tests::creation(CommandId::new(), "Old Store"), + crate::tests::creation("Old Store"), &auth_principal(owner()), ) .unwrap(); @@ -1789,14 +1784,14 @@ mod tests { use crate::tests::{affordance_named, civic_world, command, owner, play_caller}; use crate::{ DecisionInvocation, Magnitude, ProposedEffect, Quantity, Role, RoleBinding, - SubmitReceipt, Target, + Target, }; let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - crate::tests::creation(CommandId::new(), "Replayed Levy"), + crate::tests::creation("Replayed Levy"), &crate::tests::auth_principal(owner()), ) .unwrap(); @@ -1804,7 +1799,6 @@ mod tests { let caller = play_caller(); let envelope = command( &active, - CommandId::new(), caller.clone(), CommandBody::Act { actor: civic.treasury, @@ -1846,10 +1840,8 @@ mod tests { assert_eq!(replayed.band, event.band); assert_eq!(replayed.effects, event.effects); assert!(matches!( - reopened - .submit(envelope, &AuthenticatedCaller::fixture(caller)) - .unwrap(), - SubmitReceipt::AlreadyApplied(_) + reopened .submit(envelope, &AuthenticatedCaller::fixture(caller)), + Err(KernelError::RevisionMismatch { .. }) )); } @@ -1869,7 +1861,7 @@ mod tests { let path = directory.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - crate::tests::creation(CommandId::new(), "Forged Civics"), + crate::tests::creation("Forged Civics"), &auth_principal(owner()), ) .unwrap(); @@ -1977,7 +1969,7 @@ mod tests { let path = directory.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - crate::tests::creation(CommandId::new(), "Pre-Authority"), + crate::tests::creation("Pre-Authority"), &auth_principal(owner()), ) .unwrap(); @@ -2028,13 +2020,13 @@ mod tests { LEVY_KIND, auth_principal, civic_world, operations, over_subject, owner, reject_play, submit_play, }; - use crate::{ComponentOp, Mismatch, SubmitReceipt}; + use crate::{ComponentOp, Mismatch}; let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - crate::tests::creation(CommandId::new(), "Moving Civics"), + crate::tests::creation("Moving Civics"), &auth_principal(owner()), ) .unwrap(); @@ -2042,10 +2034,7 @@ mod tests { let admit = |kernel: &mut WorldKernel, ops: Vec| { let before = kernel.snapshot().unwrap(); - assert!(matches!( - submit_play(kernel, &before, operations(ops)), - SubmitReceipt::Applied(_) - )); + assert!(submit_play(kernel, &before, operations(ops)).resulting_revision > 0); verify_state_shape(&kernel.state).expect("the committed store keeps its shape"); assert!( crate::overlapping_holder(&kernel.state).is_none(), @@ -2108,9 +2097,10 @@ mod tests { #[cfg(test)] mod custody_tests { use super::*; + use super::tests::last_commit; use crate::{ - CallerId, CommandBody, CommandId, ComponentOp, DependencyRef, EntityKind, Quantity, Ref, - SubmitReceipt, WorldKernel, WorldPatch, + CallerId, CommandBody, ComponentOp, DependencyRef, EntityKind, Quantity, Ref, + WorldKernel, WorldPatch, tests::{admit_custody, admit_topology, auth_principal, command, creation, owner}, }; @@ -2123,7 +2113,7 @@ mod custody_tests { let path = directory.path().join("world.cc"); let authenticated = auth_principal(owner()); let (mut kernel, _) = - WorldKernel::create(&path, creation(CommandId::new(), "Replay"), &authenticated) + WorldKernel::create(&path, creation("Replay"), &authenticated) .unwrap(); let topology = admit_topology(&mut kernel); let custody = admit_custody(&mut kernel, &topology); @@ -2131,7 +2121,6 @@ mod custody_tests { let envelope = command( &active, - CommandId::new(), CallerId::Play, CommandBody::AdmitPatch { patch: WorldPatch { @@ -2146,21 +2135,17 @@ mod custody_tests { }, }, ); - let SubmitReceipt::Applied(receipt) = - kernel.submit(envelope.clone(), &crate::AuthenticatedCaller::verified_play()).unwrap() - else { - panic!("expected an applied transfer"); - }; + kernel.submit(envelope.clone(), &crate::AuthenticatedCaller::verified_play()).unwrap(); let accepted = kernel.snapshot().unwrap(); let world_id = accepted.world_id; drop(kernel); let mut reopened = WorldKernel::open(&path, world_id).unwrap(); assert_eq!(reopened.snapshot().unwrap(), accepted); - assert_eq!( - reopened.submit(envelope, &crate::AuthenticatedCaller::verified_play()).unwrap(), - SubmitReceipt::AlreadyApplied(receipt) - ); + assert!(matches!( + reopened.submit(envelope, &crate::AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) + )); } /// Replay recomputes `reduce`, so the band and the lowered operations are @@ -2176,7 +2161,7 @@ mod custody_tests { let authenticated = auth_principal(owner()); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "ActionReplay"), + creation("ActionReplay"), &authenticated, ) .unwrap(); @@ -2192,7 +2177,6 @@ mod custody_tests { }; let envelope = command( &active, - CommandId::new(), caller.clone(), CommandBody::Act { actor: custody.holder, @@ -2214,12 +2198,9 @@ mod custody_tests { }, ); let authenticated_controller = AuthenticatedCaller::fixture(caller); - let SubmitReceipt::Applied(receipt) = kernel + kernel .submit(envelope.clone(), &authenticated_controller) - .unwrap() - else { - panic!("expected an applied invocation"); - }; + .unwrap(); let accepted = kernel.snapshot().unwrap(); let committed = kernel .state @@ -2237,12 +2218,10 @@ mod custody_tests { reopened.state.events.last().expect("the replayed event"), &committed ); - assert_eq!( - reopened - .submit(envelope, &authenticated_controller) - .unwrap(), - SubmitReceipt::AlreadyApplied(receipt) - ); + assert!(matches!( + reopened .submit(envelope, &authenticated_controller), + Err(KernelError::RevisionMismatch { .. }) + )); } /// A store written at the pass-2 schema is refused outright. There is no @@ -2275,7 +2254,7 @@ mod custody_tests { let directory = tempfile::tempdir().unwrap(); let (kernel, _) = WorldKernel::create( directory.path().join("world.cc"), - creation(CommandId::new(), "Titled"), + creation("Titled"), &auth_principal(owner()), ) .unwrap(); @@ -2302,7 +2281,7 @@ mod custody_tests { let path = directory.path().join("world.cc"); let (kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "GrantRows"), + creation("GrantRows"), &auth_principal(owner()), ) .unwrap(); @@ -2348,7 +2327,7 @@ mod custody_tests { let path = directory.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "ActedChain"), + creation("ActedChain"), &auth_principal(owner()), ) .unwrap(); @@ -2392,13 +2371,13 @@ mod custody_tests { /// state row and commit row each on their own: reverting either constant /// to v8 would let its half of the store in. #[test] - fn v9_state_and_commit_rows_are_refused() { + fn ghostlight_state_and_commit_rows_are_refused() { use crate::tests::{act, auth_principal, creation, first_grant, owner, speak}; let directory = tempfile::tempdir().unwrap(); let (mut kernel, _) = WorldKernel::create( directory.path().join("world.cc"), - creation(CommandId::new(), "SchemaV9"), + creation("SchemaV9"), &auth_principal(owner()), ) .unwrap(); @@ -2415,8 +2394,8 @@ mod custody_tests { let state_row = |schema: &str| { envelope(STATE_ROW, schema, kernel.state.world_id.key(), &kernel.state).unwrap() }; - assert_eq!(STATE_SCHEMA, "ghostlight.world_state.consumer.v10"); - assert_eq!(COMMIT_SCHEMA, "ghostlight.world_commit.consumer.v10"); + assert_eq!(STATE_SCHEMA, "aetherlight.world_state.v1"); + assert_eq!(COMMIT_SCHEMA, "aetherlight.world_commit.v1"); recover( [commit_rows(COMMIT_SCHEMA), vec![state_row(STATE_SCHEMA)]].concat(), None, @@ -2425,17 +2404,17 @@ mod custody_tests { for (what, rows) in [ ( - "v9 state row", + "ghostlight state row", [ commit_rows(COMMIT_SCHEMA), - vec![state_row("ghostlight.world_state.consumer.v9")], + vec![state_row("ghostlight.world_state.consumer.v10")], ] .concat(), ), ( - "v9 commit rows", + "ghostlight commit rows", [ - commit_rows("ghostlight.world_commit.consumer.v9"), + commit_rows("ghostlight.world_commit.consumer.v10"), vec![state_row(STATE_SCHEMA)], ] .concat(), @@ -2462,7 +2441,7 @@ mod custody_tests { let directory = tempfile::tempdir().unwrap(); let (mut kernel, _) = WorldKernel::create( directory.path().join("world.cc"), - creation(CommandId::new(), "SilentForgery"), + creation("SilentForgery"), &auth_principal(owner()), ) .unwrap(); @@ -2520,7 +2499,7 @@ mod custody_tests { let path = directory.path().join("world.cc"); let authenticated = auth_principal(owner()); let (mut kernel, _) = - WorldKernel::create(&path, creation(CommandId::new(), "Shape"), &authenticated) + WorldKernel::create(&path, creation("Shape"), &authenticated) .unwrap(); let topology = admit_topology(&mut kernel); let custody = admit_custody(&mut kernel, &topology); @@ -2579,7 +2558,7 @@ mod custody_tests { let authenticated = auth_principal(owner()); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "EveryOperation"), + creation("EveryOperation"), &authenticated, ) .unwrap(); @@ -2591,7 +2570,6 @@ mod custody_tests { let envelope = command( &active, - CommandId::new(), CallerId::Play, CommandBody::AdmitPatch { patch: WorldPatch { @@ -2627,11 +2605,7 @@ mod custody_tests { }, }, ); - let SubmitReceipt::Applied(receipt) = - kernel.submit(envelope.clone(), &crate::AuthenticatedCaller::verified_play()).unwrap() - else { - panic!("expected an applied custody patch"); - }; + kernel.submit(envelope.clone(), &crate::AuthenticatedCaller::verified_play()).unwrap(); let accepted = kernel.snapshot().unwrap(); let holdings = kernel.state.holdings.clone(); let dependencies = kernel.state.dependencies.clone(); @@ -2644,10 +2618,10 @@ mod custody_tests { assert_eq!(reopened.state.holdings, holdings); assert_eq!(reopened.state.dependencies, dependencies); assert_eq!(reopened.state.state_digest, digest); - assert_eq!( - reopened.submit(envelope, &crate::AuthenticatedCaller::verified_play()).unwrap(), - SubmitReceipt::AlreadyApplied(receipt) - ); + assert!(matches!( + reopened.submit(envelope, &crate::AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) + )); } /// Soul: a dependency naming a target of the wrong kind, or no canonical @@ -2660,7 +2634,7 @@ mod custody_tests { let authenticated = auth_principal(owner()); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "DependencyShape"), + creation("DependencyShape"), &authenticated, ) .unwrap(); @@ -2704,7 +2678,7 @@ mod custody_tests { /// A world with one routine, one past-due goal, and a commit chain that /// reaches them: the fixture the two clock-forgery checks below need. - fn ticking_world(path: &std::path::Path) -> (WorldKernel, super::super::SubjectId, CommandId) { + fn ticking_world(path: &std::path::Path) -> (WorldKernel, super::super::SubjectId) { use crate::tests::{auth_principal, command, operations, owner}; use crate::{ AuthenticatedCaller, CallerId, CommandBody, CommitmentKind, ComponentOp, @@ -2714,7 +2688,7 @@ mod custody_tests { let authenticated = auth_principal(owner()); let (mut kernel, _) = WorldKernel::create( path, - crate::tests::creation(CommandId::new(), "Ticking"), + crate::tests::creation("Ticking"), &authenticated, ) .unwrap(); @@ -2725,7 +2699,6 @@ mod custody_tests { .submit( command( &snapshot, - CommandId::new(), CallerId::Play, operations(vec![ ComponentOp::CreateCommitment { @@ -2752,14 +2725,12 @@ mod custody_tests { ) .unwrap(); - let tick_id = CommandId::new(); let caller = CallerId::Play; let snapshot = kernel.snapshot().unwrap(); kernel .submit( command( &snapshot, - tick_id, caller.clone(), CommandBody::AdvanceTime { minutes: TickMinutes::new(30).unwrap(), @@ -2768,7 +2739,7 @@ mod custody_tests { &AuthenticatedCaller::fixture(caller), ) .unwrap(); - (kernel, subject, tick_id) + (kernel, subject) } /// Soul falsification: the replay gate and the `apply_effect` gate are two @@ -2781,11 +2752,12 @@ mod custody_tests { let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); - let (kernel, subject, tick_id) = ticking_world(&path); + let (kernel, subject) = ticking_world(&path); let WorldEffect::TimeAdvanced { motion, .. } = &kernel .journal .commits - .get(&tick_id) + .values() + .max_by_key(|commit| commit.resulting_revision) .expect("the tick's commit") .effect else { @@ -2797,7 +2769,7 @@ mod custody_tests { let forge = |rewrite: fn(&mut crate::Motion)| { let mut forged_head = kernel.state.clone(); let mut forged_commits = kernel.journal.commits.clone(); - let forged = forged_commits.get_mut(&tick_id).unwrap(); + let forged = last_commit(&mut forged_commits); let WorldEffect::TimeAdvanced { motion, .. } = &mut forged.effect else { panic!("expected a time-advanced effect"); }; @@ -2839,7 +2811,7 @@ mod custody_tests { fn soul_a_zero_period_is_refused_by_the_shape_check() { let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); - let (kernel, subject, _) = ticking_world(&path); + let (kernel, subject) = ticking_world(&path); // The forgery an in-crate caller cannot write: `TickMinutes::new` // refuses zero, and the field is private, so the only door is serde. diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index 94b323244..ce2483ab9 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -94,7 +94,6 @@ pub(crate) use patch::{ }; use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch}; -use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; @@ -103,18 +102,20 @@ use std::path::Path; use thiserror::Error; use uuid::Uuid; -pub const STATE_SCHEMA: &str = "ghostlight.world_state.consumer.v10"; -pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.consumer.v10"; +pub const STATE_SCHEMA: &str = "aetherlight.world_state.v1"; +pub(crate) const COMMIT_SCHEMA: &str = "aetherlight.world_commit.v1"; -/// Compatibility tag derived from [`STATE_SCHEMA`]: the trailing -/// `-` pair (e.g. `foundation-v1`). Callers that publish a -/// compatibility marker alongside the schema string must derive it from here -/// rather than hand-copying a second literal that can drift from the schema. -pub fn state_schema_compatibility_tag() -> String { - let mut segments = STATE_SCHEMA.rsplit('.'); - let version = segments.next().unwrap_or_default(); - let family = segments.next().unwrap_or_default(); - format!("{family}-{version}") +/// Domain strings of the three content-derived identities. A command is named +/// by what it says, so no caller draws an id and no retry needs one. +const COMMAND_DOMAIN: &[u8] = b"aetherlight.command.v1"; +const CREATE_DOMAIN: &[u8] = b"aetherlight.create.v1"; +const WORLD_DOMAIN: &[u8] = b"aetherlight.world.v1"; + +/// The first 16 bytes of a digest as a `Uuid`, as `patch::derive_id` truncates. +fn truncated_uuid(hasher: Sha256) -> Uuid { + let mut bytes = [0u8; 16]; + bytes.copy_from_slice(&hasher.finalize()[..16]); + Uuid::from_bytes(bytes) } /// The visibility argument is the whole boundary decision for an ID type: the @@ -142,23 +143,15 @@ opaque_uuid!(AffordanceId, pub); opaque_uuid!(EventId); impl CommandId { - fn issue() -> Self { - Self(Uuid::new_v4()) - } - - pub fn new() -> Self { - Self::issue() - } - - pub fn parse_uuid(value: &str) -> Result { - Uuid::parse_str(value) - .map(Self) - .map_err(|_| KernelError::InvalidCommandId) - } - fn key(self) -> String { self.0.to_string() } + + /// A named random id for tests that need a command id and no command. + #[cfg(test)] + fn issue() -> Self { + Self(Uuid::new_v4()) + } } impl WorldId { @@ -173,8 +166,12 @@ impl WorldId { Self(Uuid::nil()) } - fn issue() -> Self { - Self(Uuid::new_v4()) + /// The world is named by the creation that made it. + fn of(creation: CommandId) -> Self { + let mut hasher = Sha256::new(); + hasher.update(WORLD_DOMAIN); + hasher.update(creation.0.as_bytes()); + Self(truncated_uuid(hasher)) } fn key(self) -> String { @@ -235,7 +232,6 @@ pub enum SubjectKind { #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] struct CreateWorld { - id: CommandId, owner: PrincipalId, title: String, patch: WorldPatch, @@ -245,6 +241,16 @@ struct CreateWorld { grammar: Option, } +impl CreateWorld { + /// The creation is named by its own bytes: equal creations are one command. + fn id(&self) -> CommandId { + let mut hasher = Sha256::new(); + hasher.update(CREATE_DOMAIN); + hasher.update(rmp_serde::to_vec_named(self).expect("a creation command serializes")); + CommandId(truncated_uuid(hasher)) + } +} + /// Who wrote a command. The owner principal authors genesis and nothing after /// it; after genesis `Play` is the only caller any command body admits. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -335,13 +341,27 @@ pub struct DecisionInvocation { #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] struct CommandEnvelope { - id: CommandId, world_id: WorldId, expected_revision: u64, caller: CallerId, body: CommandBody, } +impl CommandEnvelope { + /// A command is named by the world, revision, caller and body it carries. + /// The revision is in the preimage so the same body at two revisions is + /// two commands, and every id derived from it is distinct. + fn id(&self) -> CommandId { + let mut hasher = Sha256::new(); + hasher.update(COMMAND_DOMAIN); + hasher.update(self.world_id.0.as_bytes()); + hasher.update(self.expected_revision.to_be_bytes()); + hasher.update(rmp_serde::to_vec_named(&self.caller).expect("a caller serializes")); + hasher.update(rmp_serde::to_vec_named(&self.body).expect("a command body serializes")); + CommandId(truncated_uuid(hasher)) + } +} + #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type", rename_all = "snake_case")] pub enum CommandBody { @@ -500,7 +520,7 @@ enum WorldEffect { } /// The exact raw command admitted by the kernel. This is the sole -/// persistent command authority: IDs, callers, retry identity, and effects are +/// persistent command authority: IDs, callers, and effects are /// derived from this value rather than copied into independently forgeable /// commit fields. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -513,8 +533,8 @@ enum CommittedCommand { impl CommittedCommand { fn id(&self) -> CommandId { match self { - Self::CreateWorld(command) => command.id, - Self::WorldCommand(command) => command.id, + Self::CreateWorld(command) => command.id(), + Self::WorldCommand(command) => command.id(), } } @@ -537,7 +557,6 @@ struct WorldCommit { resulting_state_digest: String, previous_commit_digest: Option, effect: WorldEffect, - committed_at: DateTime, digest: String, } @@ -790,7 +809,7 @@ impl CreationReceipt { )); }; Ok(Self { - command_id: command.id, + command_id: command.id(), world_id: commit.world_id, resulting_state_digest: commit.resulting_state_digest.clone(), commit_digest: commit.digest.clone(), @@ -809,16 +828,8 @@ impl From<&WorldCommit> for CommitReceipt { } } -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum SubmitReceipt { - Applied(CommitReceipt), - AlreadyApplied(CommitReceipt), -} - #[derive(Debug, Error)] pub enum KernelError { - #[error("command ID must be a UUID")] - InvalidCommandId, #[error("world title must not be empty")] EmptyTitle, #[error("world owner principal must be canonical and nonempty")] @@ -837,8 +848,6 @@ pub enum KernelError { AffordanceDenied, #[error("expected revision {expected}, current revision {actual}")] RevisionMismatch { expected: u64, actual: u64 }, - #[error("command ID was reused with different content")] - CommandIdConflict, #[error("world creation ID was reused with different content")] CreationConflict, #[error("world creation target already contains another world")] @@ -915,7 +924,7 @@ fn prepare_creation( let title = normalize_title(&input.title)?; // The world's own identity is not world structure, and it feeds every // derived ID, so it is minted before resolution rather than by it. - let world_id = WorldId::issue(); + let world_id = WorldId::of(input.id()); let resolved = patch::resolve_patch( &WorldState::empty( world_id, @@ -923,7 +932,7 @@ fn prepare_creation( title.clone(), input.grammar.clone(), ), - input.id, + input.id(), &input.patch, ) .map_err(KernelError::PatchRejected)?; @@ -959,7 +968,6 @@ impl WorldKernel { resulting_state_digest: state.state_digest.clone(), previous_commit_digest: None, effect, - committed_at: Utc::now(), digest: String::new(), }; genesis.digest = commit_digest(&genesis)?; @@ -971,7 +979,7 @@ impl WorldKernel { fn retry_creation(&self, prepared: &PreparedCreation) -> Result { self.journal.ensure_healthy()?; - let Some(commit) = self.journal.commit_for(prepared.command.id) else { + let Some(commit) = self.journal.commit_for(prepared.command.id()) else { return Err(KernelError::CreationTargetOccupied); }; if commit.command != CommittedCommand::CreateWorld(prepared.command.clone()) @@ -1014,28 +1022,15 @@ impl WorldKernel { &mut self, command: CommandEnvelope, authenticated: &AuthenticatedCaller, - ) -> Result { - let committed_at = Utc::now(); + ) -> Result { self.journal.ensure_healthy()?; + let command_id = command.id(); if command.world_id != self.state.world_id { return Err(KernelError::WorldMismatch); } if command.caller != authenticated.caller { return Err(KernelError::AuthenticationMismatch); } - // Retry identity is caller plus body. The expected revision is stamped by - // the mailbox owner rather than supplied by the caller, so it is not part - // of what makes a command the same command. - if let Some(commit) = self.committed_command(command.id) { - let CommittedCommand::WorldCommand(committed) = &commit.command else { - return Err(KernelError::CommandIdConflict); - }; - return if committed.caller == command.caller && committed.body == command.body { - Ok(SubmitReceipt::AlreadyApplied(CommitReceipt::from(commit))) - } else { - Err(KernelError::CommandIdConflict) - }; - } if command.expected_revision != self.state.revision { return Err(KernelError::RevisionMismatch { expected: command.expected_revision, @@ -1045,7 +1040,7 @@ impl WorldKernel { let effect = reduce(&self.state, &command)?; let mut candidate = self.state.clone(); - apply_effect(&mut candidate, command.id, &command.caller, &effect)?; + apply_effect(&mut candidate, command_id, &command.caller, &effect)?; candidate.revision = candidate .revision .checked_add(1) @@ -1062,7 +1057,6 @@ impl WorldKernel { resulting_state_digest: candidate.state_digest.clone(), previous_commit_digest: self.state.last_commit_digest.clone(), effect, - committed_at, digest: String::new(), }; commit.digest = commit_digest(&commit)?; @@ -1070,11 +1064,7 @@ impl WorldKernel { self.journal.commit(&candidate, &commit)?; self.state = candidate; - Ok(SubmitReceipt::Applied(CommitReceipt::from(&commit))) - } - - fn committed_command(&self, command_id: CommandId) -> Option<&WorldCommit> { - self.journal.commit_for(command_id) + Ok(CommitReceipt::from(&commit)) } } @@ -1084,10 +1074,11 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result { let granted = require_granted(state, *actor, invocation.affordance)?; - let event = action::exercise(state, command.id, *actor, &granted, invocation)?; + let event = action::exercise(state, command_id, *actor, &granted, invocation)?; Ok(WorldEffect::Acted { invocation: invocation.clone(), event, @@ -1108,7 +1099,7 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result { - let resolved = patch::resolve_patch(state, command.id, patch) + let resolved = patch::resolve_patch(state, command_id, patch) .map_err(KernelError::PatchRejected)?; Ok(WorldEffect::PatchAdmitted { resolved }) } @@ -1202,7 +1193,7 @@ impl WorldState { let mut state = Self::empty(world_id, owner.clone(), title.clone(), command.grammar.clone()); let expected = patch::resolve_patch( &state, - command.id, + command.id(), &command.patch, ) .map_err(KernelError::PatchRejected)?; @@ -3350,9 +3341,8 @@ mod tests { .expect("the fixture world declares this affordance") } - pub(crate) fn creation(id: CommandId, title: &str) -> CreateWorld { + pub(crate) fn creation(title: &str) -> CreateWorld { CreateWorld { - id, owner: owner(), title: title.into(), patch: WorldPatch { @@ -3413,12 +3403,10 @@ mod tests { pub(crate) fn command( snapshot: &WorldSnapshot, - id: CommandId, caller: CallerId, body: CommandBody, ) -> CommandEnvelope { CommandEnvelope { - id, world_id: snapshot.world_id, expected_revision: snapshot.revision, caller, @@ -3433,20 +3421,19 @@ mod tests { } } - pub(crate) fn play_command(snapshot: &WorldSnapshot, id: CommandId, body: CommandBody) -> CommandEnvelope { - command(snapshot, id, CallerId::Play, body) + pub(crate) fn play_command(snapshot: &WorldSnapshot, body: CommandBody) -> CommandEnvelope { + command(snapshot, CallerId::Play, body) } pub(crate) fn submit_play( kernel: &mut WorldKernel, snapshot: &WorldSnapshot, body: CommandBody, - ) -> SubmitReceipt { + ) -> CommitReceipt { kernel .submit( command( snapshot, - CommandId::new(), CallerId::Play, body, ), @@ -3563,7 +3550,7 @@ mod tests { patch: topology_patch(speak_entry(kernel)), }, ); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); let entity = |label: &str| { *kernel .state @@ -3881,7 +3868,7 @@ mod tests { patch: custody_patch(topology, speak_entry(kernel)), }, ); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); let entity = |label: &str| { *kernel .state @@ -4328,7 +4315,7 @@ mod tests { patch: civic_patch(topology, speak_entry(kernel)), }, ); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); let entity = |label: &str| { *kernel .state @@ -4590,7 +4577,6 @@ mod tests { .submit( command( snapshot, - CommandId::new(), CallerId::Play, body, ), @@ -4652,22 +4638,11 @@ mod tests { caller: CallerId, actor: SubjectId, invocation: DecisionInvocation, - ) -> Result { - act_command(kernel, CommandId::new(), caller, actor, invocation) - } - - pub(crate) fn act_command( - kernel: &mut WorldKernel, - command_id: CommandId, - caller: CallerId, - actor: SubjectId, - invocation: DecisionInvocation, - ) -> Result { + ) -> Result { let snapshot = kernel.snapshot().unwrap(); kernel.submit( command( &snapshot, - command_id, caller.clone(), CommandBody::Act { actor, invocation }, ), @@ -4683,7 +4658,7 @@ mod tests { kernel: &mut WorldKernel, actor: SubjectId, invocation: DecisionInvocation, - ) -> Result { + ) -> Result { act_as( kernel, CallerId::Play, @@ -4696,7 +4671,7 @@ mod tests { fn create_submit_restart_and_replay_are_exact() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("world.cc"); - let creation = creation(CommandId::new(), "First"); + let creation = creation("First"); let (mut kernel, creation_receipt) = WorldKernel::create(&path, creation.clone(), &auth_principal(owner())).unwrap(); let active = kernel.snapshot().unwrap(); @@ -4704,22 +4679,18 @@ mod tests { let caller = play_caller(); let command = command( &active, - CommandId::new(), caller.clone(), CommandBody::Act { actor: operator, invocation: speak(first_grant(&active, operator), "The vote carries."), }, ); - let applied = kernel + kernel .submit( command.clone(), &AuthenticatedCaller::fixture(caller.clone()), ) .unwrap(); - let SubmitReceipt::Applied(receipt) = applied else { - panic!("expected applied receipt") - }; let accepted = kernel.snapshot().unwrap(); drop(kernel); @@ -4727,12 +4698,10 @@ mod tests { WorldKernel::create(&path, creation, &auth_principal(owner())).unwrap(); assert_eq!(retried_creation_receipt, creation_receipt); assert_eq!(reopened.snapshot().unwrap(), accepted); - assert_eq!( - reopened - .submit(command, &AuthenticatedCaller::fixture(caller)) - .unwrap(), - SubmitReceipt::AlreadyApplied(receipt) - ); + assert!(matches!( + reopened .submit(command, &AuthenticatedCaller::fixture(caller)), + Err(KernelError::RevisionMismatch { .. }) + )); drop(reopened); let reopened = WorldKernel::open(&path, accepted.world_id).unwrap(); assert_eq!(reopened.snapshot().unwrap(), accepted); @@ -4744,17 +4713,14 @@ mod tests { let path = dir.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "Still"), + creation("Still"), &auth_principal(owner()), ) .unwrap(); let genesis = kernel.snapshot().unwrap(); - assert!(matches!( - submit_play(&mut kernel, &genesis, tick_body(1)), - SubmitReceipt::Applied(_) - )); + assert!(submit_play(&mut kernel, &genesis, tick_body(1)).resulting_revision > 0); let after = kernel.snapshot().unwrap(); - let stale = play_command(&genesis, CommandId::new(), tick_body(1)); + let stale = play_command(&genesis, tick_body(1)); assert!(matches!( kernel.submit(stale, &AuthenticatedCaller::verified_play()), Err(KernelError::RevisionMismatch { .. }) @@ -4764,75 +4730,57 @@ mod tests { } #[test] - fn durable_idempotency_precedes_revision_and_detects_conflicts() { + fn ids_are_derived_from_the_command() { let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("world.cc"); - let (mut kernel, _) = WorldKernel::create( - &path, - creation(CommandId::new(), "A"), - &auth_principal(owner()), - ) - .unwrap(); - let genesis = kernel.snapshot().unwrap(); - let id = CommandId::new(); - let first = play_command(&genesis, id, tick_body(1)); - let first_receipt = kernel - .submit(first.clone(), &AuthenticatedCaller::verified_play()) - .unwrap(); - let second_snapshot = kernel.snapshot().unwrap(); - kernel - .submit( - play_command(&second_snapshot, CommandId::new(), tick_body(1)), - &AuthenticatedCaller::verified_play(), - ) - .unwrap(); - let after_second = kernel.snapshot().unwrap(); - assert_eq!( - kernel - .submit(first, &AuthenticatedCaller::verified_play()) - .unwrap(), - match first_receipt { - SubmitReceipt::Applied(value) => SubmitReceipt::AlreadyApplied(value), - _ => unreachable!(), - } - ); - let conflict = play_command(&genesis, id, tick_body(2)); - assert!(matches!( - kernel.submit(conflict, &AuthenticatedCaller::verified_play()), - Err(KernelError::CommandIdConflict) - )); - assert_eq!(kernel.snapshot().unwrap(), after_second); - } + let create = |name: &str, title: &str| { + WorldKernel::create(dir.path().join(name), creation(title), &auth_principal(owner())) + .unwrap() + }; + let (mut kernel, receipt) = create("a.cc", "Same"); + let (twin, twin_receipt) = create("b.cc", "Same"); + assert_eq!(receipt, twin_receipt); + assert_eq!(kernel.state.world_id, twin.state.world_id); + assert_eq!(receipt.world_id, WorldId::of(receipt.command_id)); + let (other, _) = create("c.cc", "Other"); + assert_ne!(kernel.state.world_id, other.state.world_id); - #[test] - fn creation_retry_is_bound_to_the_exact_raw_command() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("world.cc"); - let id = CommandId::new(); - let raw = creation(id, " Canonical Result "); - let (kernel, first) = - WorldKernel::create(&path, raw.clone(), &auth_principal(owner())).unwrap(); - assert_eq!(kernel.snapshot().unwrap().title, "Canonical Result"); - drop(kernel); - - let (kernel, retry) = - WorldKernel::create(&path, raw.clone(), &auth_principal(owner())).unwrap(); - assert_eq!(retry, first); - drop(kernel); - - let mut merely_equivalent = raw; - merely_equivalent.title = "Canonical Result".into(); - assert!(matches!( - WorldKernel::create(&path, merely_equivalent, &auth_principal(owner())), - Err(KernelError::CreationConflict) - )); + // The same patch at two revisions is two commands, so the entity it + // declares is minted twice under two ids. + let patch = WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("cairn"), + label: "A Cairn".into(), + kind: EntityKind::Place, + container: None, + })], + operations: Vec::new(), + evidence: Vec::new(), + }; + let mut ids = BTreeSet::new(); + for _ in 0..2 { + let snapshot = kernel.snapshot().unwrap(); + let envelope = play_command(&snapshot, CommandBody::AdmitPatch { patch: patch.clone() }); + let expected = envelope.id(); + let receipt = kernel + .submit(envelope, &AuthenticatedCaller::verified_play()) + .unwrap(); + assert_eq!(receipt.command_id, expected); + assert!(ids.insert(receipt.command_id), "two commands share an id"); + } + let cairns = kernel + .state + .entities + .values() + .filter(|entity| entity.label == "A Cairn") + .count(); + assert_eq!(cairns, 2); } #[test] fn invalid_seed_never_allocates_a_world() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("world.cc"); - let mut invalid = creation(CommandId::new(), "Nope"); + let mut invalid = creation("Nope"); invalid.patch.declarations[3] = invalid.patch.declarations[2].clone(); let Err(KernelError::PatchRejected(rejected)) = WorldKernel::create(&path, invalid, &auth_principal(owner())) @@ -4848,7 +4796,7 @@ mod tests { assert!( WorldKernel::create( &path, - creation(CommandId::new(), "Valid"), + creation("Valid"), &auth_principal(owner()) ) .is_ok() @@ -4859,7 +4807,7 @@ mod tests { fn a_second_live_owner_is_refused() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("world.cc"); - let creation = creation(CommandId::new(), "Held"); + let creation = creation("Held"); let (kernel, _) = WorldKernel::create(&path, creation.clone(), &auth_principal(owner())).unwrap(); let world_id = kernel.snapshot().unwrap().world_id; @@ -4875,7 +4823,7 @@ mod tests { let kernel = WorldKernel::open(&path, world_id).unwrap(); drop(kernel); assert!(matches!( - WorldKernel::open(&path, WorldId::issue()), + WorldKernel::open(&path, WorldId::of(CommandId::issue())), Err(KernelError::OpenedWorldMismatch) )); } @@ -4886,13 +4834,13 @@ mod tests { let path = dir.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "Certain"), + creation("Certain"), &auth_principal(owner()), ) .unwrap(); let genesis = kernel.snapshot().unwrap(); - let uncertain = CommandId::new(); - let attempted = play_command(&genesis, uncertain, tick_body(1)); + let attempted = play_command(&genesis, tick_body(1)); + let uncertain = attempted.id(); kernel.journal.fail_after_durable_commit_for_test(); assert!(matches!( kernel.submit(attempted.clone(), &AuthenticatedCaller::verified_play()), @@ -4908,10 +4856,8 @@ mod tests { let durable = reopened.snapshot().unwrap(); assert_eq!(durable.revision, 1); assert!(matches!( - reopened - .submit(attempted, &AuthenticatedCaller::verified_play()) - .unwrap(), - SubmitReceipt::AlreadyApplied(_) + reopened .submit(attempted, &AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) )); } @@ -4919,8 +4865,8 @@ mod tests { fn lost_genesis_ack_reopens_as_the_same_world_and_exact_receipt() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("world.cc"); - let command_id = CommandId::new(); - let input = creation(command_id, "Durable Genesis"); + let input = creation("Durable Genesis"); + let command_id = input.id(); let authenticated = auth_principal(owner()); let mut empty = match journal::WorldJournal::open_owner(&path).unwrap() { journal::JournalOpen::Empty(empty) => empty, @@ -4949,7 +4895,7 @@ mod tests { let displaced = dir.path().join("displaced.cc"); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "Pinned"), + creation("Pinned"), &auth_principal(owner()), ) .unwrap(); @@ -4959,7 +4905,7 @@ mod tests { assert!(matches!(kernel.snapshot(), Err(KernelError::OwnershipLost))); assert!(matches!( kernel.submit( - play_command(&snapshot, CommandId::new(), tick_body(1)), + play_command(&snapshot, tick_body(1)), &AuthenticatedCaller::verified_play() ), Err(KernelError::OwnershipLost) @@ -4978,14 +4924,13 @@ mod tests { let path = dir.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "Owned"), + creation("Owned"), &auth_principal(owner()), ) .unwrap(); let snapshot = kernel.snapshot().unwrap(); let forged = command( &snapshot, - CommandId::new(), CallerId::Principal(human_principal()), tick_body(1), ); @@ -5004,7 +4949,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (mut kernel, _) = WorldKernel::create( dir.path().join("world.cc"), - creation(CommandId::new(), "Preimage"), + creation("Preimage"), &auth_principal(owner()), ) .unwrap(); @@ -5126,7 +5071,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (mut kernel, _) = WorldKernel::create( dir.path().join("world.cc"), - creation(CommandId::new(), "SharedCatalogIds"), + creation("SharedCatalogIds"), &auth_principal(owner()), ) .unwrap(); @@ -5165,10 +5110,7 @@ mod tests { }; // The grantee's scope commits with that id. - assert!(matches!( - invoke(&mut kernel, holders[0]).unwrap(), - SubmitReceipt::Applied(_) - )); + assert!(invoke(&mut kernel, holders[0]).unwrap().resulting_revision > 0); // A scope that does not hold the entry is denied the very same id, and // nothing commits. @@ -5191,7 +5133,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (mut kernel, _) = WorldKernel::create( dir.path().join("world.cc"), - creation(CommandId::new(), "BindingAndAdmission"), + creation("BindingAndAdmission"), &auth_principal(owner()), ) .unwrap(); @@ -5229,7 +5171,7 @@ mod tests { }, ) .expect("a distant route closing does not stop this act"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); } /// The mvp doc's disjointness requirement: an institution with an @@ -5286,7 +5228,6 @@ mod tests { .submit( command( &active, - CommandId::new(), caller.clone(), CommandBody::Act { actor: civic.treasury, @@ -5314,7 +5255,7 @@ mod tests { &AuthenticatedCaller::fixture(caller), ) .unwrap(); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); let held = |holder: SubjectId| { kernel @@ -5453,16 +5394,7 @@ mod tests { // A different kind over the same ground commits, and so does the same // kind held by a different subject: two holders authorized over one // target is not a contradiction, because nothing arbitrates. - assert!(matches!( - admit( - &mut kernel, - vec![ - grant_to(civic.reeve, JUDGE_KIND, over_place(civic.chamber)), - grant_to(civic.outsider, LEVY_KIND, over_place(civic.chamber)), - ] - ), - SubmitReceipt::Applied(_) - )); + assert!(admit( &mut kernel, vec![ grant_to(civic.reeve, JUDGE_KIND, over_place(civic.chamber)), grant_to(civic.outsider, LEVY_KIND, over_place(civic.chamber)), ] ).resulting_revision > 0); } /// Contract 6 on the civic surface: one patch, the complete sorted set, no @@ -5533,10 +5465,7 @@ mod tests { standing: over_place(civic.hall), }, ]; - assert!(matches!( - submit_play(&mut kernel, &before, operations(repaired)), - SubmitReceipt::Applied(_) - )); + assert!(submit_play(&mut kernel, &before, operations(repaired)).resulting_revision > 0); } /// A civic operation that changes nothing is not a canonical change. @@ -5828,7 +5757,7 @@ mod custody_tests { pub(crate) fn custody_kernel(path: &Path, title: &str) -> WorldKernel { WorldKernel::create( path.join("world.cc"), - creation(CommandId::new(), title), + creation(title), &auth_principal(owner()), ) .expect("a created world") @@ -6004,7 +5933,7 @@ mod custody_tests { qty: Quantity(3), }]), ); - assert!(matches!(after_three, SubmitReceipt::Applied(_))); + assert!(after_three.resulting_revision > 0); assert_eq!(holding(&kernel, custody.holder, custody.tithe), 4); let snapshot = kernel.snapshot().unwrap(); @@ -6359,7 +6288,7 @@ mod custody_tests { }, ]), ); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); // Transfer contributes to no term; transform contributes one spent and // one gained; consume contributes one consumed. Nothing was admitted. @@ -6596,7 +6525,7 @@ mod custody_tests { speak(first_grant(&moved, topology.walker), "Unmoved."), ) .expect("an unrelated subject acts at the later revision"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); } } @@ -6617,7 +6546,7 @@ mod knowledge_tests { fn speech_kernel(path: &Path, title: &str) -> (WorldKernel, Speech, WorldSnapshot) { let mut kernel = WorldKernel::create( path.join("world.cc"), - creation(CommandId::new(), title), + creation(title), &auth_principal(owner()), ) .expect("a created world") @@ -6630,7 +6559,7 @@ mod knowledge_tests { kernel: &mut WorldKernel, actor: SubjectId, invocation: DecisionInvocation, - ) -> Result { + ) -> Result { act(kernel, actor, invocation) } @@ -6651,7 +6580,7 @@ mod knowledge_tests { } } - fn rejected(result: Result) -> Vec { + fn rejected(result: Result) -> Vec { match result { Err(KernelError::ActionRejected(mismatches)) => mismatches, other => panic!("expected a rejected invocation, got {other:?}"), @@ -6751,7 +6680,7 @@ mod knowledge_tests { let directory = tempfile::tempdir().unwrap(); let mut draft = WorldKernel::create( directory.path().join("world.cc"), - creation(CommandId::new(), "Standing"), + creation("Standing"), &auth_principal(owner()), ) .expect("a draft world") @@ -7151,7 +7080,7 @@ mod knowledge_tests { let (speech, world_id, expected) = { let mut kernel = WorldKernel::create( &path, - creation(CommandId::new(), "ReplayDisplay"), + creation("ReplayDisplay"), &auth_principal(owner()), ) .expect("a created world") @@ -7412,26 +7341,23 @@ mod knowledge_tests { let directory = tempfile::tempdir().unwrap(); let (mut kernel, speech, active) = speech_kernel(directory.path(), "Allocation"); let world_id = kernel.state.world_id; - let command_id = CommandId::new(); let caller = play_caller(); let entities_before = kernel.state.entities.len(); - kernel - .submit( - command( - &active, - command_id, - caller.clone(), - CommandBody::Act { - actor: speech.speaker, - invocation: say( - speech.whisper, - vec![binding("target", Target::Subject(speech.listener))], - "Counted.", - ), - }, + let whisper = command( + &active, + caller.clone(), + CommandBody::Act { + actor: speech.speaker, + invocation: say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "Counted.", ), - &AuthenticatedCaller::fixture(caller), - ) + }, + ); + let command_id = whisper.id(); + kernel + .submit(whisper, &AuthenticatedCaller::fixture(caller)) .expect("the whisper commits"); let claim = minted_claim(&kernel); @@ -7464,7 +7390,7 @@ mod knowledge_tests { let (speech, world_id, expected) = { let mut kernel = WorldKernel::create( &path, - creation(CommandId::new(), "ReplaySpeech"), + creation("ReplaySpeech"), &auth_principal(owner()), ) .expect("a created world") @@ -7516,7 +7442,7 @@ mod knowledge_tests { fn a_forged_claim_or_forged_recipient_does_not_apply() { let directory = tempfile::tempdir().unwrap(); let (kernel, speech, _) = speech_kernel(directory.path(), "Forgery"); - let command_id = CommandId::new(); + let command_id = CommandId::issue(); let caller = play_caller(); let invocation = say( speech.proclaim, @@ -7633,7 +7559,7 @@ mod knowledge_tests { let directory = tempfile::tempdir().unwrap(); let mut kernel = WorldKernel::create( directory.path().join("world.cc"), - creation(CommandId::new(), "SpeechAudience"), + creation("SpeechAudience"), &auth_principal(owner()), ) .expect("a draft world") @@ -7702,7 +7628,7 @@ mod knowledge_tests { ), ) .expect("both statements commit identically"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); let event = kernel.state.events.last().unwrap().clone(); (kernel, speech, event) }; @@ -7743,7 +7669,7 @@ mod soul_knowledge_tests { fn speech_kernel(path: &Path, title: &str) -> (WorldKernel, Speech, WorldSnapshot) { let mut kernel = WorldKernel::create( path.join("world.cc"), - creation(CommandId::new(), title), + creation(title), &auth_principal(owner()), ) .expect("a created world") @@ -7773,7 +7699,7 @@ mod soul_knowledge_tests { kernel: &mut WorldKernel, actor: SubjectId, invocation: DecisionInvocation, - ) -> Result { + ) -> Result { act(kernel, actor, invocation) } @@ -7943,7 +7869,7 @@ mod soul_knowledge_tests { fn soul_a_forged_wider_audience_does_not_apply() { let directory = tempfile::tempdir().unwrap(); let (kernel, speech, _) = speech_kernel(directory.path(), "WiderAudience"); - let command_id = CommandId::new(); + let command_id = CommandId::issue(); let caller = play_caller(); let invocation = say( speech.whisper, @@ -8110,7 +8036,6 @@ mod soul_knowledge_tests { .submit( command( &active, - CommandId::new(), CallerId::Play, operations(vec![tell.clone(), forget.clone()]), ), @@ -8181,7 +8106,6 @@ mod soul_knowledge_tests { .submit( command( &active, - CommandId::new(), CallerId::Play, CommandBody::AdmitPatch { patch: WorldPatch { @@ -8201,7 +8125,7 @@ mod soul_knowledge_tests { &AuthenticatedCaller::fixture(CallerId::Play), ) .expect("the play table declares a claim in Active"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); assert_eq!(kernel.state.facts.len(), before.facts.len() + 1); let facts = kernel.state.facts.clone(); drop(kernel); @@ -8408,7 +8332,7 @@ mod witness_tests { fn nesting_kernel(path: &Path, title: &str) -> (WorldKernel, Nesting, WorldSnapshot) { let mut kernel = WorldKernel::create( path.join("world.cc"), - creation(CommandId::new(), title), + creation(title), &auth_principal(owner()), ) .expect("a created world") @@ -8888,7 +8812,6 @@ mod witness_tests { .submit( command( &active, - CommandId::new(), caller.clone(), CommandBody::Act { actor: world.villager, @@ -8995,7 +8918,7 @@ mod witness_tests { fn a_genesis_seeded_knowledge_row_is_acquired_at_revision_zero() { let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); - let mut creation = creation(CommandId::new(), "PAf49Genesis"); + let mut creation = creation("PAf49Genesis"); creation.patch.declarations.push(Declaration::Fact(FactDeclaration { handle: DraftHandle::new("founding"), label: "The Founding Ruling".into(), @@ -9258,7 +9181,6 @@ mod witness_tests { kernel.submit( command( &snapshot, - CommandId::new(), caller.clone(), CommandBody::AdmitPatch { patch: WorldPatch { @@ -9313,7 +9235,7 @@ mod witness_tests { Some(world.village), ); assert!( - matches!(receipt, Ok(SubmitReceipt::Applied(_))), + matches!(receipt, Ok(_)), "{receipt:?}" ); let arrived = *kernel @@ -9384,7 +9306,7 @@ mod witness_tests { witness(world.asteroid, world.village, Confidence::Certain), ]), ); - assert!(matches!(receipt, SubmitReceipt::Applied(_)), "{receipt:?}"); + assert!(receipt.resulting_revision > 0, "{receipt:?}"); assert_eq!( knows(&kernel, world.villager, world.asteroid), seen(Confidence::Certain, seeded.revision + 1), @@ -9484,7 +9406,7 @@ mod clock_tests { fn clock_kernel(path: &Path, title: &str) -> (WorldKernel, Clockwork, WorldSnapshot) { let mut kernel = WorldKernel::create( path.join("world.cc"), - creation(CommandId::new(), title), + creation(title), &auth_principal(owner()), ) .expect("a created world") @@ -9725,12 +9647,11 @@ mod clock_tests { ) } - fn tick(kernel: &mut WorldKernel, span: u32) -> Result { + fn tick(kernel: &mut WorldKernel, span: u32) -> Result { let snapshot = kernel.snapshot().unwrap(); kernel.submit( command( &snapshot, - CommandId::new(), CallerId::Play, CommandBody::AdvanceTime { minutes: minutes(span), @@ -9745,7 +9666,7 @@ mod clock_tests { actor: SubjectId, affordance: AffordanceId, bindings: Vec, - ) -> Result { + ) -> Result { act( kernel, actor, @@ -9986,7 +9907,7 @@ mod clock_tests { let directory = tempfile::tempdir().unwrap(); let mut kernel = WorldKernel::create( directory.path().join("world.cc"), - creation(CommandId::new(), "Negatives"), + creation("Negatives"), &auth_principal(owner()), ) .expect("a created world") @@ -10006,7 +9927,6 @@ mod clock_tests { .submit( command( &active, - CommandId::new(), caller.clone(), CommandBody::AdvanceTime { minutes: minutes(1), @@ -10036,7 +9956,6 @@ mod clock_tests { .submit( command( &snapshot, - CommandId::new(), CallerId::Play, CommandBody::AdvanceTime { minutes: minutes(1), @@ -10157,7 +10076,6 @@ mod clock_tests { let snapshot = kernel.snapshot().unwrap(); let repeat = command( &snapshot, - CommandId::new(), CallerId::Play, operations(vec![ComponentOp::DischargeCommitment { subject: Ref::Existing(clockwork.farmer), @@ -10188,7 +10106,7 @@ mod clock_tests { assert_eq!(replayed.snapshot().unwrap(), before_snapshot); assert!(matches!( replayed.submit(repeat, &AuthenticatedCaller::verified_play()), - Ok(SubmitReceipt::AlreadyApplied(_)) + Err(KernelError::RevisionMismatch { .. }) )); } @@ -10267,7 +10185,7 @@ mod clock_tests { ComponentOp::DischargeCommitment { subject: Ref::Existing(clockwork.farmer), key: CommitmentKey { - command: CommandId::new(), + command: CommandId::issue(), index: 0, }, }, @@ -10624,7 +10542,7 @@ mod clock_tests { fn genesis_may_not_rule_or_mint() { let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); - let mut input = creation(CommandId::new(), "RulesAndMints"); + let mut input = creation("RulesAndMints"); for handle in ["first-rule", "second-rule"] { input .patch @@ -10673,7 +10591,7 @@ mod clock_tests { fn a_genesis_patch_carrying_a_ruled_fact_is_refused() { let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); - let mut input = creation(CommandId::new(), "RuledGenesis"); + let mut input = creation("RuledGenesis"); input .patch .declarations @@ -10702,7 +10620,7 @@ mod clock_tests { fn a_genesis_patch_carrying_a_mint_is_refused() { let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("world.cc"); - let mut input = creation(CommandId::new(), "MintGenesis"); + let mut input = creation("MintGenesis"); input .patch .declarations @@ -10732,8 +10650,8 @@ mod clock_tests { /// so this cannot be satisfied by `prepare_creation`'s own check. #[test] fn genesis_itself_refuses_a_ruled_fact_and_a_mint() { - let world_id = WorldId::issue(); - let mut input = creation(CommandId::new(), "GenesisRuleDirect"); + let mut input = creation("GenesisRuleDirect"); + let world_id = WorldId::of(input.id()); input .patch .declarations @@ -10746,7 +10664,7 @@ mod clock_tests { let title = normalize_title(&input.title).unwrap(); let resolved = patch::resolve_patch( &WorldState::empty(world_id, input.owner.clone(), title.clone(), None), - input.id, + input.id(), &input.patch, ) .expect("the resolver is actor-blind and accepts a Ruled fact"); @@ -10758,8 +10676,8 @@ mod clock_tests { let error = WorldState::genesis(world_id, &input, &effect).unwrap_err(); assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); - let world_id = WorldId::issue(); - let mut input = creation(CommandId::new(), "GenesisMintDirect"); + let mut input = creation("GenesisMintDirect"); + let world_id = WorldId::of(input.id()); input .patch .declarations @@ -10772,7 +10690,7 @@ mod clock_tests { let title = normalize_title(&input.title).unwrap(); let resolved = patch::resolve_patch( &WorldState::empty(world_id, input.owner.clone(), title.clone(), None), - input.id, + input.id(), &input.patch, ) .expect("the resolver is actor-blind and accepts a Mint"); @@ -10911,7 +10829,6 @@ mod clock_tests { let snapshot = kernel.snapshot().unwrap(); let ticking = command( &snapshot, - CommandId::new(), CallerId::Play, CommandBody::AdvanceTime { minutes: minutes(span), @@ -10929,7 +10846,7 @@ mod clock_tests { // Applying the re-derived effect to a copy reproduces the committed // state exactly, which is the replay identity the journal relies on. let mut replayed = kernel.state.clone(); - apply_effect(&mut replayed, ticking.id, &CallerId::Play, &expected) + apply_effect(&mut replayed, ticking.id(), &CallerId::Play, &expected) .expect("the re-derived effect applies"); kernel .submit(ticking, &AuthenticatedCaller::fixture(CallerId::Play)) @@ -10945,10 +10862,10 @@ mod clock_tests { kernel: &mut WorldKernel, caller: CallerId, body: CommandBody, - ) -> Result { + ) -> Result { let snapshot = kernel.snapshot().unwrap(); kernel.submit( - command(&snapshot, CommandId::new(), caller.clone(), body), + command(&snapshot, caller.clone(), body), &AuthenticatedCaller::fixture(caller), ) } @@ -11035,7 +10952,7 @@ mod clock_tests { }, ) .expect("the play authority declares unanswered in Active"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); } /// Invariant 5: the play authority reaches the whole world, unconfined to @@ -11068,7 +10985,7 @@ mod clock_tests { }, ) .expect("the play authority advances time"); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); assert!(kernel.state.now > active.now); } @@ -11279,7 +11196,7 @@ mod clock_tests { } /// Play retires a subject. - fn play_retires(kernel: &mut WorldKernel, subject: SubjectId) -> Result { + fn play_retires(kernel: &mut WorldKernel, subject: SubjectId) -> Result { submit_as( kernel, CallerId::Play, @@ -11444,7 +11361,7 @@ mod clock_tests { let directory = tempfile::tempdir().unwrap(); let mut kernel = WorldKernel::create( directory.path().join("world.cc"), - creation(CommandId::new(), "SeedGrantsDraft"), + creation("SeedGrantsDraft"), &auth_principal(owner()), ) .expect("a created world") @@ -11726,7 +11643,7 @@ mod clock_tests { let directory = tempfile::tempdir().unwrap(); let mut kernel = WorldKernel::create( directory.path().join("world.cc"), - creation(CommandId::new(), "PAf33CanReach"), + creation("PAf33CanReach"), &auth_principal(owner()), ) .expect("a created world") @@ -12286,7 +12203,7 @@ mod agency_tests { let path = directory.path().join("world.cc"); let (kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), title), + creation(title), &auth_principal(owner()), ) .unwrap(); @@ -12359,7 +12276,7 @@ mod agency_tests { let commits = kernel.journal.commit_count(); let error = kernel .submit( - command(&snapshot, CommandId::new(), caller.clone(), body.clone()), + command(&snapshot, caller.clone(), body.clone()), &AuthenticatedCaller::fixture(caller.clone()), ) .unwrap_err(); @@ -12375,11 +12292,11 @@ mod agency_tests { let before = kernel.snapshot().unwrap(); let receipt = kernel .submit( - play_command(&before, CommandId::new(), body), + play_command(&before, body), &AuthenticatedCaller::verified_play(), ) .unwrap_or_else(|error| panic!("Play {name}: {error:?}")); - assert!(matches!(receipt, SubmitReceipt::Applied(_)), "Play {name}"); + assert!(receipt.resulting_revision > 0, "Play {name}"); } } @@ -12458,7 +12375,7 @@ mod agency_tests { for body in [broken.clone(), denied.clone()] { let error = kernel .submit( - command(&snapshot, CommandId::new(), caller.clone(), body), + command(&snapshot, caller.clone(), body), &AuthenticatedCaller::fixture(caller.clone()), ) .unwrap_err(); @@ -12619,7 +12536,7 @@ mod agency_tests { }) }; let directory = tempfile::tempdir().unwrap(); - let mut input = creation(CommandId::new(), "Mutes"); + let mut input = creation("Mutes"); input.patch.declarations.push(mute("born-mute")); let (mut kernel, _) = WorldKernel::create( directory.path().join("world.cc"), diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs index c63939012..cbdc5477d 100644 --- a/native/aetherlight/src/patch.rs +++ b/native/aetherlight/src/patch.rs @@ -5679,7 +5679,7 @@ mod tests { over_place, owner, reject_play, speak_entry, submit_play, }; use crate::{ - AuthenticatedCaller, CallerId, CommandBody, CommandId, KernelError, SubmitReceipt, WorldKernel, + AuthenticatedCaller, CallerId, CommandBody, CommandId, KernelError, WorldKernel, }; fn entity(handle: &str, label: &str, kind: EntityKind) -> Declaration { @@ -6030,7 +6030,7 @@ mod tests { granting("verb"), ])), ); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); assert_eq!(kernel.state.affordance_catalog.len(), entries_before + 1); assert_eq!(kernel.state.subjects.len(), subjects_before + 1); let granted = kernel @@ -6106,7 +6106,7 @@ mod tests { fn draft_world(directory: &std::path::Path) -> WorldKernel { WorldKernel::create( directory.join("world.cc"), - creation(CommandId::new(), "Kharad"), + creation("Kharad"), &auth_principal(owner()), ) .expect("draft world") @@ -6126,7 +6126,6 @@ mod tests { .submit( command( &before, - CommandId::new(), CallerId::Play, admit(patch_of(vec![institution( &kernel, @@ -6183,7 +6182,7 @@ mod tests { ), ]); let receipt = submit_play(&mut kernel, &before, admit(patch)); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); let after = kernel.snapshot().unwrap(); assert_eq!(after.revision, before.revision + 1); @@ -6236,7 +6235,6 @@ mod tests { .submit( command( &before, - CommandId::new(), CallerId::Play, admit(patch_of(vec![ entity("rhythm-tithe", "The Rhythm Tithe", EntityKind::Resource), @@ -6290,7 +6288,6 @@ mod tests { .submit( command( &before, - CommandId::new(), CallerId::Play, admit(broken), ), @@ -6336,7 +6333,7 @@ mod tests { }), ]); let receipt = submit_play(&mut kernel, &before, admit(repaired)); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); assert_eq!(kernel.state.entities.len(), 3); } @@ -6350,7 +6347,6 @@ mod tests { .submit( command( &before, - CommandId::new(), CallerId::Play, admit(patch_of(Vec::new())), ), @@ -6377,7 +6373,6 @@ mod tests { .submit( command( &before, - CommandId::new(), CallerId::Play, admit(patch_of(vec![ contained("yard", "The Cavity Yard", "road"), @@ -6422,7 +6417,6 @@ mod tests { .submit( command( &before, - CommandId::new(), CallerId::Play, admit(patch_of(vec![ entity("yard", "The Cavity Yard", EntityKind::Place), @@ -6462,7 +6456,6 @@ mod tests { .submit( command( &before, - CommandId::new(), CallerId::Play, admit(WorldPatch { declarations: vec![Declaration::Route(RouteDeclaration { @@ -6521,7 +6514,6 @@ mod tests { .submit( command( &active, - CommandId::new(), CallerId::Play, admit(operations_of(vec![ComponentOp::Relocate { subject: Ref::Existing(topology.walker), @@ -6572,7 +6564,7 @@ mod tests { ])), ); assert!( - matches!(receipt, SubmitReceipt::Applied(_)), + receipt.resulting_revision > 0, "a dead institution's lend must not collide with a fresh direct grant over the same ground" ); } @@ -6609,7 +6601,7 @@ mod tests { ])), ); assert!( - matches!(delegated, SubmitReceipt::Applied(_)), + delegated.resulting_revision > 0, "expected the delegation patch to apply, got {delegated:?}" ); let after_delegation = kernel.snapshot().unwrap(); @@ -6654,7 +6646,7 @@ mod tests { via: Ref::Existing(topology.ramp), }])), ); - assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(receipt.resulting_revision > 0); assert_eq!( kernel.state.positions.get(&topology.walker), Some(&Position { @@ -6681,7 +6673,7 @@ mod tests { let path = directory.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "Kharad"), + creation("Kharad"), &auth_principal(owner()), ) .unwrap(); @@ -6689,7 +6681,6 @@ mod tests { let active = kernel.snapshot().unwrap(); let envelope = command( &active, - CommandId::new(), CallerId::Play, admit(operations_of(vec![ComponentOp::Relocate { subject: Ref::Existing(topology.walker), @@ -6712,8 +6703,8 @@ mod tests { }) ); assert!(matches!( - reopened.submit(envelope, &AuthenticatedCaller::verified_play()).unwrap(), - SubmitReceipt::AlreadyApplied(_) + reopened.submit(envelope, &AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) )); } @@ -6764,14 +6755,13 @@ mod tests { let path = directory.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "Kharad"), + creation("Kharad"), &auth_principal(owner()), ) .unwrap(); let before = kernel.snapshot().unwrap(); let envelope = command( &before, - CommandId::new(), CallerId::Play, admit(patch_of(vec![ entity("rhythm-road", "The Rhythm Road", EntityKind::Place), @@ -6793,8 +6783,8 @@ mod tests { let mut reopened = WorldKernel::open(&path, world_id).unwrap(); assert_eq!(reopened.snapshot().unwrap(), committed); assert!(matches!( - reopened.submit(envelope, &AuthenticatedCaller::verified_play()).unwrap(), - SubmitReceipt::AlreadyApplied(_) + reopened.submit(envelope, &AuthenticatedCaller::verified_play()), + Err(KernelError::RevisionMismatch { .. }) )); } @@ -6831,7 +6821,7 @@ mod tests { .0; assert_ne!(admitted, genesis_human); - let command_id = CommandId::new(); + let command_id = CommandId::issue(); let first = resolve_patch(&kernel.state, command_id, &patch).unwrap(); let second = resolve_patch(&kernel.state, command_id, &patch).unwrap(); assert_eq!(first, second); @@ -6846,29 +6836,26 @@ mod tests { let path = directory.path().join("world.cc"); let (mut kernel, _) = WorldKernel::create( &path, - creation(CommandId::new(), "Kharad"), + creation("Kharad"), &auth_principal(owner()), ) .unwrap(); let before = kernel.snapshot().unwrap(); - let command_id = CommandId::new(); let handle = DraftHandle::new("rhythm-authority"); + let envelope = command( + &before, + CallerId::Play, + admit(patch_of(vec![institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("kharad-rhythm-road"))), + )])), + ); + let command_id = envelope.id(); let error = kernel - .submit( - command( - &before, - command_id, - CallerId::Play, - admit(patch_of(vec![institution( - &kernel, - "rhythm-authority", - "The Rhythm Authority", - Some(Ref::Draft(DraftHandle::new("kharad-rhythm-road"))), - )])), - ), - &AuthenticatedCaller::verified_play(), - ) + .submit(envelope, &AuthenticatedCaller::verified_play()) .unwrap_err(); assert!(matches!(error, KernelError::PatchRejected(_))); @@ -6920,12 +6907,12 @@ mod tests { let directory = tempfile::tempdir().unwrap(); let (kernel, _) = WorldKernel::create( &directory.path().join("world.cc"), - creation(CommandId::new(), "DeriveId"), + creation("DeriveId"), &auth_principal(owner()), ) .unwrap(); let world_id = kernel.state.world_id; - let command_id = CommandId::new(); + let command_id = CommandId::issue(); let handle = DraftHandle::new("a-handle"); assert_ne!( derive_id(SUBJECT_NAMESPACE, world_id, command_id, &handle, None), @@ -6968,7 +6955,7 @@ mod tests { Some(Ref::Draft(DraftHandle::new("rhythm-road"))), ), ]); - let resolved = resolve_patch(&kernel.state, CommandId::new(), &patch).unwrap(); + let resolved = resolve_patch(&kernel.state, CommandId::issue(), &patch).unwrap(); let honest = super::super::WorldEffect::PatchAdmitted { resolved: resolved.clone(), }; @@ -7036,7 +7023,6 @@ mod tests { .submit( command( &before, - CommandId::new(), CallerId::Play, admit(patch_of(vec![ entity("hollow", "The Hollow", EntityKind::Place), @@ -7088,7 +7074,6 @@ mod tests { .submit( command( &active, - CommandId::new(), CallerId::Play, admit(operations_of(vec![ComponentOp::Relocate { subject: Ref::Existing(unplaced), @@ -7109,7 +7094,6 @@ mod tests { .submit( command( &active, - CommandId::new(), CallerId::Play, admit(operations_of(vec![ ComponentOp::OpenRoute {