From 2b442f9e3e53b3f56c4731309693d50755fa2337 Mon Sep 17 00:00:00 2001 From: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 Date: Fri, 31 Jul 2026 11:51:56 -0400 Subject: [PATCH] fix(desktop): rerun full reconcile on Unready retry and extract enforce_decision_pass seam MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix 1 (BLOCKING): the flush loop's Unready arm previously called run_boot_barrier (barrier-only), which certifies Ready without running reconcile. If a prior reconcile leg failed — leaving the scope Unready — the barrier-only retry would strand that leg's disk edits for the session (fail-forever). Fix: replace run_boot_barrier with claim_in_progress → spawn_event_sync_with_held_claim, which runs the full reconcile+barrier sequence. run_boot_barrier is removed (now dead); test: reconcile_failure_retry_with_full_transition_certifies_and_enqueues. Fix 2 (IMPORTANT): test (j)'s stale-barrier enforcement seam was a mirrored conditional — it replicated if stale_claim.is_current() manually rather than driving the production guard. Deleting is_current() from config_barrier.rs left the test green. Extract enforce_decision_pass(claim, conn, owner_pubkey, states) from run_boot_barrier_for_scope Phase 4; drive test (j) through it. Now removing is_current() from enforce_decision_pass fails the test. Fix 3 (MINOR): correct the rationale comment in import_identity. The prior comment claimed the scope database does not change on key swap; scoped_retention_db_path hashes the owner pubkey so it does. Update to explain why skipping migrate_legacy_retention_into is still defensible (stranded legacy row adopted on the next boot's apply_workspace; consequence bounded to the import session). Co-authored-by: Will Pfleger Signed-off-by: Will Pfleger --- desktop/src-tauri/src/commands/identity.rs | 9 +- desktop/src-tauri/src/event_sync_tests.rs | 82 +++++++++++++++++++ .../src/managed_agents/config_barrier.rs | 62 ++++++-------- .../managed_agents/config_sync_readiness.rs | 10 ++- .../src/managed_agents/persona_events.rs | 54 ++++++++---- .../persona_events/flush_barrier_tests.rs | 61 ++++++++------ 6 files changed, 195 insertions(+), 83 deletions(-) diff --git a/desktop/src-tauri/src/commands/identity.rs b/desktop/src-tauri/src/commands/identity.rs index ab7230614b..e70bf560a6 100644 --- a/desktop/src-tauri/src/commands/identity.rs +++ b/desktop/src-tauri/src/commands/identity.rs @@ -380,9 +380,12 @@ pub async fn import_identity( // OLD owner's scope, and the new owner's scope was never certified. // // Mirrors `apply_workspace`'s force-claim sequence. The legacy- - // migration step is skipped here — only the keys changed, not the - // relay or scope database, so there is nothing to adopt from a - // pre-scoping global store. + // migration step is skipped here: a stranded legacy row for the + // imported identity will be adopted by the next boot's `apply_workspace` + // (consequence bounded to this import session). The scope database DOES + // change on key swap — `scoped_retention_db_path` hashes the owner + // pubkey — so the reconcile below is necessary to queue the new + // owner's disk projections for the new scope. { match crate::managed_agents::retention::active_retention_scope( &app_handle, diff --git a/desktop/src-tauri/src/event_sync_tests.rs b/desktop/src-tauri/src/event_sync_tests.rs index f7e0d88d13..4253bea115 100644 --- a/desktop/src-tauri/src/event_sync_tests.rs +++ b/desktop/src-tauri/src/event_sync_tests.rs @@ -299,3 +299,85 @@ fn migrate_teams_supersedes_future_dated_head() { assert_eq!(row.created_at, future + 1); assert!(row.pending_sync); } + +// ── Reconcile-retry: full transition reaches pending row and certifies Ready ── +// +// Pass-3 Fix 1 coverage: the flush loop's `Unready` arm now spawns the full +// reconcile+barrier transition (not barrier-only). This test verifies the +// invariant the fix must hold: +// +// reconcile leg fails → scope stays `Unready` (claim dropped via RAII) +// retry → claim → reconcile runs → disk edit reaches a pending row +// → claim.complete → scope is `Ready` +// +// The test does not call `flush_active_pending_events` (needs AppHandle), but +// exercises the same building-blocks in sequence: +// `claim_in_progress` → `migrate_personas_in_dir` → `claim.complete` +// This is the exact sequence that `spawn_event_sync_with_held_claim` runs +// (modulo the async wrapper), so the test validates the component contract. +// +// Concretely: a persona's disk edit must not be lost when reconcile fails on +// the first attempt. The barrier-only retry path that preceded this fix would +// certify `Ready` without re-queueing the edit, stranding it for the session. +#[test] +fn test_reconcile_failure_retry_with_full_transition_certifies_and_enqueues() { + use crate::managed_agents::{ + config_sync_readiness::{self, ReadinessState}, + retention::{get_retained_event, open_retention_db}, + }; + use buzz_core_pkg::kind::KIND_PERSONA; + + config_sync_readiness::mark_unready(); + + let keys = nostr::Keys::generate(); + let pubkey = keys.public_key().to_hex(); + let base = tempfile::tempdir().unwrap(); + let db_path = base.path().join("retention.db"); + write_base_personas(base.path(), &one_persona()); + + // Step 1: first attempt — claim InProgress, reconcile "fails" (claim dropped + // via RAII before complete). Scope returns to Unready. + { + let claim = config_sync_readiness::claim_in_progress().expect("must claim from Unready"); + // Simulated reconcile failure: drop without calling complete(). + drop(claim); + } + assert_eq!( + config_sync_readiness::readiness_state(), + Some(ReadinessState::Unready), + "dropped claim (reconcile failure) must leave scope Unready" + ); + + // Step 2: retry — claim again, run the full reconcile, complete the claim. + // This is what the fixed flush-loop Unready arm now spawns. + { + let claim = config_sync_readiness::claim_in_progress() + .expect("Unready scope must allow a retry claim"); + + // Full reconcile (personas leg) — the disk edit is now queued. + let migrated = migrate_personas_in_dir_at(base.path(), &keys, &db_path).expect("reconcile"); + assert_eq!(migrated, 1, "reconcile must queue the disk persona"); + + // Barrier phase (simulated: no relay in this unit test). In production + // this is `run_boot_barrier_after_claim`; here we just certify Ready + // to prove the claim path is wired correctly. + claim.complete(db_path.clone()); + } + + // Step 3: scope must be Ready and the disk edit must be pending. + assert!( + config_sync_readiness::is_ready_for(&db_path), + "retry claim.complete must transition scope to Ready" + ); + + let conn = open_retention_db(&db_path).expect("open db"); + let row = get_retained_event(&conn, KIND_PERSONA, &pubkey, "code-reviewer") + .expect("db query") + .expect("row must exist after reconcile"); + assert!( + row.pending_sync, + "disk edit must be pending after successful reconcile on retry" + ); + + config_sync_readiness::mark_unready(); // cleanup +} diff --git a/desktop/src-tauri/src/managed_agents/config_barrier.rs b/desktop/src-tauri/src/managed_agents/config_barrier.rs index 7796850376..ac6cd1f58e 100644 --- a/desktop/src-tauri/src/managed_agents/config_barrier.rs +++ b/desktop/src-tauri/src/managed_agents/config_barrier.rs @@ -45,33 +45,6 @@ use super::{ use crate::app_state::AppState; use buzz_core_pkg::kind::{KIND_MANAGED_AGENT, KIND_PERSONA, KIND_TEAM}; -/// Run the boot barrier for the active scope. -/// -/// Attempts to claim the `Unready → InProgress` transition. If another -/// caller already owns it (state is `InProgress` or `Ready`), this returns -/// immediately — the in-flight or completed barrier is sufficient. -/// -/// On success, marks the scope `Ready`, allowing the flush loop to publish -/// for that scope. On any error, resets to `Unready` so the scope stays -/// fail-closed until a later retry succeeds. -/// -/// Called from the flush loop (retry path, only when `Unready`). The -/// `claim_in_progress` CAS ensures at most one barrier runs at a time. -/// `spawn_event_sync` calls [`run_boot_barrier_after_claim`] instead, which -/// assumes the caller already holds `InProgress` and skips the CAS. -pub async fn run_boot_barrier(app: &tauri::AppHandle) { - use super::config_sync_readiness; - - // Single-flight: only the first caller to claim InProgress runs the - // barrier. If the state is already InProgress (spawn_event_sync's - // reconcile is in-flight) or Ready, skip. - let Some(claim) = config_sync_readiness::claim_in_progress() else { - return; - }; - - run_boot_barrier_enforcing(app, claim).await; -} - /// Execute the barrier enforcement assuming the caller already claimed /// `InProgress`. /// @@ -91,8 +64,8 @@ pub(crate) async fn run_boot_barrier_after_claim( } /// Outcome of a single barrier scope run. -#[derive(Debug)] -enum BarrierOutcome { +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum BarrierOutcome { /// Decision pass completed; scope is ready for publication. Success, /// Workspace switched mid-flight; the old scope's barrier was abandoned. @@ -277,11 +250,30 @@ async fn run_boot_barrier_for_scope( // Phase 4 — generation-gate the enforcement phase. // - // A preempted barrier that has stale relay evidence (e.g. it observed - // `HeadState::Absent` for a coordinate the current barrier just parked) - // must not overwrite the current barrier's gate decisions. The check runs - // while `managed_agents_store_lock` is held, so the generation cannot - // change between this check and the `run_decision_pass` write below. + // `enforce_decision_pass` checks `claim.is_current()` while + // `managed_agents_store_lock` is held (i.e., right here), so the + // generation cannot change between the check and the `run_decision_pass` + // write below. A preempted barrier returns `Abandoned` without writing. + enforce_decision_pass(claim, &conn, &owner_pubkey, &states) +} + +/// Generation-gated enforcement phase: check claim currency, write gate +/// decisions, return outcome. +/// +/// Extracted from [`run_boot_barrier_for_scope`] as a named seam so tests can +/// drive the enforcement phase directly and prove that removing the +/// `is_current()` guard causes them to fail. Without this seam, a test of +/// the guard can only mirror the `if stale_claim.is_current()` conditional +/// manually — which stays green even when the production guard is removed. +/// +/// Caller must hold `managed_agents_store_lock` around this call so the +/// generation cannot change between the currency check and the write. +pub(crate) fn enforce_decision_pass( + claim: &super::config_sync_readiness::ReadinessClaim, + conn: &rusqlite::Connection, + owner_pubkey: &str, + states: &[super::config_sync::CoordinateState], +) -> Result { if !claim.is_current() { tracing::info!( target: "buzz::config_sync", @@ -290,7 +282,7 @@ async fn run_boot_barrier_for_scope( return Ok(BarrierOutcome::Abandoned); } - run_decision_pass(&conn, &owner_pubkey, &states)?; + run_decision_pass(conn, owner_pubkey, states)?; Ok(BarrierOutcome::Success) } diff --git a/desktop/src-tauri/src/managed_agents/config_sync_readiness.rs b/desktop/src-tauri/src/managed_agents/config_sync_readiness.rs index 5771fa09fa..50d54bb066 100644 --- a/desktop/src-tauri/src/managed_agents/config_sync_readiness.rs +++ b/desktop/src-tauri/src/managed_agents/config_sync_readiness.rs @@ -10,8 +10,8 @@ //! ```text //! apply_workspace (force) ─────────────────────────► InProgress (from any state) //! flush retry (claim, only when Unready) ───────────► InProgress -//! run_boot_barrier success ─────────────────────────► Ready(db_path) -//! run_boot_barrier error / abandon ─────────────────► Unready (if still current gen) +//! boot barrier success ─────────────────────────────► Ready(db_path) +//! boot barrier error / abandon ─────────────────────► Unready (if still current gen) //! flush: InProgress → skip tick; Ready(p) → publish //! ``` //! @@ -44,7 +44,10 @@ //! - Leg 2 (stale drop destroys InProgress): stale claim's `Drop` sees a //! generation mismatch → no-op → force-claim's `InProgress` is preserved. -use std::path::{Path, PathBuf}; +use std::path::PathBuf; + +#[cfg(test)] +use std::path::Path; /// The current readiness state for the active scope's publication gate. #[derive(Debug, Clone, PartialEq, Eq)] @@ -211,6 +214,7 @@ pub fn mark_unready() { } /// `true` iff the scope is `Ready` for exactly `db_path`. +#[cfg(test)] pub fn is_ready_for(db_path: &Path) -> bool { with_lock(|latch| matches!(&latch.state, ReadinessState::Ready(p) if p == db_path)) .unwrap_or(false) diff --git a/desktop/src-tauri/src/managed_agents/persona_events.rs b/desktop/src-tauri/src/managed_agents/persona_events.rs index c0716f83a8..7d1cf0ccc2 100644 --- a/desktop/src-tauri/src/managed_agents/persona_events.rs +++ b/desktop/src-tauri/src/managed_agents/persona_events.rs @@ -247,9 +247,15 @@ pub async fn flush_pending_events( /// /// - `Ready(path)` matching the active scope → flush proceeds. /// - `InProgress` → a reconcile+barrier is in-flight; skip this tick. -/// - `Unready` → no barrier has claimed the slot; run the barrier inline -/// (which will claim `InProgress`, run, and set `Ready` or `Unready`). -/// A barrier failure skips this tick; the next tick retries. +/// - `Unready` → no barrier has claimed the slot; attempt to claim and spawn +/// the full reconcile+barrier transition (`run_event_sync` + barrier), +/// then skip this tick. The spawned task transitions to `Ready` or +/// `Unready`; the next tick retries. +/// +/// Running the FULL transition on `Unready` (not barrier-only) is load-bearing: +/// if a previous reconcile leg failed the scope is left `Unready`, and +/// certifying `Ready` via a barrier-only pass would skip the failed leg's disk +/// edits entirely — a fail-forever loss for those coordinates this session. pub async fn flush_active_pending_events( app: &tauri::AppHandle, state: &AppState, @@ -273,19 +279,37 @@ pub async fn flush_active_pending_events( return Ok(0); } _ => { - // Unready (or None if lock poisoned). Run the barrier inline; - // claim_in_progress inside run_boot_barrier is the CAS guard. - crate::managed_agents::config_barrier::run_boot_barrier(app).await; - - // Re-check after the barrier attempt. - if !config_sync_readiness::is_ready_for(&scope.db_path) { - tracing::info!( - target: "buzz::config_sync", - db_path = %scope.db_path.display(), - "flush skipped: boot barrier has not completed for this scope" - ); - return Ok(0); + // Unready (or None if lock poisoned). Attempt to claim and spawn + // the FULL reconcile+barrier transition. A barrier-only retry is + // insufficient: if reconcile failed on the prior attempt, only + // the full transition re-queues the failed leg's disk edits. + // `claim_in_progress` is the CAS guard — if another caller raced + // us to the claim, the spawned task already covers this tick. + match config_sync_readiness::claim_in_progress() { + Some(claim) => { + crate::event_sync::spawn_event_sync_with_held_claim( + app.clone(), + scope.owner_keys, + scope.db_path.clone(), + claim, + ); + } + None => { + // Raced to InProgress by another caller; that task covers this. + tracing::debug!( + target: "buzz::config_sync", + db_path = %scope.db_path.display(), + "flush: claim lost to concurrent caller; skipping this tick" + ); + } } + + tracing::info!( + target: "buzz::config_sync", + db_path = %scope.db_path.display(), + "flush skipped: boot reconcile+barrier spawned for this scope" + ); + return Ok(0); } } diff --git a/desktop/src-tauri/src/managed_agents/persona_events/flush_barrier_tests.rs b/desktop/src-tauri/src/managed_agents/persona_events/flush_barrier_tests.rs index b342deb027..f20e639d2e 100644 --- a/desktop/src-tauri/src/managed_agents/persona_events/flush_barrier_tests.rs +++ b/desktop/src-tauri/src/managed_agents/persona_events/flush_barrier_tests.rs @@ -451,28 +451,32 @@ async fn test_apply_workspace_flush_cannot_interleave_before_reconcile() { // test (i) only verified that `complete()` is a no-op; it never drove a // stale barrier all the way through enforcement. // -// This test exercises the enforcement seam directly: stale barrier S builds a +// This test drives the enforcement seam directly: stale barrier S builds a // `CoordinateState` from stale relay evidence (the exact CRITICAL cell — // `HeadState::Absent` sees cell-3 `PublishLocalEdit`, opening a gate the -// current barrier parked) and calls `run_decision_pass` while gated by the -// `is_current()` check. The generation guard must block the write. +// current barrier parked) and calls `enforce_decision_pass` — the same +// function `run_boot_barrier_for_scope` calls at Phase 4 (under the store +// lock). Because the test drives the production helper rather than mirroring +// the guard manually, removing the `is_current()` check from +// `enforce_decision_pass` causes this test to fail. // // Deterministic sequence: // 1. Flush wins claim (gen 0). Its barrier observes `HeadState::Absent` for // the coordinate — stale evidence that would decide `PublishLocalEdit`. // 2. apply_workspace force-claims (gen 1). The current barrier observes // `HeadState::Present` and decides `Park(NoBaselineWithHead)`. -// 3. Current barrier (gen 1) runs `run_decision_pass` → sets +// 3. Current barrier (gen 1) runs `enforce_decision_pass` → sets // `publish_blocked = true`. Certifies Ready(path). // 4. Stale barrier (gen 0) resumes enforcement with its stale evidence. -// Before calling `run_decision_pass`, the generation guard (`is_current()`) -// returns false — write is blocked. `publish_blocked` must remain `true`. +// Calls `enforce_decision_pass` → `is_current()` returns false → write +// is blocked. `publish_blocked` must remain `true`. // 5. Vacuity proof: without the guard, the stale pass WOULD clear the flag // (verified on a scratch db so the real store is never mutated by the test). #[test] fn test_stale_barriers_decision_pass_cannot_alter_publish_blocked() { use crate::managed_agents::{ canonical_projection::CanonicalProjection, + config_barrier::{enforce_decision_pass, BarrierOutcome}, config_sync::{local_state, plan, run_decision_pass, CoordinateState}, decision::{Decision, Head, HeadState, TombstoneEvidence}, head_lookup::Coordinate, @@ -554,8 +558,9 @@ fn test_stale_barriers_decision_pass_cannot_alter_publish_blocked() { let force_claim = config_sync_readiness::force_claim_in_progress(); assert_eq!(config_sync_readiness::current_generation(), 1); - // Step 3: current barrier (gen 1) runs its pass — Present head + no baseline - // → Park(NoBaselineWithHead) → publish_blocked = true. Certifies Ready. + // Step 3: current barrier (gen 1) runs its pass via enforce_decision_pass + // — Present head + no baseline → Park(NoBaselineWithHead) → publish_blocked = true. + // Certifies Ready. { let current_observation = { let conn = open_retention_db(&db_path).expect("open db for current observation"); @@ -577,7 +582,8 @@ fn test_stale_barriers_decision_pass_cannot_alter_publish_blocked() { .unwrap() }; let current_conn = open_retention_db(&db_path).expect("open db for current pass"); - run_decision_pass( + let outcome = enforce_decision_pass( + &force_claim, ¤t_conn, &pubkey, &[CoordinateState { @@ -586,6 +592,11 @@ fn test_stale_barriers_decision_pass_cannot_alter_publish_blocked() { }], ) .expect("current barrier enforces"); + assert_eq!( + outcome, + BarrierOutcome::Success, + "current claim must succeed" + ); } assert!( is_publish_blocked( @@ -600,24 +611,20 @@ fn test_stale_barriers_decision_pass_cannot_alter_publish_blocked() { force_claim.complete(db_path.clone()); assert!(config_sync_readiness::is_ready_for(&db_path)); - // Step 4: stale barrier (gen 0) resumes enforcement. + // Step 4: stale barrier (gen 0) resumes enforcement via enforce_decision_pass. // - // The enforcement seam: `run_boot_barrier_for_scope` calls `claim.is_current()` - // while holding `managed_agents_store_lock`, and returns `Abandoned` without - // calling `run_decision_pass` when it returns false. - // - // We reproduce that guard here: `is_current()` must return false. - assert!( - !stale_claim.is_current(), - "stale claim (gen 0) must not be current after force_claim bumped to gen 1" - ); - - // Enforcement seam: the stale barrier only calls run_decision_pass if - // is_current() returns true. Since it doesn't, the write is blocked. - // This is the invariant the production guard enforces. - if stale_claim.is_current() { - let conn = open_retention_db(&db_path).expect("open db for stale enforcement"); - run_decision_pass(&conn, &pubkey, &stale_states).expect("stale pass"); + // This drives the PRODUCTION helper — not a manual mirror of is_current(). + // Deleting the is_current() guard from enforce_decision_pass causes this test + // to fail: the stale pass clears publish_blocked, and the assert below fires. + { + let stale_conn = open_retention_db(&db_path).expect("open db for stale enforcement"); + let outcome = enforce_decision_pass(&stale_claim, &stale_conn, &pubkey, &stale_states) + .expect("enforce returns Ok even on Abandoned"); + assert_eq!( + outcome, + BarrierOutcome::Abandoned, + "stale claim (gen 0) must be Abandoned by enforce_decision_pass" + ); } // Vacuity companion: confirm the stale pass WOULD have cleared the flag @@ -659,7 +666,7 @@ fn test_stale_barriers_decision_pass_cannot_alter_publish_blocked() { d_tag, ) .unwrap(), - "publish_blocked must remain true: stale barrier's run_decision_pass was blocked by the generation guard" + "publish_blocked must remain true: stale barrier's enforce_decision_pass returned Abandoned" ); // Stale claim drops (gen mismatch → latch no-op; force-claim already certified Ready).