Skip to content

Commit c213d90

Browse files
wesbillmanBrain
andauthored
fix(desktop): bound startup request bursts and recover quota refusals (#7790)
Prepared by Brain on Wes’s behalf. ## Summary Reduce startup request amplification and let quota-refused background work recover without changing relay quotas or bypassing the existing Send gate. - Coalesce nest regeneration into one worker plus the latest pending generation. Keep the stale-write fence; bound the archive read so an old workspace cannot strand newer work. - Claim pending channel subscriptions before awaiting setup; cancel removed/unmounted entries and preserve still-owned subscriptions across reconnect handoff. - Recheck extended cooldown deadlines before retry dispatch; distinguish an explicit zero-second hint from a missing hint. - Recover native finite/unread queries within their original caller deadline and a three-retry budget, preserving verified unique events, complete filters and terminal errors. - Pace renderer initial/live-CLOSED REQs at one per 250ms: visible channel and explicitly interactive TTS/read-state/observer owners first, then live-only auxiliaries, then background history. Publication and finite queries bypass this queue. Reconnect replay now promotes explicit interactive owners alongside the visible channel with stable registration-order ties; its existing capped batches and cooldown remain intact. **Scope at `867495426`:** 39 source/test files, including 15 production files (+665/-235) and 24 test/fixture files. The diagnostic recorder, HTTP instrumentation, trace launcher and raw captures are deliberately excluded. No profile reset, grouping, quota increase or new global scheduler. ## Before / after evidence These are observations from instrumented, human-operated development Tauri/Vite runs against a production relay, plus explicitly identified controlled regressions—not a packaged-release startup benchmark. | Measurement | Before | After | Evidence boundary | | --- | --- | --- | --- | | Archive snapshot requests (kind 13535) | 290 | 3 | Recorder-only baseline → nest-only intermediate candidate; unequal 67.436s / 39.273s captures and hydration differences | | Archive responses: HTTP 200 / 429 | 277 / 13 | 3 / 0 | Same baseline/nest-only captures; not a claim that all quota pressure disappeared | | Successful archive responses’ advertised content-length sum | 21,208,505 bytes | 229,695 bytes | Header values, not actual transferred bytes | | 154-channel StrictMode replay | 308 REQs | 154 REQs | Controlled real React hook → real session → mocked Tauri transport regression | | Add one channel while 154 setups are pending | 309 REQs | 155 REQs | Same production-boundary regression; ordinary mount remains 154 → 154 | | Broad renderer request burst / spacing | 110 broad REQs within 10.766ms in pre-drain capture | 250.061ms minimum / 252.131ms median between broad REQ writes in final longer capture | Different attended runs; pacing rather than a universal request-rate cap | | Native unread query outcomes | Baseline: 8 EOSE / 146 quota CLOSED out of 154 queries | Final longer run: all 156 observed queries reach EOSE; eight refused queries each recover after two refusals | Different runs/workloads; query completion, not badge rendering | ### Timing metrics | Observation | Measured value | | --- | ---: | | Baseline’s two accepted chat EVENT socket writes → positive OK | 173.340ms / 85.556ms | | Nest-only intermediate candidate’s two accepted writes → positive OK | 277.854ms / 78.775ms | | Final candidate, short run, accepted chat writes → positive OK | 80.636ms / 77.506ms | | Final candidate, longer run, accepted chat writes → positive OK | 120.712ms / 86.895ms | | Last initial EOSE among 163 observed broad channel registrations, longer run | 64.550s after trace start | | Last EOSE among 156 observed native unread queries, longer run | 73.972s after trace start | | Native retry waits after 3s then 0s hints, longer run | 3000.7–3002.8ms, then 2001.5–2002.6ms | | Renderer finite-query retry after a 2s hint, longer run | 2061.365ms | Both Sends in each final run were accepted, with no recorded negative OK. Every quota-refused query in the longer run subsequently completed the same query. Its two Sends happened early (17.878s and 21.655s), not near the end. These small samples do not support a percentage latency improvement. **Tradeoffs and limits** - 296 background subscriptions imply about 74s of paced registration before extra cooldowns/high-priority work. The longer capture observed 163 registrations; it did not independently enumerate the expected membership set or record a queue-empty marker. - This is not a global 4-REQ/s cap: finite queries, native requests and reconnect replay are outside the drain and still share relay quota. Quota refusals recover rather than disappear. - Socket-write → OK starts after composer submission and any publisher gate wait. No click-to-visible, launch-to-usable or badge-paint latency is claimed. - Native EOSE is not proof of command return, classification, React state application or visible unread badges. Existing per-channel kinds, since floors, limits, h-less routing, unread lease/scope guard and eight-query concurrency remain intact. - The attended measurements belong to the instrumented candidate, not a fresh release run of this fixes-only commit. At the initial packaging checkpoint (`1bf3d060`), eighteen of twenty files were byte-identical; the other two removed diagnostic gate calls and isolated the nest test’s temporary paths. The subsequent interactive priority/reconnect and readiness fixes have controlled hook/session/browser evidence, not another attended voice/performance run. ### Evidence provenance (captures retained locally, not uploaded) | Capture | SHA-256 | | --- | --- | | Baseline `STARTUP_20260921T194814Z_98811.jsonl` | `f4f0a89ad9aea91084bd6a7432510488166de4cbc906600d88c26d557f380994` | | Nest-only `STARTUP_20260921T202610Z_28642.jsonl` | `ce517b02a3f717c36d96b36bb8616e8fa80b03b12b356bacfd40475925ea3f3e` | | Final short `STARTUP_20260922T013628Z_13506.jsonl` | `bfea6f3cf80cd7b7e4e676632a3df2f16271fade5bfa0edec72b7bcbbe7839ff` | | Final longer `STARTUP_20260922T014637Z_15846.jsonl` | `f4abece613d108c4c2fe3cb808e633a0486bdc9993ca92323822dc00c3fae6ec` | Final instrumented build fingerprint: `b0b4fc27d793c3e643f4e10289b5afdb4620ee2e13a8b33fa0595dd3417fd5ca`. All observed dropped-record counters in these final captures were zero. Source manifests and offline correlation analyses are retained locally; no raw captures, profile data or agent sessions are part of this PR. ## Validation Current head: `86749542657a60abdfe82eed5cc576d3e162fe5d`, based on `77729abfb692b25a0f4ec4a69add86af2e32c0dd`. Review follow-ups: - `8842dbd8`: explicit interactive TTS admission using the existing main-window owner, independent of companion/timeline selection. Real-hook/session/IPC coverage with 296 cold owners proves initial and CLOSED priority, unchanged filters/cooldown/pacing, background progress and deduplicated speech. - `8cb088106`: reconnect preserves interactive priority even with no visible channel. Stable ordering among foreground ties; real hook/session reconnect regressions cover cooldown, capped batching, all 297 owners, deduplication and unmount cancellation. Independent reviewer mutation restored the prior replay implementation, failed both reconnect rows, then passed the restored candidate. - `68e76d7c`: read-state and observer reuse interactive priority. Stop and ModelPicker wait on the existing observer owner inside send callbacks, after installing result listeners/deadlines. No new owner, timer or scheduler; inherited CLOSED/fallback/error semantics remain, rather than a new strict EOSE guarantee. The real Stop panel browser probe holds observer IPC across the click and checks observer-before-control order and correlated outcome. ModelPicker component ordering is source-reviewed only. - Mock live admission now replays matching stored history with per-filter time/limit constraints, deduplication, untagged auxiliary channel fallback and authoritative explicit h-tags. Kind-specific fixture admission waits and retry-resolving hover actions fix startup-dependent test setup without weakening event/badge assertions. - `48e9c0dad` and `867495426`: steady-state scroll-prepend setup observes live admission, subsequent head dispatch, successful/idle query completion and initial bottom geometry. Phase-2 genuine-growth and ≤32px anchor assertions are unchanged. This isolates steady-state prepending: it **does not fix or certify production early-scroll/head-reset behavior**. Current validation: - Normal push hooks at `867495426`: **6,582/6,582 renderer tests**, zero failed/skipped/cancelled; lint/static checks, typecheck and differential file-size gate passed. Native source is unchanged from the earlier checkpoint; no new native run is claimed for these renderer/test follow-ups. - E2E build passed at `48e9c0dad` plus the exact subsequently committed test-only delta (spec blob `469be2eed868c677ba80b859cc871208000fee60`). The completed affected-smoke run passed **153/153** across agent-control, badge, entity links, messaging, profile status and scroll history; the full scroll file additionally passed twice (**36/36**). No full CI-smoke pass is claimed from this six-file local run. - Pinky independently reviewed production and test follow-ups, including the final scroll spec blob `469be2eed868c677ba80b859cc871208000fee60`, with no blocking finding. Review is source evidence, not an independent test run. - **Not merge-ready:** new-head required CI must complete, exact-range security review requires authorization, and GitHub currently reports REVIEW_REQUIRED; fresh exact-head reviewer approval is still needed. No approval, dismissal or merge performed. No new packaged/native audio, launch-to-usable or badge-paint observation is claimed. Initial fixes-only checkpoint validation (`1bf3d06024d284a63326fdd353baced0842aeb81`): - Pre-commit formatting hooks passed; worktree clean. - Renderer package hooks: 6,570 tests passed, zero failed/skipped/cancelled; lint/static checks, TypeScript and differential file-size gate passed. - Native package hook passed: default and mesh-enabled all-target Clippy, then the complete native workspace test suite. App library: 3,222 passed / 0 failed / 19 ignored; terminal/integration suites passed. The real nest trigger/stalled-body test passed on macOS. - Independent whole-change source review: no blocking findings at this commit; all 20 file hashes matched the committed blobs and review/validation manifests. - Regression coverage includes real hook/session cancellation, StrictMode/membership re-entry, reconnect ownership, extended/zero cooldowns, burst pacing, auxiliary readiness (including EOSE before IPC settles), native socket refusal/retry/deadline/cancellation, unread fetch/classification and real nest trigger/HTTP/file persistence. - Earlier isolated renderer mutations that started readiness before enqueue or removed auxiliary priority each failed the real presence regression; restored controls passed. No native mutation claim. - Nest fixture uses explicit app-data/nest paths instead of assuming Windows known-folder APIs obey HOME/APPDATA. Windows runtime execution is not claimed; CI/build results remain separate. Originating conversation: buzz://message?channel=46ced308-71df-495d-a144-4ebf08334703&id=bc43c3422a3b0b2141268d0fa149b898421c824992b662aed8b73c4eee50404f No approval or merge recommendation is implied by opening this PR. --------- Signed-off-by: Brain <1a02c72794dcd0f07058a353bc3a81f4028b8c77c92c87fce6d5c8b85970a20b@buzz.block.builderlab.xyz> Co-authored-by: Brain <1a02c72794dcd0f07058a353bc3a81f4028b8c77c92c87fce6d5c8b85970a20b@buzz.block.builderlab.xyz>
1 parent 7881447 commit c213d90

49 files changed

Lines changed: 4263 additions & 385 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎desktop/src-tauri/src/managed_agents/nest.rs‎

Lines changed: 101 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -653,82 +653,84 @@ pub fn upsert_managed_section(file_path: &Path, new_section_content: &str) -> io
653653
Ok(())
654654
}
655655

