From 3be224385c0e8aaef376687c8687287a44c1a1c7 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Tue, 10 Nov 2026 18:12:22 -0600 Subject: [PATCH 1/2] feat(id): persist server-config provisioning into live serving state (#5119 slice 3) Provisioned::from_parts builds provisioning from a journaled Directory plus the serve groups log events; GroupLog::record_preformed seeds already-formed events by ID (skip if held). serve starts the config via start_server_config_persisted: accounts journal beside the groups log, group events into the groups log itself, so a restart loads them back and reports zero creations. Tests: record_preformed seeds-once-then-skips; persisted start survives a restart. --- pkgs/id/src/commands/serve.rs | 91 +++++++++++++++++++++++++- pkgs/id/src/groups/log.rs | 58 ++++++++++++++++ pkgs/id/src/server_config/provision.rs | 14 ++++ 3 files changed, 162 insertions(+), 1 deletion(-) diff --git a/pkgs/id/src/commands/serve.rs b/pkgs/id/src/commands/serve.rs index 13e4d417fd..d9d0d713c3 100644 --- a/pkgs/id/src/commands/serve.rs +++ b/pkgs/id/src/commands/serve.rs @@ -1068,6 +1068,51 @@ pub fn start_server_config(path: &Path) -> Result { }) } +/// The directory journal the server config provisioning persists +/// its accounts in (#5119 slice 3): `directory.jsonl` beside the +/// groups log, the same layout a world directory uses. +#[cfg(feature = "world")] +fn server_config_directory_path(groups_log: &Path) -> PathBuf { + groups_log.with_file_name("directory.jsonl") +} + +/// Load the operator server config at `path` and run startup +/// provisioning into the live serving state (#5119 slice 3): the +/// provisioned accounts go into the journaled directory beside the +/// groups log and the preformed group events into the groups log +/// itself — the same state live serving folds and replays — so a +/// restart loads them back, provisioning skips them, and the report +/// names no new creations. +/// +/// # Errors +/// +/// Fails on the same startup contract as [`start_server_config`], +/// and when the persisted directory or groups log cannot be opened +/// or written. +#[cfg(feature = "world")] +pub fn start_server_config_persisted( + path: &Path, + groups_log: &Path, +) -> Result { + let config = crate::server_config::ServerConfig::load(path) + .map_err(|error| anyhow::anyhow!("server config {}: {error}", path.display()))?; + let directory = crate::directory::Directory::open(&server_config_directory_path(groups_log))?; + let mut log = crate::groups::log::GroupLog::open(groups_log)?; + let mut provisioned = + crate::server_config::Provisioned::from_parts(directory, log.events().to_vec()); + let report = provisioned + .apply(&config) + .map_err(|error| anyhow::anyhow!("server config {}: {error}", path.display()))?; + for event in provisioned.events() { + log.record_preformed(event)?; + } + Ok(StartedServerConfig { + config, + provisioned, + report, + }) +} + /// The pull policy the live event-sync gate serves under (#5119): the server /// config's `[policy] pull_policy` when a config was loaded, else the code /// default ([`crate::pull_policy::PullPolicy::Open`]), so a `serve` without @@ -1193,7 +1238,7 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { #[cfg(feature = "world")] let started_server_config = match &server_config { Some(path) => { - let started = start_server_config(path)?; + let started = start_server_config_persisted(path, &groups_log)?; status!( "server config: loaded {} (provisioned {} user(s), {} group(s), {} member(s))", path.display(), @@ -3515,6 +3560,50 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[cfg(feature = "world")] + #[test] + fn start_server_config_persisted_survives_a_restart() { + let dir = serve_config_dir("persisted"); + let path = dir.join("server.toml"); + let groups_log = dir.join("groups.jsonl"); + // Real Ed25519 public keys, as in + // start_server_config_applies_provisioning. + let id = |n: u8| { + ed25519_dalek::SigningKey::from_bytes(&[n; 32]) + .verifying_key() + .to_bytes() + .iter() + .map(|b| format!("{b:02x}")) + .collect::() + }; + std::fs::write( + &path, + format!( + "[[users]]\nkey = \"ann\"\nid = \"{}\"\n\n[[users]]\nkey = \"bo\"\nid = \"{}\"\n\n\ + [[groups]]\nkey = \"team\"\nname = \"Team\"\ncreator = \"ann\"\n\n\ + [[groups.members]]\nuser = \"bo\"\nrole = \"write\"\n", + id(1), + id(2) + ), + ) + .unwrap(); + let started = start_server_config_persisted(&path, &groups_log).unwrap(); + assert_eq!(started.report.users_created, 2); + assert_eq!(started.report.groups_created, 1); + assert_eq!(started.report.members_added, 1); + drop(started); + // A restart over the same persisted state loads the accounts + // and group events back and creates nothing: no recreations, + // no new-creation reports (#5119 slice 3 acceptance). + let restarted = start_server_config_persisted(&path, &groups_log).unwrap(); + assert_eq!(restarted.report, crate::server_config::Report::default()); + assert!(restarted.provisioned.directory().account(&id(1)).is_some()); + assert!(restarted.provisioned.directory().account(&id(2)).is_some()); + // The create event plus the one member add. + assert_eq!(restarted.provisioned.events().len(), 2); + let _ = std::fs::remove_dir_all(&dir); + } + #[cfg(feature = "world")] #[test] fn start_server_config_fails_startup_on_a_malformed_file() { diff --git a/pkgs/id/src/groups/log.rs b/pkgs/id/src/groups/log.rs index 76c2cc28ab..0df7d5ec52 100644 --- a/pkgs/id/src/groups/log.rs +++ b/pkgs/id/src/groups/log.rs @@ -147,6 +147,34 @@ impl GroupLog { Ok(Recorded { event: id, outcome }) } + /// Records an event that was already formed elsewhere, keeping its + /// ID and its place in its own chain: the seeding path for events a + /// config provisioned (#5119 slice 3). An event whose ID the log + /// already holds is skipped and changes nothing, so seeding the + /// same events on every start is a no-op after the first. + /// + /// # Errors + /// + /// Fails if the events cannot be folded, or the file cannot be + /// written. Nothing is written when the fold fails. + pub fn record_preformed(&mut self, event: &Event) -> Result> { + if self.events.iter().any(|held| held.id == event.id) { + return Ok(None); + } + let mut next = self.events.clone(); + next.push(event.clone()); + let outcome = fold(&next)? + .outcome(&event.id) + .cloned() + .context("the fold did not decide the event")?; + self.append(event)?; + self.events = next; + Ok(Some(Recorded { + event: event.id, + outcome, + })) + } + /// The IDs no event names in its `after`. A new event names these, so it comes after all of them. fn heads(&self) -> Vec { let named: BTreeSet = self @@ -376,6 +404,36 @@ mod tests { }) } + #[test] + fn test_record_preformed_seeds_once_and_then_skips() { + let dir = TempDir::new().unwrap(); + let path = dir.path().join(FILE_NAME); + // Form the event in a scratch log, as provisioning forms it + // away from the log it will seed. + let scratch = dir.path().join("scratch.jsonl"); + let mut formed = GroupLog::open(&scratch).unwrap(); + let recorded = formed.record(OWNER, None, create_body()).unwrap(); + let event = formed.events()[0].clone(); + + let mut log = GroupLog::open(&path).unwrap(); + let seeded = log.record_preformed(&event).unwrap().unwrap(); + assert_eq!(seeded.event, recorded.event); + assert_eq!(seeded.outcome, Outcome::Applied); + // Seeding the same event again changes nothing. + assert!(log.record_preformed(&event).unwrap().is_none()); + assert_eq!(log.events().len(), 1); + // And the seeded event is what a reopen reads back. + let reopened = GroupLog::open(&path).unwrap(); + assert_eq!(reopened.events(), log.events()); + assert!( + reopened + .projection() + .unwrap() + .group(&recorded.event) + .is_some() + ); + } + #[test] fn test_a_recorded_event_is_read_back_and_folds_the_same() { let dir = TempDir::new().unwrap(); diff --git a/pkgs/id/src/server_config/provision.rs b/pkgs/id/src/server_config/provision.rs index e3f005a502..092c9b833e 100644 --- a/pkgs/id/src/server_config/provision.rs +++ b/pkgs/id/src/server_config/provision.rs @@ -90,6 +90,20 @@ impl Provisioned { } } + /// Starts from state a previous run persisted: the accounts in + /// `directory` and the group `events` already recorded (#5119 + /// slice 3). [`Provisioned::apply`] skips what already exists, so + /// a restart over the same persisted state creates nothing and + /// reports nothing. + #[must_use] + pub fn from_parts(directory: Directory, events: Vec) -> Self { + Self { + directory, + events, + create: CreateRule::Anyone, + } + } + /// The accounts. #[must_use] pub const fn directory(&self) -> &Directory { From 19b2f4408e6e41f58054fe0242f4c2012f9e467d Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Tue, 10 Nov 2026 18:29:18 -0600 Subject: [PATCH 2/2] fix(id): resume interrupted provisioning batches; seed only new events (#5119 slice 3, Codex P2s) Provisioned::apply now completes a partially recorded group with exactly its missing events instead of skipping on the create ID, so a crash mid-group no longer leaves memberships permanently missing (an admin-removed member is not resurrected: its add event is still recorded, hence not missing). start_server_config_persisted seeds only the suffix this start added, so a restart no longer rescans the whole groups log. New test: test_an_interrupted_group_is_completed_by_the_next_apply. --- pkgs/id/src/commands/serve.rs | 16 ++++++-- pkgs/id/src/server_config/provision.rs | 52 +++++++++++++++++++++----- 2 files changed, 54 insertions(+), 14 deletions(-) diff --git a/pkgs/id/src/commands/serve.rs b/pkgs/id/src/commands/serve.rs index d9d0d713c3..3416304ad9 100644 --- a/pkgs/id/src/commands/serve.rs +++ b/pkgs/id/src/commands/serve.rs @@ -1098,12 +1098,16 @@ pub fn start_server_config_persisted( .map_err(|error| anyhow::anyhow!("server config {}: {error}", path.display()))?; let directory = crate::directory::Directory::open(&server_config_directory_path(groups_log))?; let mut log = crate::groups::log::GroupLog::open(groups_log)?; + let already = log.events().len(); let mut provisioned = crate::server_config::Provisioned::from_parts(directory, log.events().to_vec()); let report = provisioned .apply(&config) .map_err(|error| anyhow::anyhow!("server config {}: {error}", path.display()))?; - for event in provisioned.events() { + // Seed only the events this start added: the rest are the + // from_parts state itself, and re-checking them on every + // restart would rescan the whole log history. + for event in &provisioned.events()[already..] { log.record_preformed(event)?; } Ok(StartedServerConfig { @@ -1536,9 +1540,13 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { // The world protocol instance is shared between its ALPN registration and // the meta protocol, which exposes its abuse counters (#4918). #[cfg(feature = "world")] - let world_protocol = world_hub - .as_ref() - .map(|hub| world_protocol_for(hub.clone(), *node_id.as_bytes(), started_server_config.as_ref())); + let world_protocol = world_hub.as_ref().map(|hub| { + world_protocol_for( + hub.clone(), + *node_id.as_bytes(), + started_server_config.as_ref(), + ) + }); #[cfg(feature = "world")] let abuse_handle = world_protocol diff --git a/pkgs/id/src/server_config/provision.rs b/pkgs/id/src/server_config/provision.rs index 092c9b833e..cdef4792f0 100644 --- a/pkgs/id/src/server_config/provision.rs +++ b/pkgs/id/src/server_config/provision.rs @@ -148,7 +148,9 @@ impl Provisioned { } /// Creates the accounts and groups the config names, and adds their members. What already - /// exists is skipped, so a second run of the same config changes nothing. + /// exists is skipped, so a second run of the same config changes nothing. A group recorded + /// only in part (an earlier run stopped mid-group) is completed with exactly its missing + /// events, so interrupted provisioning resumes instead of succeeding over a half-made group. /// /// # Errors /// @@ -173,23 +175,30 @@ impl Provisioned { report.users_created += 1; } for group in config.groups() { - if self.events.iter().any(|event| event.id == group.id) { + let batch = group_events(group); + let missing: Vec = batch + .iter() + .filter(|event| !self.events.iter().any(|held| held.id == event.id)) + .cloned() + .collect(); + if missing.is_empty() { continue; } - if !config - .create_rule() - .allows(&group.creator, &self.projection()?) + let creates = missing.iter().any(|event| event.id == group.id); + if creates + && !config + .create_rule() + .allows(&group.creator, &self.projection()?) { return Err(ProvisionError::NotAllowed { group: group.key.clone(), creator: hex_encode(&group.creator), }); } - let batch = group_events(group); let mut next = self.events.clone(); - next.extend(batch.iter().cloned()); + next.extend(missing.iter().cloned()); let projection = fold(&next)?; - for event in &batch { + for event in &missing { if let Some(Outcome::Refused(refusal)) = projection.outcome(&event.id) { return Err(ProvisionError::Refused { group: group.key.clone(), @@ -198,8 +207,10 @@ impl Provisioned { } } self.events = next; - report.groups_created += 1; - report.members_added += group.members.len(); + if creates { + report.groups_created += 1; + } + report.members_added += missing.iter().filter(|event| event.id != group.id).count(); } Ok(report) } @@ -582,6 +593,27 @@ mod tests { } } + #[test] + fn test_an_interrupted_group_is_completed_by_the_next_apply() { + // The first run recorded the create and stopped before the + // member adds: the next apply adds exactly the missing + // events and reports them, without recreating the group. + let text = config(TEAM); + let (state, result) = apply(&text); + result.unwrap(); + let full = state.events().to_vec(); + let mut resumed = Provisioned::from_parts(state.directory().clone(), full[..1].to_vec()); + let parsed = ServerConfig::parse(&text).unwrap(); + let report = resumed.apply(&parsed).unwrap(); + assert_eq!(report.users_created, 0); + assert_eq!(report.groups_created, 0); + assert_eq!(report.members_added, 2); + assert_eq!(resumed.events(), full.as_slice()); + // And a third run is a no-op again. + let again = resumed.apply(&parsed).unwrap(); + assert_eq!(again, Report::default()); + } + #[test] fn test_a_create_recorded_after_the_start_meets_the_create_rule() { // Only ann may create. A create by anyone else that arrives after the start is refused, as