Skip to main content

flint_lean/
verbs.rs

1//! The one-shot verbs, and which of them holds the publish fence for
2//! its whole run.
3//!
4//! Lifted out of `bin/flint_sync.rs` so the RULE — which verb claims —
5//! is a property the battery can execute rather than a line of dispatch
6//! nobody can reach from a test. `a_checkout_does_not_wait_out_a_\
7//! standing_lease` in `tests.rs` calls `lease_free_then`, the same
8//! function the dispatch calls, rather than a re-implementation of it.
9
10use super::lease;
11use super::{LeanError, Syncer};
12
13/// A comma list, trimmed, empties dropped. Returns `None` when the
14/// variable is unset or holds only separators — `Some(vec![])` would be
15/// an empty scope, and `checkout_scoped` refuses that rather than let it
16/// mean "everything".
17pub fn env_list(name: &str) -> Option<Vec<String>> {
18    let raw = std::env::var(name).ok()?;
19    let v: Vec<String> =
20        raw.split(',').map(|e| e.trim().to_string()).filter(|e| !e.is_empty()).collect();
21    if v.is_empty() {
22        return None;
23    }
24    Some(v)
25}
26
27pub enum Step {
28    Checkout,
29    Barrier,
30    Sync,
31    /// The narrow/widen verb. `None` is the whole tree; an empty
32    /// argument list therefore cannot mean "narrow to nothing".
33    Rescope(Option<Vec<String>>),
34}
35
36impl Step {
37    /// Does this verb hold the publish fence for its WHOLE run?
38    ///
39    /// The epoch cell arbitrates who may INSTALL a manifest, and since
40    /// the lease is held per barrier (design 2026-09-13 §4) a barrier
41    /// claims it INSIDE — after its uploads, for the commit section
42    /// only — so the `barrier` verb needs no outer claim. `checkout`
43    /// and `sync` install nothing: every GET they make carries the
44    /// cited etag as `If-Match`, so a publisher racing them yields a
45    /// handled 412, never a torn file, and holding the fence around
46    /// them only ever serialised readers on one cell (four syncers
47    /// reading disjoint subtrees ran 2.1x faster without it, 0.41x with
48    /// it — measured 2026-09-11).
49    ///
50    /// `rescope` is the only `true`. It reads the bucket and writes
51    /// nothing to it either, but it rewrites the held set and leaves a
52    /// replayable intent behind, so it stays fenced until someone has
53    /// walked that crash matrix with two of them running.
54    pub fn holds_the_fence_throughout(&self) -> bool {
55        match self {
56            Step::Rescope(_) => true,
57            Step::Checkout | Step::Barrier | Step::Sync => false,
58        }
59    }
60}
61
62/// The one door every one-shot verb goes through. The ROUTING lives
63/// here rather than in the binary's argv match so that the battery
64/// exercises the same decision the shipped binary makes.
65pub async fn run_verb(sc: &mut Syncer, step: Step) -> Result<(), LeanError> {
66    if step.holds_the_fence_throughout() {
67        claim_then(sc, step).await
68    } else {
69        lease_free_then(sc, step).await
70    }
71}
72
73/// Take the fence, do one step, release it.
74pub async fn claim_then(sc: &mut Syncer, step: Step) -> Result<(), LeanError> {
75    lease::verify_claim(sc).await?;
76    lease::warn_if_prefix_is_shared(sc).await;
77    let held = lease::claim(sc).await?;
78    eprintln!("flint-sync: holding epoch {}", held.epoch);
79    let out = run_step(sc, step).await;
80    if let Err(e) = lease::release(sc).await {
81        eprintln!("flint-sync: the publish fence could not be released ({e}); a waiter deposes it");
82    }
83    out
84}
85
86/// A verb that claims nothing up front. Two things here are not the
87/// lease and stay:
88///   * `verify_claim` — the project-id precondition. A refusal, not a
89///     fence: this prefix is another project's and must not be read or
90///     written by us at all.
91///   * `warn_if_prefix_is_shared` — a diagnostic nobody else emits.
92pub async fn lease_free_then(sc: &mut Syncer, step: Step) -> Result<(), LeanError> {
93    lease::verify_claim(sc).await?;
94    lease::warn_if_prefix_is_shared(sc).await;
95    run_step(sc, step).await
96}
97
98/// The verb bodies. Shared by both doors above so that the ONLY
99/// difference between a fenced verb and a lease-free one is the door,
100/// never a second copy of the work.
101pub async fn run_step(sc: &mut Syncer, step: Step) -> Result<(), LeanError> {
102    {
103        match step {
104            Step::Checkout => {
105                let r = sc.checkout_scoped(env_list("FLINT_SYNC_CHECKOUT_SCOPE")).await?;
106                eprintln!(
107                    "flint-sync: checkout — {} materialized, {} present, live-tree={}",
108                    r.materialized, r.skipped_present, r.resumed_live_tree
109                );
110                if let Some(sc) = &r.scope {
111                    // The declined count, not just the scope: a scope
112                    // that admits everything reads exactly like no
113                    // scope, and "it was configured" is not evidence
114                    // that it did anything.
115                    eprintln!(
116                        "flint-sync: checkout SCOPED to {:?} — {} citations declined",
117                        sc, r.out_of_scope
118                    );
119                }
120                // BYTES on the same line as the phases, deliberately:
121                // an A/B of the fetch window compares two wall clocks,
122                // and an arm that "wins" by materialising fewer bytes
123                // is the failure mode a timing-only line cannot show.
124                eprintln!(
125                    "flint-sync: phase manifest={:.3}s fetch={:.3}s commit={:.3}s bytes={} ranged={}",
126                    r.manifest_secs, r.fetch_secs, r.commit_secs, r.bytes, r.ranged
127                );
128            }
129            Step::Rescope(target) => {
130                let r = sc.rescope(target).await?;
131                eprintln!(
132                    "flint-sync: rescope to {:?} — uncited {}, unlinked {}, materialised {} \
133                     ({} bytes), already held {}",
134                    r.target, r.uncited, r.unlinked, r.materialized, r.bytes, r.already_held
135                );
136                // A kept path is the one outcome a caller must not miss:
137                // the scope now says one thing and the held set holds
138                // more, and the reason is an edit only they can resolve.
139                if !r.kept_dirty.is_empty() {
140                    eprintln!(
141                        "flint-sync: rescope KEPT {} path(s) with unpublished changes: {:?} — \
142                         publish them, then rescope again to drop them",
143                        r.kept_dirty.len(),
144                        r.kept_dirty
145                    );
146                }
147            }
148            Step::Barrier => {
149                let r = sc.run_barrier().await?;
150                eprintln!(
151                    "flint-sync: barrier seq={:?} up={} del={} parked={} consumed={}",
152                    r.seq,
153                    r.uploaded.len(),
154                    r.deleted.len(),
155                    r.parked.len(),
156                    r.consumed
157                );
158            }
159            Step::Sync => {
160                let r = sc.sync().await?;
161                println!("{}", serde_json::to_string_pretty(&r).unwrap());
162            }
163        }
164        Ok(())
165    }
166}