656-
/// Serializes nest-context writes so a slow, stale regeneration cannot roll the
657-
/// file back over a newer one. This is an ordered, latest-request-wins gate —
658-
/// not a work coalescer: every superseded generation still performs its relay
659-
/// reads, then drops its result at commit time. Adding a true dirty-loop owner
660-
/// would be a larger change and is unwarranted at this user-driven trigger rate.
656+
/// One regeneration worker with a latest-request-wins write fence. Startup
657+
/// persona backfill can request hundreds of renders: intermediate requests must
658+
/// supersede stale writes without each doing their own archive snapshot read.
661659
///
662-
/// Each regeneration request claims a monotonic generation *synchronously* at
663-
/// request time (see [`NestRegenGate::claim`]), so the generation encodes
664-
/// program order: boot's regen is claimed before `apply_workspace`'s, an edit's
665-
/// regen before the next edit's. The claimed generation travels with the
666-
/// spawned task and gates its write in [`NestRegenGate::commit`]: a task drops
667-
/// its result once a *newer generation has been requested*, even if that newer
668-
/// generation later fails before it writes. Gating on the highest *requested*
669-
/// generation — not the highest *written* one — is what stops a slow, stale
670-
/// pre-edit render from publishing after a newer post-edit render was claimed
671-
/// and then failed during its relay work (which would otherwise leave the
672-
/// obsolete roster authoritative until the next unrelated trigger). Declared
673-
/// semantic: once a newer regeneration is requested, no older one publishes;
674-
/// if that newer one fails, the file simply waits for the next trigger.
675-
///
676-
/// `claim` and `commit` share one lock, so the "is this still the newest
677-
/// request?" compare is atomic with the synchronous file write. A bare atomic
678-
/// watermark checked separately from the write would let a new claim slip
679-
/// between an older task's eligibility check and its write; holding the lock
680-
/// across both closes that window (no `await` occurs while it is held).
660+
/// Claiming, finishing and committing share one lock. A trigger during a read
661+
/// leaves one latest-generation follow-up; a trigger at worker shutdown either
662+
/// becomes that follow-up or starts a new worker. No debounce or cached archive
663+
/// state is needed. Once a newer generation is requested, an older one cannot
664+
/// publish, even if the newer render fails (the next trigger can try again).
681665
struct NestRegenGate {
682-
/// Highest generation *requested* so far (`0` = none yet). Advanced by
683-
/// [`claim`] and read by [`commit`]; guarding both under this single lock
684-
/// keeps the eligibility compare atomic with the file write.
685-
highest_requested: Mutex<u64>,
666+
state: Mutex<NestRegenState>,
667+
}
668+
669+
struct NestRegenState {
670+
highest_requested: u64,
671+
running: bool,
686672
}
687673

