Skip to main content

bynk/deploy/
revert.rs

1//! #3073: `bynk revert` — make the previous deployment live again, after
2//! checking what makes that unsafe.
3//!
4//! The mechanism is Cloudflare's own version rollback, driven by Bynk. What
5//! Bynk adds is the judgement: it reads the facts each version carries about
6//! itself ([`Facts`], set at deploy), compares the live and target versions,
7//! and refuses, naming each reason, when going back would fault agents on
8//! newer records, run on a schema the target was not built for, break a
9//! contract a live peer holds, or bind a resource the ledger no longer
10//! records. Every unknown is a refusal. Nothing is rebuilt and no `.bynk/`
11//! build tree is needed, so it works from a fresh CI checkout.
12//!
13//! Everything that touches the account sits behind [`Account`], so the checks,
14//! the history walk and the execution are exercised against a fake. The real
15//! implementation ([`LiveAccount`]) rests on Cloudflare behaviour the
16//! proposal lists as gated probes (response shapes, what a rollback restores).
17
18use super::facts::{FACTS_VAR, Facts};
19use super::*;
20use crate::cloudflare::{CloudflareError, Rest};
21use crate::migrate::sweep::{Cloudflare as DoApi, SETTLING_MARGIN};
22use bynk_driver::emsg;
23
24/// One entry of a Worker's deployment list, newest first.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub(crate) struct Deployment {
27    pub(crate) id: String,
28    /// RFC 3339.
29    pub(crate) created_on: String,
30    /// `annotations["workers/triggered_by"]`: `upload`, `secret`, `deployment`…
31    /// Cloudflare reports a rollback (`wrangler rollback`, so `bynk revert`) as
32    /// `deployment`, not `rollback` (#3112).
33    pub(crate) trigger: Option<String>,
34    /// `(version id, percentage)`.
35    pub(crate) versions: Vec<(String, u32)>,
36}
37
38impl Deployment {
39    fn is_secret(&self) -> bool {
40        self.trigger.as_deref() == Some("secret")
41    }
42    /// A deployment that re-activates an existing version. Cloudflare records
43    /// `wrangler rollback` (and so `bynk revert`) as trigger `deployment`,
44    /// not `rollback` (#3112, observed on a real account); `rollback` is kept
45    /// in case another path reports it.
46    fn is_rollback(&self) -> bool {
47        matches!(self.trigger.as_deref(), Some("rollback" | "deployment"))
48    }
49    /// The one version this deployment serves at 100%, if it is not split.
50    fn sole_version(&self) -> Option<&str> {
51        match self.versions.as_slice() {
52            [(id, 100)] => Some(id),
53            _ => None,
54        }
55    }
56}
57
58/// What the revert needs from the account.
59pub(crate) trait Account {
60    /// The Worker's deployments, newest first, as many as Cloudflare lists.
61    fn deployments(&self, script: &str) -> Result<Vec<Deployment>, CloudflareError>;
62    /// The text of a version's [`FACTS_VAR`] variable, `None` when it has none.
63    fn version_facts(&self, script: &str, version: &str)
64    -> Result<Option<String>, CloudflareError>;
65    /// The migration files a D1 database has applied, in order.
66    fn applied_migrations(&self, database_id: &str) -> Result<Vec<String>, CloudflareError>;
67    /// Whether any instance of agent `class` on `script` holds stored data.
68    fn has_stored_data(&self, script: &str, class: &str) -> Result<bool, CloudflareError>;
69    /// Make `version` the Worker's live deployment.
70    fn rollback(&self, script: &str, version: &str) -> Result<(), CloudflareError>;
71}
72
73/// Where the live and target versions sit in a Worker's history.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub(crate) struct Located {
76    /// The newest deployment of any trigger: the version whose facts describe
77    /// what is live (a secret change keeps the code and the variables).
78    pub(crate) live_version: String,
79    /// That deployment's id: re-read before the rollback, so a deploy *or* a
80    /// secret change made after the plan stops the revert.
81    pub(crate) live_deployment: String,
82    pub(crate) live_code_created: String,
83    /// The version the revert goes back to.
84    pub(crate) target_version: String,
85    /// Secret-triggered deployments newer than the target's own.
86    pub(crate) secret_changes: usize,
87}
88
89const GRADUAL: &str = "a gradual deployment is in progress (traffic is split between versions); finish or cancel it first";
90
91/// Find the live and target versions in `deployments` (newest first).
92///
93/// The target is the deployment immediately before the *upload of the live
94/// code version*: what was live, secrets included, just before the release
95/// being left. Going back to an older *upload* instead would restore the
96/// secret values from before any rotation in between. Other deployments are
97/// read as follows. A rollback deployment re-activates a version and adds no
98/// code, so the live code version is found by its own upload, and a second
99/// revert goes back past that upload rather than to the release just left.
100/// A secret change mints a version with the same code, so it never counts as
101/// the live code, but it can be a target (it is what was live).
102pub(crate) fn locate(deployments: &[Deployment], to: Option<&str>) -> Result<Located, String> {
103    let newest = deployments
104        .first()
105        .ok_or("Cloudflare lists no deployment for it")?;
106    let live_version = newest.sole_version().ok_or(GRADUAL)?.to_string();
107    let live_code = deployments
108        .iter()
109        .find(|d| !d.is_secret())
110        .ok_or("every listed deployment is a secret change; the code's history is out of view")?;
111    let live_code_version = live_code.sole_version().ok_or(GRADUAL)?.to_string();
112    let target_index = match to {
113        Some(id) => {
114            if id == live_code_version || id == live_version {
115                return Err(format!("version `{id}` is the one already live"));
116            }
117            deployments
118                .iter()
119                .position(|d| d.sole_version() == Some(id))
120                .ok_or_else(|| {
121                    format!("version `{id}` is not among the Worker's listed deployments")
122                })?
123        }
124        None => {
125            let upload = deployments
126                .iter()
127                .position(|d| {
128                    !d.is_secret()
129                        && !d.is_rollback()
130                        && d.sole_version() == Some(live_code_version.as_str())
131                })
132                .ok_or("the live version's own upload is out of the listed history, so what preceded it cannot be told (a version made live by `wrangler versions deploy` or the dashboard has no upload deployment: name the target with `--to`)")?;
133            if upload + 1 >= deployments.len() {
134                return Err("there is no earlier deployment in the Worker's listed history".into());
135            }
136            upload + 1
137        }
138    };
139    let target = deployments[target_index].sole_version().ok_or(GRADUAL)?;
140    if target == live_code_version || target == live_version {
141        return Err(format!("version `{target}` is the one already live"));
142    }
143    let secret_changes = deployments[..target_index]
144        .iter()
145        .filter(|d| d.is_secret())
146        .count();
147    Ok(Located {
148        live_version,
149        live_deployment: newest.id.clone(),
150        live_code_created: live_code.created_on.clone(),
151        target_version: target.to_string(),
152        secret_changes,
153    })
154}
155
156/// The registered diagnostic code of each refusal (`bynk explain <code>`).
157mod code {
158    pub(super) const FACTS_MISSING: &str = "bynk.revert.facts_missing";
159    pub(super) const D1_SCHEMA_AHEAD: &str = "bynk.revert.database_schema_ahead";
160    pub(super) const AGENT_SCHEMA_OLDER: &str = "bynk.revert.agent_schema_older";
161    pub(super) const LAYOUT_OLDER: &str = "bynk.revert.layout_older";
162    pub(super) const CLASS_CHANGED: &str = "bynk.revert.class_changed";
163    pub(super) const CONTRACT_SKEW: &str = "bynk.revert.contract_skew";
164    pub(super) const ID_UNRECORDED: &str = "bynk.revert.id_unrecorded";
165    pub(super) const SECRET_CHANGED: &str = "bynk.revert.secret_changed";
166    pub(super) const HISTORY_UNPLACEABLE: &str = "bynk.revert.history_unplaceable";
167    pub(super) const MEMBERSHIP_CHANGED: &str = "bynk.revert.membership_changed";
168}
169
170/// A group is one script, so a rollback must go to a version holding the same members.
171fn membership_finding(c: &Case<'_>) -> Option<Finding> {
172    (c.live.contexts != c.target.contexts).then(|| {
173        Finding::refused(
174            "members",
175            code::MEMBERSHIP_CHANGED,
176            c.worker,
177            format!(
178                "the live version holds [{}] and the target holds [{}]; rolling back would take a context's code out of the Worker, or put one back that has since moved. Deploy forward instead",
179                c.live.contexts.join(", "),
180                c.target.contexts.join(", ")
181            ),
182        )
183    })
184}
185
186/// One check's outcome.
187#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
188pub(crate) struct Finding {
189    pub(crate) check: &'static str,
190    /// The registered `bynk.revert.*` diagnostic code of a refusal, for scripts
191    /// to match on; absent from a passing check.
192    #[serde(skip_serializing_if = "Option::is_none")]
193    pub(crate) code: Option<&'static str>,
194    pub(crate) subject: String,
195    /// `ok` or `refused`.
196    pub(crate) verdict: &'static str,
197    pub(crate) detail: String,
198}
199
200impl Finding {
201    fn ok(check: &'static str, subject: impl Into<String>, detail: impl Into<String>) -> Self {
202        Finding {
203            check,
204            code: None,
205            subject: subject.into(),
206            verdict: "ok",
207            detail: detail.into(),
208        }
209    }
210    fn refused(
211        check: &'static str,
212        code: &'static str,
213        subject: impl Into<String>,
214        why: impl Into<String>,
215    ) -> Self {
216        Finding {
217            check,
218            code: Some(code),
219            subject: subject.into(),
220            verdict: "refused",
221            detail: why.into(),
222        }
223    }
224    pub(crate) fn is_refusal(&self) -> bool {
225        self.verdict == "refused"
226    }
227}
228
229/// What the account said about stored agent data for one class.
230#[derive(Debug, Clone, PartialEq, Eq)]
231pub(crate) enum Stored {
232    None,
233    Present,
234    /// The listing lags a write by minutes (ADR 0566): inside the margin of
235    /// the live deploy, or unreadable, an empty listing proves nothing.
236    Unknown(String),
237}
238
239/// What [`evaluate`] weighs for one Worker.
240pub(crate) struct Case<'a> {
241    pub(crate) worker: &'a str,
242    pub(crate) environment: &'a str,
243    pub(crate) live: &'a Facts,
244    pub(crate) target: &'a Facts,
245    /// Applied migrations by D1 binding.
246    pub(crate) applied: &'a BTreeMap<String, Result<Vec<String>, String>>,
247    /// Stored-data state by agent class, for the classes that need it.
248    pub(crate) stored: &'a BTreeMap<String, Stored>,
249    /// Each class's floor in the checkout's `bynk.schema.lock`.
250    pub(crate) floors: &'a BTreeMap<String, i64>,
251    /// The ledger as it will stand once every selected Worker is reverted.
252    pub(crate) after: &'a DeployLock,
253    /// The ledger as it stands now, for the recorded ids.
254    pub(crate) lock: &'a DeployLock,
255    pub(crate) secret_changes: usize,
256    pub(crate) accept_schema_ahead: &'a BTreeSet<String>,
257    pub(crate) accept_secret_changes: bool,
258}
259
260/// The D1 bindings whose applied list a case needs.
261pub(crate) fn databases_to_read(live: &Facts, target: &Facts) -> BTreeSet<String> {
262    live.migrations
263        .keys()
264        .chain(target.migrations.keys())
265        .cloned()
266        .collect()
267}
268
269/// The agent classes whose stored data a case needs to know about: those the
270/// live version writes at a higher schema version than the target, and, when the
271/// live version writes a later storage layout than the target (#3189), every class
272/// the two share.
273pub(crate) fn classes_to_probe(live: &Facts, target: &Facts) -> BTreeSet<String> {
274    let layout_ahead = live.layout() > target.layout();
275    live.agents
276        .iter()
277        .filter(|(class, lv)| {
278            target
279                .agents
280                .get(*class)
281                .is_some_and(|tv| tv < lv || layout_ahead)
282        })
283        .map(|(class, _)| class.clone())
284        .collect()
285}
286
287/// The binding's id as the ledger records it now.
288fn recorded_id(
289    lock: &DeployLock,
290    worker: &str,
291    binding: &str,
292    environment: &str,
293) -> Option<String> {
294    // 1D.1 (#3929): each converted kind's, first.
295    recorded_bound_id(LedgerView::of(lock, environment), worker, binding)
296}
297
298/// Every check for one Worker. A refusal is any finding with verdict
299/// `refused`; nothing here is advisory.
300/// #3477: a rollback restores the version's image map, which a *new* start
301/// reads; an instance that is already running keeps the image it started with
302/// and takes no part in application-wide rollouts. Said for each container the
303/// target carries, so a revert is not taken to replace a running one. Read from
304/// the Cloudflare docs, not yet seen on a real account.
305fn container_rollback_notes(target: &Facts) -> Vec<Finding> {
306    target
307        .classes
308        .iter()
309        .filter(|class| class.starts_with(bynk_check::containers::CONTAINER_CLASS_PREFIX))
310        .map(|class| {
311            Finding::ok(
312                "container",
313                class,
314                "warning: the rollback restores the image for new starts only; instances already running keep the image they started with until they stop",
315            )
316        })
317        .collect()
318}
319
320/// D1 migrations are forward-only (ADR 0664).
321fn d1_findings(c: &Case<'_>, out: &mut Vec<Finding>) {
322    for binding in databases_to_read(c.live, c.target) {
323        let target_files = c.target.migrations.get(&binding);
324        if target_files.is_none() && !c.target.ids.contains_key(&binding) {
325            out.push(Finding::ok("d1", &binding, "not used by the target"));
326            continue;
327        }
328        let applied = match c.applied.get(&binding) {
329            Some(Ok(a)) => a,
330            Some(Err(e)) => {
331                out.push(Finding::refused(
332                    "d1",
333                    code::D1_SCHEMA_AHEAD,
334                    &binding,
335                    format!("could not read the applied migrations: {e}"),
336                ));
337                continue;
338            }
339            None => {
340                out.push(Finding::refused(
341                    "d1",
342                    code::D1_SCHEMA_AHEAD,
343                    &binding,
344                    "the applied migrations were not read",
345                ));
346                continue;
347            }
348        };
349        let known: BTreeSet<&String> = target_files.into_iter().flatten().collect();
350        let ahead: Vec<&String> = applied.iter().filter(|f| !known.contains(f)).collect();
351        if ahead.is_empty() {
352            out.push(Finding::ok(
353                "d1",
354                &binding,
355                "no migration newer than the target",
356            ));
357        } else {
358            let files = ahead
359                .iter()
360                .map(|f| f.as_str())
361                .collect::<Vec<_>>()
362                .join(", ");
363            if c.accept_schema_ahead.contains(&binding) {
364                out.push(Finding::ok(
365                    "d1",
366                    &binding,
367                    format!("applied after the target was built, accepted as additive: {files}"),
368                ));
369            } else {
370                out.push(Finding::refused(
371                    "d1",
372                    code::D1_SCHEMA_AHEAD,
373                    &binding,
374                    format!(
375                        "the live version applied {files} after the target was built; migrations are forward-only, so the target may not run on this schema (if each is additive, `--accept-schema-ahead {binding}`)"
376                    ),
377                ));
378            }
379        }
380    }
381}
382
383pub(crate) fn evaluate(c: &Case<'_>) -> Vec<Finding> {
384    let mut out = Vec::new();
385
386    out.extend(container_rollback_notes(c.target));
387
388    // #3562: a group is one script, so the version it goes back to must hold the
389    // contexts the live one does. Another membership (a context moved into or out of
390    // the group since, or a version from before groups) would take a context's code
391    // out from under its traffic.
392    out.extend(membership_finding(c));
393
394    d1_findings(c, &mut out);
395
396    // Agent state is stamped with its schema version (ADR 0545) and faults on
397    // newer records.
398    if c.live.classes != c.target.classes {
399        let added: Vec<&String> = c
400            .live
401            .classes
402            .iter()
403            .filter(|x| !c.target.classes.contains(x))
404            .collect();
405        let removed: Vec<&String> = c
406            .target
407            .classes
408            .iter()
409            .filter(|x| !c.live.classes.contains(x))
410            .collect();
411        out.push(Finding::refused(
412            "classes",
413            code::CLASS_CHANGED,
414            c.worker,
415            format!(
416                "the Durable Object classes differ (added since the target: [{}]; removed since: [{}]); Cloudflare cannot roll back across a class migration",
417                added.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", "),
418                removed.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", "),
419            ),
420        ));
421    }
422    let classes: BTreeSet<&String> = c.live.agents.keys().chain(c.target.agents.keys()).collect();
423    for class in classes {
424        match (c.live.agents.get(class), c.target.agents.get(class)) {
425            (Some(_), None) | (None, Some(_)) => out.push(Finding::refused(
426                "agent",
427                code::AGENT_SCHEMA_OLDER,
428                class.as_str(),
429                "the class is declared by only one of the two versions",
430            )),
431            (Some(lv), Some(tv)) => {
432                let floor = c.floors.get(class).copied().unwrap_or(1);
433                if *tv < floor {
434                    out.push(Finding::refused(
435                        "agent",
436                        code::AGENT_SCHEMA_OLDER,
437                        class.as_str(),
438                        format!("the target writes schema v{tv}, below the class's floor v{floor} (a sweep raised it; instances there have no migration path)"),
439                    ));
440                } else if tv < lv {
441                    match c.stored.get(class) {
442                        Some(Stored::None) => out.push(Finding::ok(
443                            "agent",
444                            class.as_str(),
445                            format!("target writes v{tv}, live v{lv}, and no instance holds stored data"),
446                        )),
447                        Some(Stored::Present) => out.push(Finding::refused(
448                            "agent",
449                            code::AGENT_SCHEMA_OLDER,
450                            class.as_str(),
451                            format!("the target writes schema v{tv} but the live version wrote v{lv}, and stored instances exist; the target would fault on them (NewerSchema)"),
452                        )),
453                        Some(Stored::Unknown(why)) => out.push(Finding::refused(
454                            "agent",
455                            code::AGENT_SCHEMA_OLDER,
456                            class.as_str(),
457                            format!("the target writes schema v{tv}, live v{lv}, and whether instances hold data is not known: {why}"),
458                        )),
459                        None => out.push(Finding::refused(
460                            "agent",
461                            code::AGENT_SCHEMA_OLDER,
462                            class.as_str(),
463                            "stored data was not read",
464                        )),
465                    }
466                } else {
467                    out.push(Finding::ok(
468                        "agent",
469                        class.as_str(),
470                        format!("target v{tv}, live v{lv}"),
471                    ));
472                }
473            }
474            (None, None) => {}
475        }
476    }
477
478    // Storage layout (#3189): a build that writes an older layout than the live one
479    // would read records in a layout it does not know. The build that has the
480    // forward-compatibility guard faults `NewerLayout`; one without it zero-merges
481    // the missing collections and writes wholesale, orphaning every per-entry key.
482    // Either way an instance with stored data is not safe to roll back over, and
483    // nothing here can tell the two builds apart, so any rollback to an older layout
484    // with stored data is refused. It is a property of the whole build, so every
485    // class the two share is looked at.
486    if c.live.layout() > c.target.layout() {
487        let (ll, tl) = (c.live.layout(), c.target.layout());
488        let shared: Vec<&String> = c
489            .live
490            .agents
491            .keys()
492            .filter(|class| c.target.agents.contains_key(*class))
493            .collect();
494        let mut found = false;
495        for class in &shared {
496            found = true;
497            match c.stored.get(*class) {
498                Some(Stored::None) => {}
499                Some(Stored::Present) => out.push(Finding::refused(
500                    "layout",
501                    code::LAYOUT_OLDER,
502                    class.as_str(),
503                    format!("the target writes storage layout {tl} but the live version wrote layout {ll}, and stored instances exist; the target cannot read them (NewerLayout), and a build without that check would orphan their entries"),
504                )),
505                Some(Stored::Unknown(why)) => out.push(Finding::refused(
506                    "layout",
507                    code::LAYOUT_OLDER,
508                    class.as_str(),
509                    format!("the target writes storage layout {tl}, live {ll}, and whether instances hold data is not known: {why}"),
510                )),
511                None => out.push(Finding::refused(
512                    "layout",
513                    code::LAYOUT_OLDER,
514                    class.as_str(),
515                    "stored data was not read",
516                )),
517            }
518        }
519        if !found
520            || shared
521                .iter()
522                .all(|class| matches!(c.stored.get(*class), Some(Stored::None)))
523        {
524            out.push(Finding::ok(
525                "layout",
526                c.worker,
527                format!("target writes layout {tl}, live {ll}, and no instance holds stored data"),
528            ));
529        }
530    }
531
532    // Contracts (#643, #2077): the target's records against the ledger as it
533    // will stand with every selected Worker reverted.
534    let mut skew = Vec::new();
535    for s in contract_skews(
536        &c.target.expects,
537        c.after,
538        |dependency: &str| c.after.worker_of(c.environment, dependency),
539        c.environment,
540    ) {
541        skew.push(format!(
542            "calls {}.{} at {} but it provides {}",
543            s.dependency, s.service, s.expected, s.live
544        ));
545    }
546    for s in callee_contract_skews(
547        c.worker,
548        &c.target.provides,
549        c.after,
550        |dependency: &str| c.after.worker_of(c.environment, dependency),
551        c.environment,
552    ) {
553        skew.push(format!(
554            "live caller `{}` stamps {}.{} at {} but the target provides {}",
555            s.caller, s.dependency, s.service, s.expected, s.provided
556        ));
557    }
558    if skew.is_empty() {
559        out.push(Finding::ok(
560            "contracts",
561            c.worker,
562            "no skew against the other live Workers",
563        ));
564    } else {
565        out.push(Finding::refused(
566            "contracts",
567            code::CONTRACT_SKEW,
568            c.worker,
569            skew.join("; "),
570        ));
571    }
572
573    // Resource ids: the target must bind what the ledger records now.
574    let mut id_problems = Vec::new();
575    for (binding, id) in &c.target.ids {
576        match recorded_id(c.lock, c.worker, binding, c.environment) {
577            Some(now) if now == *id => {}
578            Some(now) => id_problems.push(format!("{binding} was {id}, the ledger records {now}")),
579            None => id_problems.push(format!("{binding} ({id}) is no longer recorded")),
580        }
581    }
582    if id_problems.is_empty() {
583        out.push(Finding::ok(
584            "ids",
585            c.worker,
586            "every bound resource is the one the ledger records",
587        ));
588    } else {
589        out.push(Finding::refused(
590            "ids",
591            code::ID_UNRECORDED,
592            c.worker,
593            format!(
594                "the target would bind a resource that has since been replaced: {}",
595                id_problems.join("; ")
596            ),
597        ));
598    }
599
600    // Secrets changed between the target and now.
601    if c.secret_changes == 0 {
602        out.push(Finding::ok(
603            "secrets",
604            c.worker,
605            "no secret change since the target",
606        ));
607    } else if c.accept_secret_changes {
608        out.push(Finding::ok(
609            "secrets",
610            c.worker,
611            format!(
612                "{} secret change(s) since the target, accepted",
613                c.secret_changes
614            ),
615        ));
616    } else {
617        out.push(Finding::refused(
618            "secrets",
619            code::SECRET_CHANGED,
620            c.worker,
621            format!(
622                "{} secret change(s) since the target; a rollback may restore a secret (an edge key, say) its peers no longer accept (a `bynk migrate sweep` makes two; if only those, `--accept-secret-changes`)",
623                c.secret_changes
624            ),
625        ));
626    }
627    out
628}
629
630/// The order to revert in: callers before the callees they call, so a
631/// reverted callee never answers a caller still on the newer contract
632/// (ADR 0648 covers the window for compatible changes). Cycles and
633/// ties fall back to name order.
634pub(crate) fn revert_order(
635    workers: &BTreeMap<String, &Facts>,
636    worker_of: &dyn Fn(&str) -> String,
637) -> Vec<String> {
638    let mut remaining: BTreeSet<String> = workers.keys().cloned().collect();
639    let mut order = Vec::new();
640    while !remaining.is_empty() {
641        let next = remaining
642            .iter()
643            .find(|w| {
644                // Callers first: `w` is next when nothing remaining calls it.
645                !remaining.iter().any(|other| {
646                    other != *w
647                        && workers[other]
648                            .expects
649                            .keys()
650                            .any(|dep| worker_of(dep) == **w)
651                })
652            })
653            .or_else(|| remaining.iter().next())
654            .cloned()
655            .expect("remaining is not empty");
656        remaining.remove(&next);
657        order.push(next);
658    }
659    order
660}
661
662/// A copy of the ledger (it is not `Clone`: it round-trips through TOML, as it
663/// does on disk).
664fn clone_lock(lock: &DeployLock) -> DeployLock {
665    toml::to_string(lock)
666        .ok()
667        .and_then(|text| toml::from_str::<DeployLock>(&text).ok())
668        .unwrap_or_default()
669}
670
671/// A copy of `lock` with `target`'s contract records standing for `worker`.
672fn with_target_contracts(
673    lock: &DeployLock,
674    environment: &str,
675    worker: &str,
676    target: &Facts,
677) -> DeployLock {
678    let mut copy = clone_lock(lock);
679    apply_target(&mut copy, environment, worker, target);
680    copy
681}
682
683/// What a reverted Worker's ledger entry says: the contracts of the version
684/// now live. Ids, queues and tombstones are untouched.
685fn apply_target(lock: &mut DeployLock, environment: &str, worker: &str, target: &Facts) {
686    lock.record_deployed(environment, worker, Some(target.provides.clone()));
687    lock.record_expects(environment, worker, target.expects.clone());
688    lock.record_foreign(environment, worker, target.foreign.clone());
689}
690
691/// `bynk revert`'s options.
692#[derive(Debug, Clone, Default)]
693pub struct RevertOptions {
694    pub environment: String,
695    /// One context (dotted name or Worker directory); the whole project when
696    /// `None`.
697    pub context: Option<String>,
698    /// #3562: `context` was given as `--worker NAME`, a Worker directory (a group's
699    /// key) and not a context's name.
700    pub by_worker: bool,
701    /// A Cloudflare version id to go back to instead of the previous upload.
702    pub to: Option<String>,
703    pub dry_run: bool,
704    pub json: bool,
705    pub yes: bool,
706    /// D1 bindings whose newer migrations the operator asserts are additive.
707    pub accept_schema_ahead: Vec<String>,
708    /// Accept secret changes between the target and now.
709    pub accept_secret_changes: bool,
710}
711
712/// One Worker's planned revert.
713#[derive(Debug, Serialize)]
714pub(crate) struct WorkerPlan {
715    pub(crate) worker: String,
716    pub(crate) script: String,
717    pub(crate) live_version: String,
718    pub(crate) target_version: String,
719    pub(crate) checks: Vec<Finding>,
720    pub(crate) ok: bool,
721    /// Whether the revert changes this Worker's entry in `bynk.deploy.lock`.
722    pub(crate) lock_changes: bool,
723}
724
725/// The plan `bynk revert --dry-run --format json` prints.
726#[derive(Debug, Serialize)]
727pub(crate) struct RevertPlan {
728    pub(crate) version: u32,
729    pub(crate) environment: String,
730    /// In the order they would be reverted.
731    pub(crate) workers: Vec<WorkerPlan>,
732    pub(crate) ok: bool,
733    /// What to know before confirming: today, that a whole-project revert
734    /// steps every Worker back, whatever the last release touched.
735    pub(crate) notes: Vec<String>,
736}
737
738impl RevertPlan {
739    /// The plan as `bynk revert` prints it, plain.
740    #[cfg(test)]
741    pub(crate) fn render_short(&self) -> String {
742        self.render(false)
743    }
744
745    /// [`Self::render_short`], coloured when `colour` is on: each Worker's
746    /// heading bold, a check's `ok` green and `refused` red, a `warning:` amber
747    /// and a `note:` blue, and the verdict green or red.
748    pub(crate) fn render(&self, colour: bool) -> String {
749        use bynk_driver::colour::{Style, paint};
750        let mut out = String::new();
751        for w in &self.workers {
752            let heading = format!(
753                "revert {} (env {}): {} -> {}",
754                w.worker, self.environment, w.live_version, w.target_version
755            );
756            out.push_str(&format!("{}\n", paint(colour, Style::Bold, &heading)));
757            for f in &w.checks {
758                let mark = if f.is_refusal() {
759                    paint(colour, Style::Red, "refused")
760                } else {
761                    paint(colour, Style::Green, "ok")
762                };
763                let detail = match f.detail.strip_prefix("warning:") {
764                    Some(rest) => format!("{}{rest}", paint(colour, Style::Amber, "warning:")),
765                    None => f.detail.clone(),
766                };
767                out.push_str(&format!(
768                    "  {:<9} {:<14} {mark}: {detail}\n",
769                    f.check, f.subject
770                ));
771            }
772            if w.ok {
773                out.push_str(if w.lock_changes {
774                    "  bynk.deploy.lock: this Worker's contract records change; commit it afterwards\n"
775                } else {
776                    "  bynk.deploy.lock: unchanged\n"
777                });
778            }
779        }
780        for note in &self.notes {
781            out.push_str(&format!("{} {note}\n", paint(colour, Style::Blue, "note:")));
782        }
783        out.push_str(&if self.ok {
784            paint(colour, Style::Green, "Every check passed.")
785        } else {
786            paint(colour, Style::Red, "Refused: nothing was changed.")
787        });
788        out.push('\n');
789        out
790    }
791}
792
793/// A plan with what executing it needs: each Worker's position in its
794/// history and the target's facts.
795pub(crate) struct Planned {
796    pub(crate) plan: RevertPlan,
797    pub(crate) located: BTreeMap<String, Located>,
798    pub(crate) targets: BTreeMap<String, Facts>,
799}
800
801/// Build the plan: locate, read facts, gather what the checks need, evaluate.
802pub(crate) fn plan(
803    api: &dyn Account,
804    lock: &DeployLock,
805    floors: &BTreeMap<String, i64>,
806    workers: &[String],
807    opts: &RevertOptions,
808    now: std::time::SystemTime,
809) -> Result<Planned, String> {
810    let environment = opts.environment.as_str();
811    let mut located = BTreeMap::new();
812    let mut live_facts = BTreeMap::new();
813    let mut target_facts = BTreeMap::new();
814    let mut early: BTreeMap<String, Vec<Finding>> = BTreeMap::new();
815    for worker in workers {
816        let script = deployed_worker_name(environment, &lock.script_of(environment, worker));
817        // Anything that cannot be read or placed for one Worker is that
818        // Worker's refusal, not the run's error.
819        let outcome = (|| -> Result<(Located, Option<Facts>, Option<Facts>), String> {
820            let deployments = api
821                .deployments(&script)
822                .map_err(|e| format!("could not read the deployments: {e}"))?;
823            let loc = locate(&deployments, opts.to.as_deref())?;
824            let read = |version: &str| -> Result<Option<Facts>, String> {
825                Ok(api
826                    .version_facts(&script, version)
827                    .map_err(|e| format!("could not read version `{version}`: {e}"))?
828                    .and_then(|t| Facts::decode(&t)))
829            };
830            let live = read(&loc.live_version)?;
831            let target = read(&loc.target_version)?;
832            Ok((loc, live, target))
833        })();
834        let (loc, live, target) = match outcome {
835            Ok(found) => found,
836            Err(why) => {
837                early.insert(
838                    worker.clone(),
839                    vec![Finding::refused(
840                        "history",
841                        code::HISTORY_UNPLACEABLE,
842                        worker.as_str(),
843                        why,
844                    )],
845                );
846                continue;
847            }
848        };
849        match (live, target) {
850            (Some(l), Some(t)) => {
851                live_facts.insert(worker.clone(), l);
852                target_facts.insert(worker.clone(), t);
853            }
854            (l, t) => {
855                let mut findings = Vec::new();
856                if l.is_none() {
857                    findings.push(Finding::refused(
858                        "facts",
859                        code::FACTS_MISSING,
860                        &loc.live_version,
861                        "the live version records no deploy facts (it predates `bynk revert`, or its record did not fit); redeploy the previous tag instead",
862                    ));
863                }
864                if t.is_none() {
865                    findings.push(Finding::refused(
866                        "facts",
867                        code::FACTS_MISSING,
868                        &loc.target_version,
869                        "the target version records no deploy facts (it predates `bynk revert`, or its record did not fit); redeploy its tag instead",
870                    ));
871                }
872                early.insert(worker.clone(), findings);
873            }
874        }
875        located.insert(worker.clone(), loc);
876    }
877
878    // The ledger as it will stand once every selected Worker is reverted.
879    let mut after = clone_lock(lock);
880    for (worker, target) in &target_facts {
881        apply_target(&mut after, environment, worker, target);
882    }
883
884    let accepted: BTreeSet<String> = opts.accept_schema_ahead.iter().cloned().collect();
885    let mut plans: BTreeMap<String, WorkerPlan> = BTreeMap::new();
886    for worker in workers {
887        let loc = located.get(worker);
888        let script = deployed_worker_name(environment, &lock.script_of(environment, worker));
889        let (checks, lock_changes) = match (loc, live_facts.get(worker), target_facts.get(worker)) {
890            (Some(loc), Some(live), Some(target)) => {
891                let mut applied = BTreeMap::new();
892                for binding in databases_to_read(live, target) {
893                    let result = match live.ids.get(&binding).or_else(|| target.ids.get(&binding)) {
894                        Some(id) => api.applied_migrations(id).map_err(|e| e.to_string()),
895                        None => Err("no database id is recorded for it".to_string()),
896                    };
897                    applied.insert(binding, result);
898                }
899                // An unreadable time cannot show the live code is old enough
900                // for an empty listing to count, so it reads as just deployed.
901                let inside_margin = time::OffsetDateTime::parse(
902                    &loc.live_code_created,
903                    &time::format_description::well_known::Rfc3339,
904                )
905                .ok()
906                .map(std::time::SystemTime::from)
907                .and_then(|settled| now.duration_since(settled).ok())
908                .map(|age| age < SETTLING_MARGIN)
909                .unwrap_or(true);
910                let mut stored = BTreeMap::new();
911                for class in classes_to_probe(live, target) {
912                    let agent = class.rsplit_once('.').map_or(class.as_str(), |(_, a)| a);
913                    let state = match api.has_stored_data(&script, agent) {
914                        Ok(true) => Stored::Present,
915                        Ok(false) if inside_margin => Stored::Unknown(
916                            "the live code was deployed less than 30 minutes ago, and Cloudflare's objects listing lags a write by minutes".into(),
917                        ),
918                        Ok(false) => Stored::None,
919                        Err(e) => Stored::Unknown(e.to_string()),
920                    };
921                    stored.insert(class, state);
922                }
923                let checks = evaluate(&Case {
924                    worker,
925                    environment,
926                    live,
927                    target,
928                    applied: &applied,
929                    stored: &stored,
930                    floors,
931                    after: &after,
932                    lock,
933                    secret_changes: loc.secret_changes,
934                    accept_schema_ahead: &accepted,
935                    accept_secret_changes: opts.accept_secret_changes,
936                });
937                let scratch = with_target_contracts(lock, environment, worker, target);
938                let changed = toml::to_string(&scratch).ok() != toml::to_string(lock).ok();
939                (checks, changed)
940            }
941            _ => (early.remove(worker).unwrap_or_default(), false),
942        };
943        let ok = !checks.is_empty() && checks.iter().all(|f| !f.is_refusal());
944        plans.insert(
945            worker.clone(),
946            WorkerPlan {
947                worker: worker.clone(),
948                script,
949                live_version: loc.map(|l| l.live_version.clone()).unwrap_or_default(),
950                target_version: loc.map(|l| l.target_version.clone()).unwrap_or_default(),
951                checks,
952                ok,
953                lock_changes,
954            },
955        );
956    }
957    let order = revert_order(
958        &target_facts
959            .iter()
960            .map(|(w, f)| (w.clone(), f))
961            .collect::<BTreeMap<_, _>>(),
962        &|dependency: &str| lock.worker_of(environment, dependency),
963    );
964    let mut ordered: Vec<WorkerPlan> = Vec::new();
965    for w in order {
966        if let Some(p) = plans.remove(&w) {
967            ordered.push(p);
968        }
969    }
970    // Workers with no facts have no place in the call graph: list them last.
971    ordered.extend(plans.into_values());
972    let ok = ordered.iter().all(|w| w.ok);
973    Ok(Planned {
974        plan: RevertPlan {
975            version: 1,
976            environment: environment.to_string(),
977            notes: if workers.len() > 1 && opts.context.is_none() {
978                vec!["Every Worker goes back to its own previous deployment, whatever the last release touched. If the last release changed one context, revert just that one with `--context`.".to_string()]
979            } else {
980                Vec::new()
981            },
982            workers: ordered,
983            ok,
984        },
985        located,
986        targets: target_facts,
987    })
988}
989
990/// Why an execution stopped.
991#[derive(Debug, PartialEq, Eq)]
992pub(crate) enum Stopped {
993    /// A Worker's live deployment changed after the plan was made.
994    Moved(String),
995    /// The rollback failed.
996    Failed(String),
997    /// The ledger could not be written after a rollback landed.
998    Unrecorded(String),
999}
1000
1001/// Roll each planned Worker back, in plan order, recording each one in the
1002/// ledger as it lands. Re-reads every Worker's live deployment first and
1003/// refuses if it is no longer the one the plan was made against.
1004pub(crate) fn execute(
1005    api: &dyn Account,
1006    planned: &Planned,
1007    lock: &mut DeployLock,
1008    lock_path: &Path,
1009    environment: &str,
1010    done: &mut Vec<String>,
1011) -> Result<(), Stopped> {
1012    let (plan, located, targets) = (&planned.plan, &planned.located, &planned.targets);
1013    for w in &plan.workers {
1014        let loc = &located[&w.worker];
1015        let current = api.deployments(&w.script).map_err(|e| {
1016            Stopped::Failed(format!(
1017                "could not re-read `{}`'s deployments: {e}",
1018                w.script
1019            ))
1020        })?;
1021        // The newest deployment of any trigger, not only the newest code
1022        // deployment: a secret change made since the plan (a concurrent sweep,
1023        // say) would otherwise be undone by the rollback without a word.
1024        if current.first().map(|d| d.id.as_str()) != Some(loc.live_deployment.as_str()) {
1025            return Err(Stopped::Moved(w.script.clone()));
1026        }
1027        api.rollback(&w.script, &w.target_version)
1028            .map_err(|e| Stopped::Failed(format!("rolling `{}` back failed: {e}", w.script)))?;
1029        done.push(w.worker.clone());
1030        apply_target(lock, environment, &w.worker, &targets[&w.worker]);
1031        write_lock(lock_path, lock)
1032            .map_err(|e| Stopped::Unrecorded(format!("`{}`: {e}", w.script)))?;
1033    }
1034    Ok(())
1035}
1036
1037/// Cloudflare as the live revert sees it.
1038pub(crate) struct LiveAccount<'a> {
1039    pub(crate) rest: Rest,
1040    /// `wrangler rollback`.
1041    pub(crate) api: &'a dyn CloudflareApi,
1042}
1043
1044impl Account for LiveAccount<'_> {
1045    fn deployments(&self, script: &str) -> Result<Vec<Deployment>, CloudflareError> {
1046        let mut out = Vec::new();
1047        crate::cloudflare::paging::Numbered::capped(20).follow(
1048            |page| -> Result<_, CloudflareError> {
1049                let body = self.rest.get(&format!(
1050                    "/workers/scripts/{script}/deployments?per_page=50&page={page}"
1051                ))?;
1052                let items = body["result"]["deployments"]
1053                    .as_array()
1054                    .cloned()
1055                    .unwrap_or_default();
1056                let n = items.len();
1057                for d in items {
1058                    out.push(Deployment {
1059                        id: d["id"].as_str().unwrap_or_default().to_string(),
1060                        created_on: d["created_on"].as_str().unwrap_or_default().to_string(),
1061                        trigger: d["annotations"]["workers/triggered_by"]
1062                            .as_str()
1063                            .map(str::to_string),
1064                        versions: d["versions"]
1065                            .as_array()
1066                            .map(|vs| {
1067                                vs.iter()
1068                                    .filter_map(|v| {
1069                                        Some((
1070                                            v["version_id"].as_str()?.to_string(),
1071                                            v["percentage"].as_f64()?.round() as u32,
1072                                        ))
1073                                    })
1074                                    .collect()
1075                            })
1076                            .unwrap_or_default(),
1077                    });
1078                }
1079                Ok(crate::cloudflare::paging::Page::of(&body, n))
1080            },
1081        )?;
1082        Ok(out)
1083    }
1084
1085    fn version_facts(
1086        &self,
1087        script: &str,
1088        version: &str,
1089    ) -> Result<Option<String>, CloudflareError> {
1090        let body = self
1091            .rest
1092            .get(&format!("/workers/scripts/{script}/versions/{version}"))?;
1093        let bindings = body["result"]["resources"]["bindings"]
1094            .as_array()
1095            .cloned()
1096            .unwrap_or_default();
1097        Ok(bindings
1098            .iter()
1099            .find(|b| b["name"].as_str() == Some(FACTS_VAR))
1100            .and_then(|b| b["text"].as_str())
1101            .map(str::to_string))
1102    }
1103
1104    fn applied_migrations(&self, database_id: &str) -> Result<Vec<String>, CloudflareError> {
1105        let body = self
1106            .rest
1107            .post(
1108                &format!("/d1/database/{database_id}/query"),
1109                &serde_json::json!({ "sql": "SELECT name FROM d1_migrations ORDER BY id" }),
1110                // A `SELECT`: sent again, it reads the same.
1111                crate::cloudflare::Idempotent::Yes,
1112            )
1113            .map_err(|e| -> CloudflareError {
1114                if e.message_mentions("no such table") {
1115                    "the database has no `d1_migrations` table: no migration has been applied to it yet, or it records them under another name; Bynk reads the default table, so this is refused rather than assumed empty".into()
1116                } else {
1117                    e.into()
1118                }
1119            })?;
1120        Ok(body["result"][0]["results"]
1121            .as_array()
1122            .map(|rows| {
1123                rows.iter()
1124                    .filter_map(|r| r["name"].as_str().map(str::to_string))
1125                    .collect()
1126            })
1127            .unwrap_or_default())
1128    }
1129
1130    fn has_stored_data(&self, script: &str, class: &str) -> Result<bool, CloudflareError> {
1131        let namespaces = self.rest.namespaces()?;
1132        match namespaces
1133            .iter()
1134            .find(|n| n.script == script && n.class == class)
1135        {
1136            // No namespace: the class has never stored anything there.
1137            None => Ok(false),
1138            Some(ns) => Ok(!self.rest.stored_objects(&ns.id)?.is_empty()),
1139        }
1140    }
1141
1142    fn rollback(&self, script: &str, version: &str) -> Result<(), CloudflareError> {
1143        // What wrangler wrote to stderr: `rollback` reports there alone.
1144        self.api
1145            .rollback(script, version)
1146            .map_err(|e| CloudflareError::Other(e.stderr_only()))
1147    }
1148}
1149
1150/// `bynk revert`.
1151pub fn revert(root: &Path, opts: &RevertOptions) -> ExitCode {
1152    match revert_run(root, opts) {
1153        Ok(code) => code,
1154        Err(message) => {
1155            emsg!("bynk: error: {message}");
1156            ExitCode::FAILURE
1157        }
1158    }
1159}
1160
1161/// The one Worker `--context` or `--worker` names (#3562). A group is one script,
1162/// so it reverts as a unit and a member cannot be reverted alone: naming one says
1163/// which Worker holds it.
1164fn select_worker(
1165    lock: &DeployLock,
1166    deployed: &[String],
1167    name: &str,
1168    opts: &RevertOptions,
1169) -> Result<String, String> {
1170    let environment = opts.environment.as_str();
1171    let not_recorded =
1172        || format!("`{name}` is not recorded as deployed in environment `{environment}`");
1173    if opts.by_worker {
1174        return deployed
1175            .iter()
1176            .find(|worker| *worker == name)
1177            .cloned()
1178            .ok_or_else(not_recorded);
1179    }
1180    let holder = lock.worker_of(environment, name);
1181    let dashed = name.replace('.', "-");
1182    if holder != dashed {
1183        return Err(format!(
1184            "context `{name}` is in Worker `{holder}`, which reverts as a unit: use `--worker {holder}`"
1185        ));
1186    }
1187    if deployed.contains(&dashed) {
1188        Ok(dashed)
1189    } else {
1190        Err(not_recorded())
1191    }
1192}
1193
1194fn revert_run(root: &Path, opts: &RevertOptions) -> Result<ExitCode, String> {
1195    if opts.to.is_some() && opts.context.is_none() {
1196        return Err(
1197            "`--to` names one Worker's version, so it needs `--context` or `--worker`".to_string(),
1198        );
1199    }
1200    let lock_path = root.join(LOCK_FILE);
1201    let mut lock = read_lock(&lock_path)?;
1202    let mut workers = lock.deployed_workers(&opts.environment);
1203    if let Some(name) = &opts.context {
1204        workers = vec![select_worker(&lock, &workers, name, opts)?];
1205    }
1206    if workers.is_empty() {
1207        return Err(format!(
1208            "bynk.deploy.lock records no deployed Worker in environment `{}`",
1209            opts.environment
1210        ));
1211    }
1212    let floors = schema_floors(root);
1213    let rest = crate::cloudflare::rest::for_purpose("revert", crate::migrate::SWEEP_TOKEN_NEEDS)
1214        .map_err(|e| match e {
1215            CloudflareError::Credentials(missing) => format!(
1216                "{missing}; a revert also reads D1 migrations, so the token needs D1 read access"
1217            ),
1218            other => other.to_string(),
1219        })?;
1220    let probe = probe::detect(
1221        &probe::SystemToolbox,
1222        "wrangler",
1223        probe::DetectOpts {
1224            project_root: Some(root),
1225            allow_npx: true,
1226            manager: Some(bynk_driver::npm_install::system_tool_manager(root)),
1227        },
1228    );
1229    let api = Wrangler::new(&probe.provenance, root);
1230    let account = LiveAccount { rest, api: &api };
1231    let planned = plan(
1232        &account,
1233        &lock,
1234        &floors,
1235        &workers,
1236        opts,
1237        std::time::SystemTime::now(),
1238    )?;
1239    if opts.json {
1240        println!(
1241            "{}",
1242            serde_json::to_string_pretty(&planned.plan).map_err(|e| e.to_string())?
1243        );
1244    } else {
1245        print!("{}", planned.plan.render(bynk_driver::colour::stdout()));
1246    }
1247    if !planned.plan.ok {
1248        return Ok(ExitCode::FAILURE);
1249    }
1250    if opts.dry_run {
1251        return Ok(ExitCode::SUCCESS);
1252    }
1253    if !confirm_revert(opts.yes) {
1254        return Ok(ExitCode::FAILURE);
1255    }
1256    let before = toml::to_string(&lock).ok();
1257    let mut done = Vec::new();
1258    match execute(
1259        &account,
1260        &planned,
1261        &mut lock,
1262        &lock_path,
1263        &opts.environment,
1264        &mut done,
1265    ) {
1266        Ok(()) => {
1267            eprintln!(
1268                "bynk: reverted {} Worker(s): {}",
1269                done.len(),
1270                done.join(", ")
1271            );
1272            if toml::to_string(&lock).ok() != before {
1273                emsg!("bynk: note: bynk.deploy.lock changed; commit it");
1274            }
1275            Ok(ExitCode::SUCCESS)
1276        }
1277        Err(stop) => {
1278            if !done.is_empty() {
1279                emsg!("bynk: already reverted: {}", done.join(", "));
1280            }
1281            Err(match stop {
1282                Stopped::Moved(script) => format!(
1283                    "`{script}` was deployed after the plan was made; nothing further was changed. Plan again."
1284                ),
1285                Stopped::Failed(m) => m,
1286                Stopped::Unrecorded(m) => format!(
1287                    "the rollback landed but bynk.deploy.lock could not be written ({m}); the contracts it records for the reverted Workers are now stale"
1288                ),
1289            })
1290        }
1291    }
1292}
1293
1294/// Each agent class's floor in the checkout's `bynk.schema.lock`; empty
1295/// without one.
1296fn schema_floors(root: &Path) -> BTreeMap<String, i64> {
1297    let Ok(existing) = bynk_driver::schema_lock::read(root) else {
1298        return BTreeMap::new();
1299    };
1300    let Ok(registry) = bynk_project::schema_registry::parse(existing.as_deref(), root) else {
1301        return BTreeMap::new();
1302    };
1303    registry
1304        .agents()
1305        .map(|(class, entry)| (class.clone(), entry.floor))
1306        .collect()
1307}
1308
1309fn confirm_revert(yes: bool) -> bool {
1310    if yes {
1311        return true;
1312    }
1313    if !io::stdin().is_terminal() {
1314        emsg!(
1315            "bynk: error: refusing to change Cloudflare in a non-interactive session without --yes"
1316        );
1317        return false;
1318    }
1319    eprint!("Revert? [y/N] ");
1320    let _ = io::stderr().flush();
1321    let mut answer = String::new();
1322    io::stdin().read_line(&mut answer).is_ok()
1323        && matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes")
1324}
1325
1326#[cfg(test)]
1327mod tests {
1328    use super::*;
1329    use std::cell::RefCell;
1330
1331    fn dep(id: &str, trigger: &str, version: &str) -> Deployment {
1332        Deployment {
1333            id: id.into(),
1334            created_on: "2026-01-01T00:00:00Z".into(),
1335            trigger: Some(trigger.into()),
1336            versions: vec![(version.into(), 100)],
1337        }
1338    }
1339
1340    #[test]
1341    fn the_target_is_what_was_live_just_before_the_live_upload() {
1342        let h = [
1343            dep("d3", "upload", "v3"),
1344            dep("d2", "upload", "v2"),
1345            dep("d1", "upload", "v1"),
1346        ];
1347        let l = locate(&h, None).unwrap();
1348        assert_eq!(
1349            (l.live_version.as_str(), l.target_version.as_str()),
1350            ("v3", "v2")
1351        );
1352        assert_eq!(l.secret_changes, 0);
1353    }
1354
1355    #[test]
1356    fn a_secret_rotation_between_the_uploads_is_kept_not_rolled_back() {
1357        // Newest first: upload v3, secret v2s, upload v2. What was live before the
1358        // bad v3 is v2s (v2's code with the rotated secret), not v2.
1359        let h = [
1360            dep("d3", "upload", "v3"),
1361            dep("d2s", "secret", "v2s"),
1362            dep("d2", "upload", "v2"),
1363        ];
1364        let l = locate(&h, None).unwrap();
1365        assert_eq!(l.target_version, "v2s");
1366        assert_eq!(l.secret_changes, 0, "no secret changed after the target");
1367    }
1368
1369    #[test]
1370    fn a_second_revert_goes_back_past_the_live_upload_not_to_the_bad_release() {
1371        // After reverting v3 -> v2 the list reads rollback->v2, upload v3, v2, v1.
1372        let h = [
1373            dep("d4", "rollback", "v2"),
1374            dep("d3", "upload", "v3"),
1375            dep("d2", "upload", "v2"),
1376            dep("d1", "upload", "v1"),
1377        ];
1378        let l = locate(&h, None).unwrap();
1379        assert_eq!(l.live_version, "v2");
1380        assert_eq!(l.target_version, "v1", "never back to the bad v3");
1381    }
1382
1383    #[test]
1384    fn a_rollback_as_cloudflare_reports_it_is_not_taken_for_an_upload() {
1385        // #3112: a real `wrangler rollback` lists as `workers/triggered_by:
1386        // "deployment"`. Read as an upload, the second revert went to the bad
1387        // release (v2) instead of finding the rollback's own upload (v1).
1388        let h = [
1389            dep("d3", "deployment", "v1"),
1390            dep("d2", "upload", "v2"),
1391            dep("d1", "upload", "v1"),
1392        ];
1393        let l = locate(&h, None);
1394        assert!(
1395            l.unwrap_err().contains("no earlier deployment"),
1396            "v1 is the first upload; nothing precedes it"
1397        );
1398    }
1399
1400    #[test]
1401    fn an_earlier_rollback_before_the_live_upload_is_what_was_live() {
1402        // upload v1, upload v2 (bad), rollback->v1, upload v3: before v3 was v1.
1403        let h = [
1404            dep("d4", "upload", "v3"),
1405            dep("d3", "rollback", "v1"),
1406            dep("d2", "upload", "v2"),
1407            dep("d1", "upload", "v1"),
1408        ];
1409        assert_eq!(locate(&h, None).unwrap().target_version, "v1");
1410    }
1411
1412    #[test]
1413    fn secret_changes_after_the_live_upload_are_counted_and_not_the_live_code() {
1414        let h = [
1415            dep("d4", "secret", "v3s2"),
1416            dep("d3", "secret", "v3s1"),
1417            dep("d2", "upload", "v3"),
1418            dep("d1", "upload", "v2"),
1419        ];
1420        let l = locate(&h, None).unwrap();
1421        assert_eq!(
1422            l.live_version, "v3s2",
1423            "the newest version's facts describe what is live"
1424        );
1425        assert_eq!(l.live_deployment, "d4");
1426        assert_eq!(l.target_version, "v2");
1427        assert_eq!(l.secret_changes, 2);
1428    }
1429
1430    #[test]
1431    fn a_gradual_deployment_or_missing_history_is_refused() {
1432        let mut split = dep("d2", "upload", "v2");
1433        split.versions = vec![("v2".into(), 50), ("v1".into(), 50)];
1434        assert!(
1435            locate(&[split, dep("d1", "upload", "v1")], None)
1436                .unwrap_err()
1437                .contains("gradual")
1438        );
1439        assert!(
1440            locate(&[dep("d1", "upload", "v1")], None)
1441                .unwrap_err()
1442                .contains("no earlier deployment")
1443        );
1444        assert!(locate(&[], None).is_err());
1445    }
1446
1447    #[test]
1448    fn a_version_deployed_outside_bynk_is_refused_with_the_to_hint() {
1449        // #3112: `wrangler versions deploy` and the dashboard record trigger
1450        // `deployment`, the same as a rollback, so the only deployment carrying
1451        // the live version reads as a re-activation and has no upload.
1452        let h = [dep("d2", "deployment", "v2"), dep("d1", "upload", "v1")];
1453        let err = locate(&h, None).unwrap_err();
1454        assert!(err.contains("own upload is out of the listed history"));
1455        assert!(err.contains("--to"), "the refusal names the way out: {err}");
1456        // And it is the way out: `--to` names the earlier version.
1457        assert_eq!(locate(&h, Some("v1")).unwrap().target_version, "v1");
1458    }
1459
1460    #[test]
1461    fn to_names_a_listed_version_and_not_the_live_one() {
1462        let h = [
1463            dep("d3", "upload", "v3"),
1464            dep("d2", "upload", "v2"),
1465            dep("d1", "upload", "v1"),
1466        ];
1467        assert_eq!(locate(&h, Some("v1")).unwrap().target_version, "v1");
1468        assert!(locate(&h, Some("v3")).unwrap_err().contains("already live"));
1469        assert!(locate(&h, Some("nope")).unwrap_err().contains("not among"));
1470    }
1471
1472    // ---- the checks ----
1473
1474    fn facts(mut f: impl FnMut(&mut Facts)) -> Facts {
1475        let mut x = Facts {
1476            v: 1,
1477            ..Default::default()
1478        };
1479        f(&mut x);
1480        x
1481    }
1482
1483    struct Fx {
1484        live: Facts,
1485        target: Facts,
1486        applied: BTreeMap<String, Result<Vec<String>, String>>,
1487        stored: BTreeMap<String, Stored>,
1488        floors: BTreeMap<String, i64>,
1489        lock: DeployLock,
1490        after: DeployLock,
1491        secrets: usize,
1492        schema_ok: BTreeSet<String>,
1493        secrets_ok: bool,
1494    }
1495
1496    impl Fx {
1497        fn new(live: Facts, target: Facts) -> Self {
1498            Fx {
1499                live,
1500                target,
1501                applied: BTreeMap::new(),
1502                stored: BTreeMap::new(),
1503                floors: BTreeMap::new(),
1504                lock: DeployLock::default(),
1505                after: DeployLock::default(),
1506                secrets: 0,
1507                schema_ok: BTreeSet::new(),
1508                secrets_ok: false,
1509            }
1510        }
1511        fn run(&self) -> Vec<Finding> {
1512            evaluate(&Case {
1513                worker: "shop",
1514                environment: "default",
1515                live: &self.live,
1516                target: &self.target,
1517                applied: &self.applied,
1518                stored: &self.stored,
1519                floors: &self.floors,
1520                after: &self.after,
1521                lock: &self.lock,
1522                secret_changes: self.secrets,
1523                accept_schema_ahead: &self.schema_ok,
1524                accept_secret_changes: self.secrets_ok,
1525            })
1526        }
1527    }
1528
1529    #[test]
1530    fn every_refusal_code_is_registered_and_serialised_on_the_finding() {
1531        for c in [
1532            code::FACTS_MISSING,
1533            code::D1_SCHEMA_AHEAD,
1534            code::AGENT_SCHEMA_OLDER,
1535            code::LAYOUT_OLDER,
1536            code::CLASS_CHANGED,
1537            code::CONTRACT_SKEW,
1538            code::ID_UNRECORDED,
1539            code::SECRET_CHANGED,
1540            code::HISTORY_UNPLACEABLE,
1541        ] {
1542            assert!(
1543                bynk_syntax::diagnostics::REGISTRY
1544                    .iter()
1545                    .any(|d| d.code == c),
1546                "`{c}` is not in the diagnostics registry"
1547            );
1548            assert!(
1549                bynk_syntax::diagnostics::explain(c).is_some(),
1550                "`{c}` has no explanation"
1551            );
1552        }
1553        let refused = Finding::refused("secrets", code::SECRET_CHANGED, "shop", "why");
1554        assert_eq!(
1555            serde_json::to_value(&refused).unwrap()["code"],
1556            "bynk.revert.secret_changed"
1557        );
1558        let ok = serde_json::to_value(Finding::ok("secrets", "shop", "fine")).unwrap();
1559        assert!(ok.get("code").is_none(), "a passing check carries no code");
1560    }
1561
1562    fn refusals(findings: &[Finding]) -> Vec<&Finding> {
1563        findings.iter().filter(|f| f.is_refusal()).collect()
1564    }
1565
1566    /// #3477: reverting a Worker whose target carries a container warns that the
1567    /// rollback restores the image for new starts only. It is not a refusal, and
1568    /// a Worker with no container gets no such line.
1569    #[test]
1570    fn a_container_in_the_target_is_warned_about_and_not_refused() {
1571        let with = |classes: &[&str]| {
1572            facts(|f| f.classes = classes.iter().map(|c| c.to_string()).collect())
1573        };
1574        let both = with(&["__Container_Renderer", "Cart"]);
1575        let findings = Fx::new(both.clone(), both).run();
1576        let containers: Vec<&Finding> =
1577            findings.iter().filter(|f| f.check == "container").collect();
1578        assert_eq!(containers.len(), 1, "{findings:?}");
1579        assert_eq!(containers[0].subject, "__Container_Renderer");
1580        assert!(!containers[0].is_refusal());
1581        assert!(
1582            containers[0].detail.contains("new starts only")
1583                || containers[0].detail.contains("for new starts only"),
1584            "{}",
1585            containers[0].detail
1586        );
1587        assert!(
1588            containers[0]
1589                .detail
1590                .contains("keep the image they started with")
1591        );
1592        assert!(refusals(&findings).is_empty());
1593        let plain = with(&["Cart"]);
1594        assert!(
1595            Fx::new(plain.clone(), plain)
1596                .run()
1597                .iter()
1598                .all(|f| f.check != "container")
1599        );
1600    }
1601
1602    #[test]
1603    fn identical_versions_revert_cleanly() {
1604        let f = Fx::new(facts(|_| {}), facts(|_| {}));
1605        assert!(refusals(&f.run()).is_empty(), "{:?}", f.run());
1606    }
1607
1608    fn with_migrations(files: &[&str]) -> Facts {
1609        facts(|f| {
1610            f.migrations.insert(
1611                "D1_ORDERS".into(),
1612                files.iter().map(|s| s.to_string()).collect(),
1613            );
1614            f.ids.insert("D1_ORDERS".into(), "db-1".into());
1615        })
1616    }
1617
1618    #[test]
1619    fn an_applied_migration_the_target_does_not_know_is_refused_and_overridable_per_database() {
1620        let mut f = Fx::new(
1621            with_migrations(&["0001_a.sql", "0002_b.sql"]),
1622            with_migrations(&["0001_a.sql"]),
1623        );
1624        f.applied.insert(
1625            "D1_ORDERS".into(),
1626            Ok(vec!["0001_a.sql".into(), "0002_b.sql".into()]),
1627        );
1628        f.lock.record::<D1>(
1629            "default",
1630            "shop",
1631            "D1_ORDERS",
1632            D1Record::of("shop-orders", "db-1"),
1633        );
1634        let r = f.run();
1635        let d1 = refusals(&r)
1636            .into_iter()
1637            .find(|x| x.check == "d1")
1638            .expect("a d1 refusal");
1639        assert_eq!(d1.code, Some("bynk.revert.database_schema_ahead"));
1640        assert!(
1641            d1.detail.contains("0002_b.sql")
1642                && d1.detail.contains("--accept-schema-ahead D1_ORDERS"),
1643            "{}",
1644            d1.detail
1645        );
1646        f.schema_ok.insert("D1_ORDERS".into());
1647        assert!(refusals(&f.run()).is_empty(), "{:?}", f.run());
1648        // An unread list is a refusal, never a pass.
1649        f.schema_ok.clear();
1650        f.applied.insert("D1_ORDERS".into(), Err("403".into()));
1651        assert!(f.run().iter().any(|x| x.check == "d1"
1652            && x.code == Some("bynk.revert.database_schema_ahead")
1653            && x.is_refusal()
1654            && x.detail.contains("403")));
1655    }
1656
1657    fn with_agent(v: i64) -> Facts {
1658        facts(|f| {
1659            f.agents.insert("shop.Cart".into(), v);
1660            f.classes = vec!["Cart".into()];
1661        })
1662    }
1663
1664    #[test]
1665    fn an_older_target_schema_is_refused_with_stored_data_or_unknown_and_passes_without() {
1666        let mut f = Fx::new(with_agent(3), with_agent(2));
1667        f.stored.insert("shop.Cart".into(), Stored::Present);
1668        assert!(f.run().iter().any(|x| x.check == "agent"
1669            && x.code == Some("bynk.revert.agent_schema_older")
1670            && x.is_refusal()
1671            && x.detail.contains("NewerSchema")));
1672        f.stored
1673            .insert("shop.Cart".into(), Stored::Unknown("lag".into()));
1674        assert!(f.run().iter().any(|x| x.check == "agent"
1675            && x.code == Some("bynk.revert.agent_schema_older")
1676            && x.is_refusal()
1677            && x.detail.contains("not known")));
1678        f.stored.insert("shop.Cart".into(), Stored::None);
1679        assert!(refusals(&f.run()).is_empty());
1680        // The same version, or a newer target, needs no look at the data.
1681        assert!(refusals(&Fx::new(with_agent(2), with_agent(2)).run()).is_empty());
1682    }
1683
1684    fn with_layout(v: i64, layout: i64) -> Facts {
1685        let mut f = with_agent(v);
1686        f.layout = Some(layout);
1687        f
1688    }
1689
1690    #[test]
1691    fn a_target_on_an_older_layout_is_refused_with_stored_data_or_unknown_and_passes_without() {
1692        // Same schema version either side: only the layout differs.
1693        let mut f = Fx::new(with_layout(2, 2), with_agent(2));
1694        f.stored.insert("shop.Cart".into(), Stored::Present);
1695        let found = f.run();
1696        assert!(
1697            found.iter().any(|x| x.check == "layout"
1698                && x.code == Some("bynk.revert.layout_older")
1699                && x.is_refusal()
1700                && x.detail.contains("NewerLayout")),
1701            "{found:?}"
1702        );
1703        f.stored
1704            .insert("shop.Cart".into(), Stored::Unknown("lag".into()));
1705        assert!(f.run().iter().any(|x| x.check == "layout"
1706            && x.code == Some("bynk.revert.layout_older")
1707            && x.is_refusal()
1708            && x.detail.contains("not known")));
1709        f.stored.remove("shop.Cart");
1710        assert!(
1711            f.run()
1712                .iter()
1713                .any(|x| x.check == "layout" && x.is_refusal() && x.detail.contains("not read"))
1714        );
1715        f.stored.insert("shop.Cart".into(), Stored::None);
1716        assert!(refusals(&f.run()).is_empty());
1717    }
1718
1719    #[test]
1720    fn the_layout_checks_are_silent_when_the_target_is_not_older() {
1721        // The same layout, or a newer target (the upgrade direction), needs no look at the data.
1722        for (live, target) in [
1723            (with_agent(2), with_agent(2)),
1724            (with_layout(2, 2), with_layout(2, 2)),
1725            (with_agent(2), with_layout(2, 2)),
1726        ] {
1727            let found = Fx::new(live, target).run();
1728            assert!(refusals(&found).is_empty(), "{found:?}");
1729            assert!(found.iter().all(|x| x.check != "layout"));
1730        }
1731    }
1732
1733    #[test]
1734    fn a_layout_difference_makes_every_shared_class_probed_for_stored_data() {
1735        let live = with_layout(2, 2);
1736        let target = with_agent(2);
1737        assert_eq!(
1738            classes_to_probe(&live, &target),
1739            BTreeSet::from(["shop.Cart".to_string()])
1740        );
1741        // Without the layout difference the same schema version needs no probe.
1742        assert!(classes_to_probe(&with_agent(2), &with_agent(2)).is_empty());
1743    }
1744
1745    #[test]
1746    fn a_target_below_the_floor_or_a_changed_class_set_is_refused() {
1747        let mut f = Fx::new(with_agent(4), with_agent(2));
1748        f.stored.insert("shop.Cart".into(), Stored::None);
1749        f.floors.insert("shop.Cart".into(), 3);
1750        assert!(f.run().iter().any(|x| x.check == "agent"
1751            && x.code == Some("bynk.revert.agent_schema_older")
1752            && x.detail.contains("floor v3")));
1753        let added = Fx::new(
1754            facts(|f| f.classes = vec!["Cart".into(), "Wishlist".into()]),
1755            facts(|f| f.classes = vec!["Cart".into()]),
1756        );
1757        assert!(added.run().iter().any(|x| x.check == "classes"
1758            && x.code == Some("bynk.revert.class_changed")
1759            && x.detail.contains("Wishlist")));
1760    }
1761
1762    #[test]
1763    fn contract_skew_against_another_live_worker_is_refused_using_the_post_revert_ledger() {
1764        // The target of `shop` expects `pay.charge` at `old`; `pay` is live at `new`.
1765        let target = facts(|f| {
1766            f.expects.insert(
1767                "pay".into(),
1768                BTreeMap::from([("charge".into(), "old".into())]),
1769            );
1770        });
1771        let mut after = DeployLock::default();
1772        after.record_deployed(
1773            "default",
1774            "pay",
1775            Some(BTreeMap::from([("charge".into(), "new".into())])),
1776        );
1777        let mut f = Fx::new(facts(|_| {}), target);
1778        f.after = after;
1779        let r = f.run();
1780        let c = refusals(&r)
1781            .into_iter()
1782            .find(|x| x.check == "contracts")
1783            .expect("a contract refusal");
1784        assert_eq!(c.code, Some("bynk.revert.contract_skew"));
1785        assert!(
1786            c.detail.contains("pay.charge") && c.detail.contains("old") && c.detail.contains("new"),
1787            "{}",
1788            c.detail
1789        );
1790        // When `pay` is reverted too, the post-revert ledger agrees and the skew is gone.
1791        let mut both = DeployLock::default();
1792        both.record_deployed(
1793            "default",
1794            "pay",
1795            Some(BTreeMap::from([("charge".into(), "old".into())])),
1796        );
1797        f.after = both;
1798        assert!(refusals(&f.run()).is_empty());
1799    }
1800
1801    /// #3970: a version bound to a Hyperdrive config the ledger has since replaced is refused,
1802    /// as a replaced KV namespace is.
1803    #[test]
1804    fn a_replaced_hyperdrive_config_id_is_refused() {
1805        // The target version bound `id-1`, which `build_facts` recorded.
1806        let target = facts(|f| {
1807            f.ids.insert("HYPERDRIVE_MAIN".into(), "id-1".into());
1808        });
1809        let mut f = Fx::new(facts(|_| {}), target);
1810        f.lock.record::<Hyperdrive>(
1811            "default",
1812            "shop",
1813            "HYPERDRIVE_MAIN",
1814            HyperdriveRecord {
1815                name: "shop-main".into(),
1816                id: "id-2".into(),
1817                adopted: false,
1818                superseded: Vec::new(),
1819            },
1820        );
1821        assert!(f.run().iter().any(|x| x.check == "ids"
1822            && x.code == Some("bynk.revert.id_unrecorded")
1823            && x.is_refusal()
1824            && x.detail.contains("id-1")
1825            && x.detail.contains("id-2")));
1826        // The config the ledger records now is the one the target bound: nothing to refuse.
1827        let mut same = Fx::new(
1828            facts(|_| {}),
1829            facts(|f| {
1830                f.ids.insert("HYPERDRIVE_MAIN".into(), "id-2".into());
1831            }),
1832        );
1833        same.lock.record::<Hyperdrive>(
1834            "default",
1835            "shop",
1836            "HYPERDRIVE_MAIN",
1837            HyperdriveRecord {
1838                name: "shop-main".into(),
1839                id: "id-2".into(),
1840                adopted: false,
1841                superseded: Vec::new(),
1842            },
1843        );
1844        assert!(
1845            !same
1846                .run()
1847                .iter()
1848                .any(|x| x.check == "ids" && x.is_refusal())
1849        );
1850    }
1851
1852    #[test]
1853    fn a_replaced_resource_id_is_refused() {
1854        let target = facts(|f| {
1855            f.ids.insert("KV".into(), "kv-old".into());
1856        });
1857        let mut f = Fx::new(facts(|_| {}), target);
1858        f.lock
1859            .record::<Kv>("default", "shop", "KV", KvNamespace::of("kv-new"));
1860        assert!(f.run().iter().any(|x| x.check == "ids"
1861            && x.code == Some("bynk.revert.id_unrecorded")
1862            && x.is_refusal()
1863            && x.detail.contains("kv-old")
1864            && x.detail.contains("kv-new")));
1865        let mut g = Fx::new(
1866            facts(|_| {}),
1867            facts(|f| {
1868                f.ids.insert("KV".into(), "kv-1".into());
1869            }),
1870        );
1871        g.lock
1872            .record::<Kv>("default", "shop", "KV", KvNamespace::of("kv-1"));
1873        assert!(refusals(&g.run()).is_empty());
1874    }
1875
1876    #[test]
1877    fn secret_changes_since_the_target_are_refused_unless_accepted() {
1878        let mut f = Fx::new(facts(|_| {}), facts(|_| {}));
1879        f.secrets = 2;
1880        assert!(f.run().iter().any(|x| x.check == "secrets"
1881            && x.code == Some("bynk.revert.secret_changed")
1882            && x.is_refusal()));
1883        f.secrets_ok = true;
1884        assert!(refusals(&f.run()).is_empty());
1885    }
1886
1887    #[test]
1888    fn callers_are_reverted_before_the_callees_they_call() {
1889        let shop = facts(|f| {
1890            f.expects.insert("pay".into(), BTreeMap::new());
1891        });
1892        let pay = facts(|_| {});
1893        let map = BTreeMap::from([("pay".to_string(), &pay), ("shop".to_string(), &shop)]);
1894        assert_eq!(
1895            revert_order(&map, &|c: &str| c.replace('.', "-")),
1896            ["shop", "pay"]
1897        );
1898    }
1899
1900    // ---- plan and execution against a fake account ----
1901
1902    #[derive(Default)]
1903    struct Fake {
1904        deployments: RefCell<BTreeMap<String, Vec<Deployment>>>,
1905        facts: BTreeMap<(String, String), String>,
1906        rolled: RefCell<Vec<(String, String)>>,
1907        /// Push a newer deployment when `deployments` is read this many times.
1908        move_after_reads: Option<usize>,
1909        reads: RefCell<usize>,
1910    }
1911
1912    impl Account for Fake {
1913        fn deployments(
1914            &self,
1915            script: &str,
1916        ) -> Result<Vec<Deployment>, crate::cloudflare::CloudflareError> {
1917            *self.reads.borrow_mut() += 1;
1918            if self
1919                .move_after_reads
1920                .is_some_and(|n| *self.reads.borrow() > n)
1921            {
1922                self.deployments
1923                    .borrow_mut()
1924                    .get_mut(script)
1925                    .unwrap()
1926                    .insert(0, dep("dX", "upload", "vX"));
1927            }
1928            self.deployments
1929                .borrow()
1930                .get(script)
1931                .cloned()
1932                .ok_or_else(|| "no such Worker".into())
1933        }
1934        fn version_facts(
1935            &self,
1936            script: &str,
1937            version: &str,
1938        ) -> Result<Option<String>, crate::cloudflare::CloudflareError> {
1939            Ok(self
1940                .facts
1941                .get(&(script.to_string(), version.to_string()))
1942                .cloned())
1943        }
1944        fn applied_migrations(
1945            &self,
1946            _: &str,
1947        ) -> Result<Vec<String>, crate::cloudflare::CloudflareError> {
1948            Ok(vec![])
1949        }
1950        fn has_stored_data(
1951            &self,
1952            _: &str,
1953            _: &str,
1954        ) -> Result<bool, crate::cloudflare::CloudflareError> {
1955            Ok(false)
1956        }
1957        fn rollback(
1958            &self,
1959            script: &str,
1960            version: &str,
1961        ) -> Result<(), crate::cloudflare::CloudflareError> {
1962            self.rolled
1963                .borrow_mut()
1964                .push((script.into(), version.into()));
1965            Ok(())
1966        }
1967    }
1968
1969    fn account(live: &Facts, target: Option<&Facts>) -> Fake {
1970        let mut fake = Fake::default();
1971        fake.deployments.borrow_mut().insert(
1972            "shop".into(),
1973            vec![dep("d2", "upload", "v2"), dep("d1", "upload", "v1")],
1974        );
1975        fake.facts
1976            .insert(("shop".into(), "v2".into()), live.encode().unwrap());
1977        if let Some(t) = target {
1978            fake.facts
1979                .insert(("shop".into(), "v1".into()), t.encode().unwrap());
1980        }
1981        fake
1982    }
1983
1984    fn opts() -> RevertOptions {
1985        RevertOptions {
1986            environment: "default".into(),
1987            ..Default::default()
1988        }
1989    }
1990
1991    fn long_ago() -> std::time::SystemTime {
1992        std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(4_000_000_000)
1993    }
1994
1995    fn lock_with_shop() -> DeployLock {
1996        let mut lock: DeployLock = toml::from_str("version = 1\n").unwrap();
1997        lock.record_deployed("default", "shop", Some(BTreeMap::new()));
1998        lock
1999    }
2000
2001    #[test]
2002    fn a_clean_revert_plans_ok_and_rolls_back_with_the_lock_recorded() {
2003        let live = facts(|f| {
2004            f.provides.insert("quote".into(), "new".into());
2005        });
2006        let target = facts(|f| {
2007            f.provides.insert("quote".into(), "old".into());
2008        });
2009        let api = account(&live, Some(&target));
2010        let mut lock = lock_with_shop();
2011        let planned = plan(
2012            &api,
2013            &lock,
2014            &BTreeMap::new(),
2015            &["shop".to_string()],
2016            &opts(),
2017            long_ago(),
2018        )
2019        .unwrap();
2020        let plan = &planned.plan;
2021        assert!(plan.ok, "{}", plan.render_short());
2022        assert!(plan.workers[0].lock_changes, "the contract record differs");
2023        // Coloured, the same plan: the heading bold, each check green, the
2024        // verdict green; plain, no escapes.
2025        let coloured = plan.render(true);
2026        assert!(coloured.starts_with("\x1b[1mrevert shop "), "{coloured}");
2027        assert!(coloured.contains(" \x1b[32mok\x1b[39m: "), "{coloured}");
2028        assert!(
2029            coloured.ends_with("\x1b[32mEvery check passed.\x1b[39m\n"),
2030            "{coloured}"
2031        );
2032        assert!(!plan.render(false).contains('\x1b'));
2033        let dir = std::env::temp_dir().join(format!("bynk-revert-{}", std::process::id()));
2034        std::fs::create_dir_all(&dir).unwrap();
2035        let path = dir.join("bynk.deploy.lock");
2036        let mut done = Vec::new();
2037        execute(&api, &planned, &mut lock, &path, "default", &mut done).unwrap();
2038        assert_eq!(
2039            *api.rolled.borrow(),
2040            [("shop".to_string(), "v1".to_string())]
2041        );
2042        assert_eq!(done, ["shop"]);
2043        let written = read_lock(&path).unwrap();
2044        assert_eq!(
2045            written.live_contracts("default", "shop").unwrap()["quote"],
2046            "old"
2047        );
2048        let _ = std::fs::remove_dir_all(dir);
2049    }
2050
2051    #[test]
2052    fn a_version_without_facts_is_refused_and_nothing_is_rolled_back() {
2053        let live = facts(|_| {});
2054        let api = account(&live, None);
2055        let lock = lock_with_shop();
2056        let Planned { plan, .. } = plan(
2057            &api,
2058            &lock,
2059            &BTreeMap::new(),
2060            &["shop".to_string()],
2061            &opts(),
2062            long_ago(),
2063        )
2064        .unwrap();
2065        assert!(!plan.ok);
2066        assert!(plan.workers[0].checks.iter().any(|f| f.check == "facts"
2067            && f.code == Some("bynk.revert.facts_missing")
2068            && f.detail.contains("redeploy")));
2069        assert!(api.rolled.borrow().is_empty());
2070        // And a live version without facts is refused alike.
2071        let mut none = account(&live, Some(&live));
2072        none.facts.remove(&("shop".to_string(), "v2".to_string()));
2073        let Planned { plan, .. } = self::plan(
2074            &none,
2075            &lock,
2076            &BTreeMap::new(),
2077            &["shop".to_string()],
2078            &opts(),
2079            long_ago(),
2080        )
2081        .unwrap();
2082        assert!(!plan.ok);
2083    }
2084
2085    #[test]
2086    fn live_code_deployed_inside_the_settling_margin_makes_stored_data_unknown() {
2087        let live = with_agent(3);
2088        let target = with_agent(2);
2089        let api = account(&live, Some(&target));
2090        let lock = lock_with_shop();
2091        let just_after =
2092            std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_767_225_600 + 60); // 2026-01-01T00:01:00Z
2093        let Planned { plan, .. } = plan(
2094            &api,
2095            &lock,
2096            &BTreeMap::new(),
2097            &["shop".to_string()],
2098            &opts(),
2099            just_after,
2100        )
2101        .unwrap();
2102        assert!(!plan.ok);
2103        assert!(
2104            plan.workers[0]
2105                .checks
2106                .iter()
2107                .any(|f| f.check == "agent" && f.detail.contains("not known"))
2108        );
2109        let Planned { plan, .. } = plan_at(&api, &lock, long_ago());
2110        assert!(plan.ok, "settled and empty: {}", plan.render_short());
2111    }
2112
2113    fn plan_at(api: &Fake, lock: &DeployLock, now: std::time::SystemTime) -> Planned {
2114        plan(
2115            api,
2116            lock,
2117            &BTreeMap::new(),
2118            &["shop".to_string()],
2119            &opts(),
2120            now,
2121        )
2122        .unwrap()
2123    }
2124
2125    #[test]
2126    fn a_deploy_that_lands_mid_revert_stops_it_before_the_rollback() {
2127        let live = facts(|_| {});
2128        let mut api = account(&live, Some(&live));
2129        let mut lock = lock_with_shop();
2130        let planned = plan_at(&api, &lock, long_ago());
2131        assert!(planned.plan.ok);
2132        api.move_after_reads = Some(*api.reads.borrow());
2133        let dir = std::env::temp_dir().join(format!("bynk-revert-moved-{}", std::process::id()));
2134        std::fs::create_dir_all(&dir).unwrap();
2135        let mut done = Vec::new();
2136        let stopped = execute(
2137            &api,
2138            &planned,
2139            &mut lock,
2140            &dir.join("bynk.deploy.lock"),
2141            "default",
2142            &mut done,
2143        )
2144        .unwrap_err();
2145        assert_eq!(stopped, Stopped::Moved("shop".into()));
2146        assert!(api.rolled.borrow().is_empty() && done.is_empty());
2147        let _ = std::fs::remove_dir_all(dir);
2148    }
2149
2150    #[test]
2151    fn the_json_plan_is_pinned() {
2152        let live = facts(|_| {});
2153        let api = account(&live, Some(&live));
2154        let lock = lock_with_shop();
2155        let Planned { plan, .. } = plan_at(&api, &lock, long_ago());
2156        let json = serde_json::to_string_pretty(&plan).unwrap();
2157        assert_eq!(
2158            json,
2159            r#"{
2160  "version": 1,
2161  "environment": "default",
2162  "workers": [
2163    {
2164      "worker": "shop",
2165      "script": "shop",
2166      "live_version": "v2",
2167      "target_version": "v1",
2168      "checks": [
2169        {
2170          "check": "contracts",
2171          "subject": "shop",
2172          "verdict": "ok",
2173          "detail": "no skew against the other live Workers"
2174        },
2175        {
2176          "check": "ids",
2177          "subject": "shop",
2178          "verdict": "ok",
2179          "detail": "every bound resource is the one the ledger records"
2180        },
2181        {
2182          "check": "secrets",
2183          "subject": "shop",
2184          "verdict": "ok",
2185          "detail": "no secret change since the target"
2186        }
2187      ],
2188      "ok": true,
2189      "lock_changes": true
2190    }
2191  ],
2192  "ok": true,
2193  "notes": []
2194}"#
2195        );
2196    }
2197
2198    #[test]
2199    fn a_secret_change_made_after_the_plan_stops_the_revert_too() {
2200        let live = facts(|_| {});
2201        let api = account(&live, Some(&live));
2202        let mut lock = lock_with_shop();
2203        let planned = plan_at(&api, &lock, long_ago());
2204        assert!(planned.plan.ok);
2205        // A concurrent `bynk migrate sweep` (or any secret put) lands.
2206        api.deployments
2207            .borrow_mut()
2208            .get_mut("shop")
2209            .unwrap()
2210            .insert(0, dep("dS", "secret", "v2s"));
2211        let dir = std::env::temp_dir().join(format!("bynk-revert-secret-{}", std::process::id()));
2212        std::fs::create_dir_all(&dir).unwrap();
2213        let mut done = Vec::new();
2214        let stopped = execute(
2215            &api,
2216            &planned,
2217            &mut lock,
2218            &dir.join("bynk.deploy.lock"),
2219            "default",
2220            &mut done,
2221        )
2222        .unwrap_err();
2223        assert_eq!(stopped, Stopped::Moved("shop".into()));
2224        assert!(api.rolled.borrow().is_empty());
2225        let _ = std::fs::remove_dir_all(dir);
2226    }
2227
2228    #[test]
2229    fn a_worker_that_cannot_be_placed_is_a_refusal_not_an_error_for_the_run() {
2230        // `pay` was first added in the bad release: nothing precedes it.
2231        let live = facts(|_| {});
2232        let api = account(&live, Some(&live));
2233        api.deployments
2234            .borrow_mut()
2235            .insert("pay".into(), vec![dep("p1", "upload", "pv1")]);
2236        let mut lock = lock_with_shop();
2237        lock.record_deployed("default", "pay", Some(BTreeMap::new()));
2238        let planned = plan(
2239            &api,
2240            &lock,
2241            &BTreeMap::new(),
2242            &["pay".to_string(), "shop".to_string()],
2243            &opts(),
2244            long_ago(),
2245        )
2246        .unwrap();
2247        assert!(!planned.plan.ok);
2248        let pay = planned
2249            .plan
2250            .workers
2251            .iter()
2252            .find(|w| w.worker == "pay")
2253            .unwrap();
2254        assert!(pay.checks.iter().any(|f| f.check == "history"
2255            && f.code == Some("bynk.revert.history_unplaceable")
2256            && f.detail.contains("no earlier deployment")));
2257        let shop = planned
2258            .plan
2259            .workers
2260            .iter()
2261            .find(|w| w.worker == "shop")
2262            .unwrap();
2263        assert!(shop.ok, "the other Worker is still judged on its own");
2264        assert!(planned.plan.notes[0].contains("--context"));
2265    }
2266
2267    #[test]
2268    fn to_needs_a_context() {
2269        let dir = std::env::temp_dir().join(format!("bynk-revert-to-{}", std::process::id()));
2270        std::fs::create_dir_all(&dir).unwrap();
2271        let err = revert_run(
2272            &dir,
2273            &RevertOptions {
2274                environment: "default".into(),
2275                to: Some("v1".into()),
2276                ..Default::default()
2277            },
2278        )
2279        .unwrap_err();
2280        assert!(err.contains("--context"), "{err}");
2281        let _ = std::fs::remove_dir_all(dir);
2282    }
2283
2284    /// #3562: a group is one script, so it reverts as a unit: selected by its key,
2285    /// and a member named alone is refused with the Worker that holds it.
2286    #[test]
2287    fn a_group_reverts_as_a_unit_and_a_member_alone_is_refused() {
2288        let mut lock = lock_with_shop();
2289        lock.record_deployed("default", "core", Some(BTreeMap::new()));
2290        lock.record_members(
2291            "default",
2292            "core",
2293            &["shop.a".to_string(), "shop.b".to_string()],
2294        );
2295        let deployed = lock.deployed_workers("default");
2296        let by = |name: &str, by_worker: bool| {
2297            let opts = RevertOptions {
2298                context: Some(name.into()),
2299                by_worker,
2300                ..opts()
2301            };
2302            select_worker(&lock, &deployed, name, &opts)
2303        };
2304        assert_eq!(by("core", true).unwrap(), "core");
2305        assert_eq!(by("shop", false).unwrap(), "shop", "a context's own Worker");
2306        for member in ["shop.a", "shop-a"] {
2307            let err = by(member, false).unwrap_err();
2308            assert!(
2309                err.contains("is in Worker `core`, which reverts as a unit")
2310                    && err.contains("--worker core"),
2311                "{err}"
2312            );
2313        }
2314        assert!(
2315            by("nope", true)
2316                .unwrap_err()
2317                .contains("not recorded as deployed")
2318        );
2319    }
2320
2321    /// #3562: a dependency is found under the group's Worker, so callers revert
2322    /// before the group they call and an intra-group call is not a dependency.
2323    #[test]
2324    fn a_dependency_in_a_group_orders_by_its_worker() {
2325        let mut lock = DeployLock::default();
2326        lock.record_deployed("default", "core", Some(BTreeMap::new()));
2327        lock.record_members("default", "core", &["shop.a".to_string()]);
2328        let shop = facts(|f| {
2329            f.expects.insert("shop.a".into(), BTreeMap::new());
2330        });
2331        let core = facts(|_| {});
2332        let map = BTreeMap::from([("core".to_string(), &core), ("shop".to_string(), &shop)]);
2333        assert_eq!(
2334            revert_order(&map, &|c: &str| lock.worker_of("default", c)),
2335            ["shop", "core"]
2336        );
2337    }
2338
2339    fn group_account(live: &Facts, target: &Facts, script: &str) -> Fake {
2340        let mut fake = Fake::default();
2341        fake.deployments.borrow_mut().insert(
2342            script.into(),
2343            vec![dep("d2", "upload", "v2"), dep("d1", "upload", "v1")],
2344        );
2345        fake.facts
2346            .insert((script.into(), "v2".into()), live.encode().unwrap());
2347        fake.facts
2348            .insert((script.into(), "v1".into()), target.encode().unwrap());
2349        fake
2350    }
2351
2352    fn group_lock(script: &str) -> DeployLock {
2353        let mut lock: DeployLock = toml::from_str("version = 1\n").unwrap();
2354        lock.record_deployed("default", "core", Some(BTreeMap::new()));
2355        lock.record_members(
2356            "default",
2357            "core",
2358            &["shop.a".to_string(), "shop.b".to_string()],
2359        );
2360        lock.record_script("default", "core", script);
2361        lock
2362    }
2363
2364    /// #3562: a renamed group is read and rolled back under its script name, not
2365    /// its key. The fake account knows only the script.
2366    #[test]
2367    fn a_renamed_group_is_rolled_back_under_its_script_name() {
2368        let members = || {
2369            facts(|f| {
2370                f.contexts = vec!["shop.a".into(), "shop.b".into()];
2371            })
2372        };
2373        let (live, target) = (members(), members());
2374        let api = group_account(&live, &target, "core-script");
2375        let lock = group_lock("core-script");
2376        let planned = plan(
2377            &api,
2378            &lock,
2379            &BTreeMap::new(),
2380            &["core".to_string()],
2381            &opts(),
2382            long_ago(),
2383        )
2384        .unwrap();
2385        assert!(planned.plan.ok, "{:?}", planned.plan.workers[0].checks);
2386        assert_eq!(planned.plan.workers[0].script, "core-script");
2387        // Keyed by the key, the account has no such script: that is the regression.
2388        let wrong = group_lock("core");
2389        let refused = plan(
2390            &api,
2391            &wrong,
2392            &BTreeMap::new(),
2393            &["core".to_string()],
2394            &opts(),
2395            long_ago(),
2396        )
2397        .unwrap();
2398        assert!(!refused.plan.ok);
2399        let coloured = refused.plan.render(true);
2400        assert!(
2401            coloured.contains(" \x1b[31mrefused\x1b[39m: "),
2402            "{coloured}"
2403        );
2404        assert!(
2405            coloured.ends_with("\x1b[31mRefused: nothing was changed.\x1b[39m\n"),
2406            "{coloured}"
2407        );
2408    }
2409
2410    /// #3562: a group goes back only to a version that held the same contexts.
2411    #[test]
2412    fn a_group_is_not_reverted_across_a_membership_change() {
2413        let live = facts(|f| {
2414            f.contexts = vec!["shop.a".into(), "shop.b".into()];
2415        });
2416        let moved_in = facts(|f| {
2417            f.contexts = vec!["shop.a".into()];
2418        });
2419        let before_groups = facts(|_| {});
2420        for target in [&moved_in, &before_groups] {
2421            let api = group_account(&live, target, "core");
2422            let lock = group_lock("core");
2423            let Planned { plan, .. } = plan(
2424                &api,
2425                &lock,
2426                &BTreeMap::new(),
2427                &["core".to_string()],
2428                &opts(),
2429                long_ago(),
2430            )
2431            .unwrap();
2432            assert!(!plan.ok);
2433            let finding = plan.workers[0]
2434                .checks
2435                .iter()
2436                .find(|f| f.check == "members")
2437                .expect("a membership finding");
2438            assert_eq!(finding.code, Some("bynk.revert.membership_changed"));
2439            assert!(finding.detail.contains("shop.b"), "{}", finding.detail);
2440            assert!(api.rolled.borrow().is_empty());
2441        }
2442    }
2443}