688674
impl NestRegenGate {
689675
const fn new() -> Self {
690676
Self {
691-
highest_requested: Mutex::new(0),
677+
state: Mutex::new(NestRegenState {
678+
highest_requested: 0,
679+
running: false,
680+
}),
692681
}
693682
}
694683

695-
/// Claim the next generation. Call synchronously at request time so the
696-
/// value reflects when the regeneration was requested, not when its task
697-
/// happens to run. Advancing the shared watermark here is what lets a later
698-
/// [`commit`] recognize — and drop — any older generation's stale render.
699-
fn claim(&self) -> u64 {
700-
let mut requested = self
701-
.highest_requested
702-
.lock()
703-
.unwrap_or_else(|poisoned| poisoned.into_inner());
704-
*requested += 1;
705-
*requested
684+
/// Claim synchronously, before spawning. Only the idle-to-running caller
685+
/// owns a worker; all other callers just advance the pending generation.
686+
fn claim(&self) -> (u64, bool) {
687+
let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner());
688+
state.highest_requested += 1;
689+
let start_worker = !state.running;
690+
state.running = true;
691+
(state.highest_requested, start_worker)
692+
}
693+
694+
/// Return work only to the caller that starts the worker. The callback is
695+
/// the real regeneration path, supplied here so tests can hold its I/O.
696+
fn request<'a, F, Fut>(
697+
&'a self,
698+
mut regenerate: F,
699+
) -> Option<impl std::future::Future<Output = ()> + 'a>
700+
where
701+
F: FnMut(u64) -> Fut + 'a,
702+
Fut: std::future::Future<Output = Result<(), String>> + 'a,
703+
{
704+
let (mut generation, start_worker) = self.claim();
705+
if !start_worker {
706+
return None;
707+
}
708+
Some(async move {
709+
loop {
710+
if let Err(error) = regenerate(generation).await {
711+
eprintln!("buzz-desktop: nest context regeneration failed: {error}");
712+
}
713+
let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner());
714+
if state.highest_requested == generation {
715+
state.running = false;
716+
return;
717+
}
718+
generation = state.highest_requested;
719+
}
720+
})
706721
}
707722

708-
/// Non-blocking [`claim`] against the *exact* lock `claim` takes. Returns
709-
/// `Some(generation)` if it acquired the lock — i.e. a claim could proceed
710-
/// with no contention — or `None` if the lock is already held, meaning a
711-
/// concurrent claim would block on it. Because `claim` and `commit` share
712-
/// `highest_requested`, calling this from inside `commit_hooked`'s
713-
/// under-lock hook reports `None`: the eligibility compare and the write
714-
/// are serialized against any new claim. A design that advanced the
715-
/// watermark under a separate lock (or a lock-free atomic) would report
716-
/// `Some` here — the regression this probe proves absent, with no reliance
717-
/// on elapsed time or thread scheduling.
723+
/// Probe the exact claim/commit lock, including inside the commit hook.
718724
#[cfg(test)]
719725
fn try_claim(&self) -> Option<u64> {
720-
match self.highest_requested.try_lock() {
721-
Ok(mut requested) => {
722-
*requested += 1;
723-
Some(*requested)
724-
}
725-
Err(std::sync::TryLockError::WouldBlock) => None,
726-
Err(std::sync::TryLockError::Poisoned(poisoned)) => {
727-
let mut requested = poisoned.into_inner();
728-
*requested += 1;
729-
Some(*requested)
730-
}
731-
}
726+
let mut state = match self.state.try_lock() {
727+
Ok(state) => state,
728+
Err(std::sync::TryLockError::WouldBlock) => return None,
729+
Err(std::sync::TryLockError::Poisoned(poisoned)) => poisoned.into_inner(),
730+
};
731+
state.highest_requested += 1;
732+
state.running = true;
733+
Some(state.highest_requested)
732734
}
733735

734736
/// Commit `content` for `generation`, dropping the write once a newer
@@ -755,10 +757,10 @@ impl NestRegenGate {
755757
under_lock: impl FnOnce(),
756758
) -> io::Result<bool> {
757759
let requested = self
758-
.highest_requested
760+
.state
759761
.lock()
760762
.map_err(|_| io::Error::other("nest regen gate lock poisoned"))?;
761-
if generation < *requested {
763+
if generation < requested.highest_requested {
762764
return Ok(false);
763765
}
764766
under_lock();
@@ -767,7 +769,12 @@ impl NestRegenGate {
767769
}
768770
}
769771

770-
/// Process-wide ordered write gate for nest-context regeneration.
772+
// A best-effort roster refresh must not strand every newer edit behind an old
773+
// relay's unbounded NIP-11 body or admission wait. Bound the complete archive
774+
// operation, not just request headers; timeout preserves the existing fail-open.
775+
const NEST_ARCHIVE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
776+
777+
/// Process-wide regeneration owner and ordered write gate.
771778
static NEST_REGEN: NestRegenGate = NestRegenGate::new();
772779

773780
pub async fn regenerate_nest_context<R: tauri::Runtime>(
@@ -795,10 +802,20 @@ pub async fn regenerate_nest_context<R: tauri::Runtime>(
795802
// uses the same captured target as the rendered relay; a later generation's
796803
// task always wins the commit, so a fallback-relay boot render cannot bury a
797804
// later apply_workspace render.
798-
let archived: HashSet<String> = fetch_archived_pubkeys_at(&state, &target)
799-
.await
800-
.into_iter()
801-
.collect();
805+
let archived: HashSet<String> = match tokio::time::timeout(
806+
NEST_ARCHIVE_TIMEOUT,
807+
fetch_archived_pubkeys_at(&state, &target),
808+
)
809+
.await
810+
{
811+
Ok(pubkeys) => pubkeys.into_iter().collect(),
812+
Err(_) => {
813+
eprintln!(
814+
"buzz-desktop: nest archive read timed out; rendering without archive filter"
815+
);
816+
HashSet::new()
817+
}
818+
};
802819
let content = render_dynamic_section(&personas, &agents, &archived, &target.ws_url);
803820
NEST_REGEN
804821
.commit(&agents_md, &content, generation)
@@ -807,27 +824,25 @@ pub async fn regenerate_nest_context<R: tauri::Runtime>(
807824
Ok(())
808825
}
809826

810-
/// Convenience wrapper: claims a regeneration generation, then regenerates on a
811-
/// spawned task, logging a warning on failure.
812-
///
813-
/// All call sites treat regeneration as fire-and-forget — agents run fine with
814-
/// a stale AGENTS.md, so we warn and continue rather than propagating the error.
815-
/// The generation is claimed *here*, synchronously, so it encodes call order;
816-
/// the spawned task carries it into [`NestRegenGate::commit`], which drops
817-
/// a stale render rather than letting a slow task overwrite a newer file.
818-
/// Archive/unarchive trigger this directly, but the regen races the relay's
819-
/// `kind:13535` snapshot update, so a just-archived agent may still linger for
820-
/// one cycle until the next regen (any agent/team edit or the next launch).
827+
/// Fire-and-forget regeneration: one worker reads the latest state, with one
828+
/// pending follow-up if another trigger arrives. Failures still warn and leave
829+
/// the file for the next trigger; they never strand the worker as running.
830+
/// Archive/unarchive can race the relay's snapshot update, so an archived agent
831+
/// may still linger until the next trigger, as before.
821832
pub fn try_regenerate_nest<R: tauri::Runtime>(app: &AppHandle<R>) {
822-
let generation = NEST_REGEN.claim();
823833
let app = app.clone();
824-
tauri::async_runtime::spawn(async move {
825-
if let Err(error) = regenerate_nest_context(&app, generation).await {
826-
eprintln!("buzz-desktop: nest context regeneration failed: {error}");
827-
}
828-
});
834+
if let Some(work) = NEST_REGEN.request(move |generation| {
835+
let app = app.clone();
836+
async move { regenerate_nest_context(&app, generation).await }
837+
}) {
838+
tauri::async_runtime::spawn(work);
839+
}
829840
}
830841

842+
#[cfg(test)]
843+
mod regen_tests;
844+
#[cfg(test)]
845+
mod regen_trigger_tests;
831846
#[cfg(test)]
832847
mod render_tests;
833848
#[cfg(test)]
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
//! Exercise the production request/worker/commit boundary with held I/O and a
2+
//! real managed-section file. No sleeps, live relay, Tauri process or home writes.
3+
use super::*;
4+
use std::sync::atomic::{AtomicUsize, Ordering};
5+
use tokio::sync::{mpsc, oneshot};
6+
7+
#[tokio::test]
8+
async fn burst_coalesces_reads_and_commits_only_the_latest_workspace() {
9+
let gate = NestRegenGate::new();
10+
let tmp = tempfile::tempdir().unwrap();
11+
let file = tmp.path().join("AGENTS.md");
12+
fs::write(&file, "# User instructions\n").unwrap();
13+
let current = Mutex::new("wss://before.example");
14+
let reads = AtomicUsize::new(0);
15+
let active = AtomicUsize::new(0);
16+
let (started, mut starts) = mpsc::unbounded_channel();
17+
let worker = gate
18+
.request(|generation| {
19+
let relay = *current.lock().unwrap();
20+
let (release, released) = oneshot::channel();
21+
reads.fetch_add(1, Ordering::SeqCst);
22+
assert_eq!(active.fetch_add(1, Ordering::SeqCst), 0);
23+
started.send((generation, release)).unwrap();
24+
let gate = &gate;
25+
let active = &active;
26+
let file = &file;
27+
async move {
28+
released.await.unwrap();
29+
let content = render_dynamic_section(&[], &[], &HashSet::new(), relay);
30+
gate.commit(file, &content, generation).unwrap();
31+
active.fetch_sub(1, Ordering::SeqCst);
32+
Ok(())
33+
}
34+
})
35+
.unwrap();
36+
tokio::pin!(worker);
37+
let (first, release_first) = tokio::select! {
38+
value = starts.recv() => value.unwrap(),
39+
() = &mut worker => panic!("worker completed before its read"),
40+
};
41+
assert_eq!(first, 1);
42+
43+
// Model startup backfill and a workspace switch while the first snapshot
44+
// read is held. New requests must not even start their expensive callback.
45+
*current.lock().unwrap() = "wss://latest.example";
46+
for _ in 0..289 {
47+
assert!(gate
48+
.request(|_| async { panic!("duplicate worker") })
49+
.is_none());
50+
}
51+
assert_eq!(reads.load(Ordering::SeqCst), 1);
52+
release_first.send(()).unwrap();
53+
let (latest, release_latest) = tokio::select! {
54+
value = starts.recv() => value.unwrap(),
55+
() = &mut worker => panic!("latest request was lost"),
56+
};
57+
assert_eq!(latest, 290);
58+
assert_eq!(reads.load(Ordering::SeqCst), 2);
59+
assert_eq!(fs::read_to_string(&file).unwrap(), "# User instructions\n");
60+
release_latest.send(()).unwrap();
61+
worker.await;
62+
63+
let content = fs::read_to_string(&file).unwrap();
64+
assert!(content.starts_with("# User instructions"));
65+
assert!(content.contains("wss://latest.example"));
66+
assert!(!content.contains("wss://before.example"));
67+
assert_eq!(active.load(Ordering::SeqCst), 0);
68+
assert!(!gate.state.lock().unwrap().running);
69+
}
70+
71+
#[tokio::test]
72+
async fn trigger_during_follow_up_and_after_idle_is_not_lost() {
73+
let gate = NestRegenGate::new();
74+
let passes = AtomicUsize::new(0);
75+
gate.request(|generation| {
76+
let pass = passes.fetch_add(1, Ordering::SeqCst);
77+
if pass < 2 {
78+
assert!(gate
79+
.request(|_| async { panic!("second worker") })
80+
.is_none());
81+
}
82+
async move {
83+
assert_eq!(generation, pass as u64 + 1);
84+
Ok(())
85+
}
86+
})
87+
.unwrap()
88+
.await;
89+
assert_eq!(passes.load(Ordering::SeqCst), 3);
90+
assert!(!gate.state.lock().unwrap().running);
91+
92+
// A request after idle must acquire ownership, not remain stranded dirty.
93+
gate.request(|generation| async move {
94+
assert_eq!(generation, 4);
95+
Ok(())
96+
})
97+
.unwrap()
98+
.await;
99+
assert!(!gate.state.lock().unwrap().running);
100+
}
101+
102+
#[tokio::test]
103+
async fn failed_pass_runs_pending_latest_and_releases_owner_for_next_trigger() {
104+
let gate = NestRegenGate::new();
105+
let passes = AtomicUsize::new(0);
106+
gate.request(|_| {
107+
if passes.fetch_add(1, Ordering::SeqCst) == 0 {
108+
assert!(gate
109+
.request(|_| async { panic!("second worker") })
110+
.is_none());
111+
}
112+
async { Err("controlled regeneration failure".into()) }
113+
})
114+
.unwrap()
115+
.await;
116+
assert_eq!(passes.load(Ordering::SeqCst), 2);
117+
assert!(!gate.state.lock().unwrap().running);
118+
gate.request(|_| async { Ok(()) }).unwrap().await;
119+
assert!(!gate.state.lock().unwrap().running);
120+
}

0 commit comments

Comments
 (0)