Skip to main content

dort_core/
batch_execution.rs

1//! Schema-4 guarded execution and whole-transaction rollback.
2pub use crate::adoption::{Boundary, Event};
3use crate::{
4    Error, Manifest, Result,
5    adoption::{self, anchors, checked_bytes, parent_identity, same},
6    batch::{self, Action, Approval},
7    batch_journal::{self as wire, Header, Journal, Mutation, Operation, Role, Watch},
8    context::HostContext,
9    error::io_error,
10    journal::{self, Phase, Progress},
11    observation::{self, Entry, Fingerprint, Kind},
12    planner::{self, Outcome, Request, UnmanageMode},
13    state::WriterLock,
14};
15use rustix::fs::{self, Mode, OFlags, RenameFlags};
16use std::{
17    fs::File,
18    path::{Path, PathBuf},
19};
20fn stage_name(id: usize) -> String {
21    format!("op-{id:04}")
22}
23fn stage_path(j: &Journal, id: usize) -> PathBuf {
24    j.directory.path.join(stage_name(id))
25}
26fn inspect(path: &Path, role: Role) -> Result<Entry> {
27    if role == Role::Manifest && observation::inspect(path, false)?.kind == Kind::Regular {
28        observation::read_manifest(path).map(|(_, e)| e)
29    } else {
30        observation::inspect(path, true)
31    }
32}
33fn notify(
34    j: &Journal,
35    boundary: Boundary,
36    observer: &mut impl FnMut(&Event) -> Result<()>,
37) -> Result<()> {
38    observer(&Event {
39        transaction_id: j.record.header.transaction_id.clone(),
40        boundary,
41        sequence: j.record.sequence,
42    })
43}
44fn checkpoint(j: &mut Journal, observer: &mut impl FnMut(&Event) -> Result<()>) -> Result<()> {
45    j.save()?;
46    notify(j, Boundary::Checkpoint, observer)
47}
48fn stage_file(j: &Journal, id: usize, bytes: &[u8], fp: &Fingerprint) -> Result<()> {
49    let name = stage_name(id);
50    j.directory.create(&name, bytes)?;
51    let file = File::from(
52        fs::openat(
53            &j.directory.file,
54            name.as_str(),
55            OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
56            Mode::empty(),
57        )
58        .map_err(|e| io_error("open batch preparation", &j.directory.path, e))?,
59    );
60    fs::fchown(&file, None, Some(rustix::process::Gid::from_raw(fp.gid)))
61        .map_err(|e| io_error("preserve prepared group", &j.directory.path, e))?;
62    fs::fchmod(&file, Mode::from_bits_truncate((fp.mode & 0o777) as _))
63        .map_err(|e| io_error("preserve prepared permissions", &j.directory.path, e))?;
64    file.sync_all()
65        .map_err(|e| io_error("sync batch preparation", &j.directory.path, e))?;
66    j.directory.sync()
67}
68
69/// Parsed tables carry document-global positions. Discard positions imported
70/// from the separate addition document so normal insertion order is used.
71/// The full semantic equality check below remains authoritative.
72fn clear_imported_positions(table: &mut toml_edit::Table) {
73    table.set_position(None);
74    for (_, item) in table.iter_mut() {
75        match item {
76            toml_edit::Item::Table(child) => clear_imported_positions(child),
77            toml_edit::Item::ArrayOfTables(children) => {
78                for child in children.iter_mut() {
79                    clear_imported_positions(child);
80                }
81            }
82            _ => (),
83        }
84    }
85}
86fn edit_manifest(bytes: &[u8], h: &Header, host: &HostContext) -> Result<Option<Vec<u8>>> {
87    if h.action == Action::Apply {
88        return Ok(None);
89    }
90    if h.action != Action::Adopt {
91        let mut edited = bytes.to_vec();
92        for w in &h.watches {
93            edited = crate::lifecycle::remove_mapping(
94                &edited,
95                &w.mapping.id,
96                host,
97                &h.repository,
98                &h.profiles,
99            )?;
100        }
101        return Ok(Some(edited));
102    }
103    let text =
104        std::str::from_utf8(bytes).map_err(|_| Error::Invalid("manifest must be UTF-8".into()))?;
105    let mut expected = Manifest::parse(text)?;
106    let mappings: Vec<_> = h.watches.iter().map(|w| w.mapping.clone()).collect();
107    batch::validate_adoptions(
108        &mut expected,
109        &mappings,
110        host,
111        &h.profiles.iter().cloned().collect(),
112        &h.repository,
113    )?;
114    #[derive(serde::Serialize)]
115    struct Addition<'a> {
116        files: &'a [crate::model::ManagedFile],
117    }
118    let added = toml::to_string(&Addition { files: &mappings })
119        .map_err(|_| Error::Invalid("cannot encode batch mappings".into()))?
120        .parse::<toml_edit::DocumentMut>()
121        .map_err(|_| Error::Invalid("cannot encode batch mapping tables".into()))?;
122    let expected = journal::encode(&expected)?;
123    // Keep every previously successful edit byte-for-byte: recovery binds the
124    // edited-manifest digest in existing schema-4 headers. Only retry an edit
125    // rejected by the original semantic guard, never relax that guard.
126    for reset_positions in [false, true] {
127        let mut doc = text
128            .parse::<toml_edit::DocumentMut>()
129            .map_err(|_| Error::Invalid("cannot edit manifest".into()))?;
130        let mut tables = added["files"]
131            .as_array_of_tables()
132            .ok_or_else(|| Error::Invalid("cannot encode batch mapping tables".into()))?
133            .clone();
134        if reset_positions {
135            for table in tables.iter_mut() {
136                clear_imported_positions(table);
137            }
138        }
139        if doc.get("files").is_none() {
140            doc["files"] = toml_edit::Item::ArrayOfTables(tables);
141        } else if let Some(array) = doc["files"].as_array_of_tables_mut() {
142            for table in &tables {
143                array.push(table.clone());
144            }
145        } else if let Some(array) = doc["files"].as_array_mut() {
146            for table in &tables {
147                array.push(table.clone().into_inline_table());
148            }
149        } else {
150            return Err(Error::Invalid(
151                "unsupported manifest files representation".into(),
152            ));
153        }
154        let edited = doc.to_string();
155        if let Ok(parsed) = Manifest::parse(&edited)
156            && journal::encode(&parsed)? == expected
157        {
158            parsed.validate_selection(
159                host,
160                &h.profiles.iter().cloned().collect(),
161                Some(&h.repository),
162            )?;
163            return Ok(Some(edited.into_bytes()));
164        }
165    }
166    Err(Error::Invalid(
167        "batch edit changed unrelated manifest declarations".into(),
168    ))
169}
170
171/// Returns None on an entirely correct/empty apply; no transaction/backups are created.
172/// One approved request is one transaction. Atomic publications are NOT global atomicity.
173pub fn execute(
174    host: &HostContext,
175    lock: &WriterLock,
176    approval: Approval,
177    mut observer: impl FnMut(&Event) -> Result<()>,
178) -> Result<Option<String>> {
179    lock.check_context(host)?;
180    journal::ensure_writable(host)?;
181    let inputs = approval
182        .plan
183        .inputs
184        .items
185        .first()
186        .ok_or_else(|| Error::Invalid("empty batch".into()))?;
187    if journal::encode(host)? != journal::encode(&inputs.host)? {
188        return Err(Error::Invalid("approval belongs to another host".into()));
189    }
190    let profiles: Vec<_> = inputs.active_profiles.iter().cloned().collect();
191    let fresh = batch::plan(batch::observe(
192        host,
193        &inputs.repository,
194        &inputs.temporary_profiles,
195        approval.plan.request(),
196    )?);
197    if fresh.has_blockers() || batch::binding(&fresh)? != approval.digest {
198        return Err(Error::Invalid(
199            "stale or substituted batch plan; observe and approve again".into(),
200        ));
201    }
202    let local = crate::local::LocalConfig::load(host)?;
203    let repo_id = local
204        .repositories
205        .iter()
206        .find(|(_, r)| r.root == inputs.repository)
207        .map(|(id, _)| id.clone())
208        .ok_or_else(|| Error::Invalid("batch execution requires a registered repository".into()))?;
209    if fresh
210        .items
211        .iter()
212        .flat_map(|p| &p.files)
213        .all(|f| matches!(f.outcome, Outcome::NoOp))
214    {
215        return Ok(None);
216    }
217    let action = fresh.inputs.action;
218    let watches: Vec<_> = fresh
219        .inputs
220        .items
221        .iter()
222        .flat_map(|s| &s.files)
223        .map(|f| {
224            Ok(Watch {
225                mapping: f.mapping.clone(),
226                source: f
227                    .source
228                    .clone()
229                    .ok_or_else(|| Error::Invalid("missing batch source snapshot".into()))?,
230                destination: f
231                    .destination
232                    .clone()
233                    .ok_or_else(|| Error::Invalid("missing batch destination snapshot".into()))?,
234            })
235        })
236        .collect::<Result<Vec<_>>>()?;
237    let first = &fresh.inputs.items[0];
238    let mut entries = vec![&first.manifest, &first.local_config];
239    for w in &watches {
240        entries.extend([&w.source, &w.destination]);
241    }
242    let mut h = Header {
243        repository_id: repo_id,
244        repository: inputs.repository.clone(),
245        transaction_id: adoption::transaction_id(),
246        approved_plan_sha256: approval.digest,
247        action,
248        acknowledged_ids: if action == Action::Remove {
249            watches.iter().map(|w| w.mapping.id.clone()).collect()
250        } else {
251            vec![]
252        },
253        new_manifest_sha256: None,
254        profiles,
255        anchors: anchors(&entries),
256        watches,
257        manifest: first.manifest.clone(),
258        local_config: first.local_config.clone(),
259        backups: vec![],
260    };
261    if h.manifest
262        .fingerprint
263        .as_ref()
264        .is_none_or(|f| f.mode & 0o7000 != 0)
265    {
266        return Err(Error::Invalid(
267            "manifest special permission bits refused".into(),
268        ));
269    }
270    h.backups = wire::backup_specs(&h)?;
271    let expected = wire::expected(&h)?;
272    // Read bytes and construct/revalidate the focused edit before allocating a transaction.
273    let manifest_bytes = checked_bytes(&h.manifest)?;
274    let new_manifest = edit_manifest(&manifest_bytes, &h, host)?;
275    h.new_manifest_sha256 = new_manifest.as_ref().map(|b| journal::digest(b));
276    let mut backup_bytes = vec![];
277    for b in &h.backups {
278        let e = if b.path == h.manifest.path {
279            &h.manifest
280        } else {
281            &h.watches
282                .iter()
283                .find(|w| w.destination.path == b.path)
284                .ok_or_else(|| Error::Invalid("missing backup destination".into()))?
285                .destination
286        };
287        let bytes = if e.kind == Kind::Symlink {
288            e.link_target
289                .as_ref()
290                .ok_or_else(|| Error::Invalid("missing backup link target".into()))?
291                .to_str()
292                .ok_or_else(|| Error::Invalid("backup link target must be UTF-8".into()))?
293                .as_bytes()
294                .to_vec()
295        } else {
296            checked_bytes(e)?
297        };
298        if journal::digest(&bytes) != b.sha256 {
299            return Err(Error::Invalid("backup input changed".into()));
300        }
301        backup_bytes.push(bytes);
302    }
303    let prepared_bytes = h
304        .watches
305        .iter()
306        .map(|w| {
307            if action == Action::Keep {
308                checked_bytes(&w.source)
309            } else if action == Action::Adopt {
310                checked_bytes(&w.destination)
311            } else {
312                Ok(vec![])
313            }
314        })
315        .collect::<Result<Vec<_>>>()?;
316    let mut j = Journal::begin(host, h)?;
317    notify(&j, Boundary::Checkpoint, &mut observer)?;
318    for (backup, bytes) in j.record.header.backups.iter().zip(&backup_bytes) {
319        j.directory.create(&backup.name, bytes)?;
320    }
321    j.verify_backups()?;
322    let device = Fingerprint::from_stat(
323        &fs::fstat(&j.directory.file)
324            .map_err(|e| io_error("inspect transaction filesystem", &j.directory.path, e))?,
325    )
326    .device;
327    // Even watched sources stay on this device: consistent with the reviewed constraint.
328    for entry in std::iter::once(&j.record.header.manifest).chain(
329        j.record
330            .header
331            .watches
332            .iter()
333            .flat_map(|w| [&w.source, &w.destination]),
334    ) {
335        if entry
336            .parents
337            .last()
338            .is_none_or(|p| p.fingerprint.device != device || p.fingerprint.uid != first.user_id)
339            || entry
340                .fingerprint
341                .as_ref()
342                .is_some_and(|f| f.device != device)
343        {
344            return Err(Error::Invalid(
345                "batch requires owned parents and one filesystem; no cross-device fallback".into(),
346            ));
347        }
348    }
349    for (id, (role, mutation, path)) in expected.into_iter().enumerate() {
350        let before = match role {
351            Role::Directory => inspect(&path, role)?,
352            Role::Manifest => j.record.header.manifest.clone(),
353            Role::Source => j
354                .record
355                .header
356                .watches
357                .iter()
358                .find(|w| w.source.path == path)
359                .ok_or_else(|| Error::Invalid("missing watched source".into()))?
360                .source
361                .clone(),
362            Role::Destination => j
363                .record
364                .header
365                .watches
366                .iter()
367                .find(|w| w.destination.path == path)
368                .ok_or_else(|| Error::Invalid("missing watched destination".into()))?
369                .destination
370                .clone(),
371        };
372        match role {
373            Role::Directory => {
374                fs::mkdirat(
375                    &j.directory.file,
376                    stage_name(id).as_str(),
377                    Mode::from_raw_mode(0o700),
378                )
379                .map_err(|e| io_error("prepare destination parent", &path, e))?;
380                let dir = File::from(
381                    fs::openat(
382                        &j.directory.file,
383                        stage_name(id).as_str(),
384                        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
385                        Mode::empty(),
386                    )
387                    .map_err(|e| io_error("open prepared parent", &path, e))?,
388                );
389                dir.sync_all()
390                    .map_err(|e| io_error("sync prepared parent", &path, e))?;
391            }
392            Role::Manifest => stage_file(
393                &j,
394                id,
395                new_manifest
396                    .as_ref()
397                    .ok_or_else(|| Error::Invalid("missing edited manifest".into()))?,
398                before
399                    .fingerprint
400                    .as_ref()
401                    .ok_or_else(|| Error::Invalid("missing manifest fingerprint".into()))?,
402            )?,
403            Role::Source => {
404                let index = j
405                    .record
406                    .header
407                    .watches
408                    .iter()
409                    .position(|w| w.source.path == path)
410                    .ok_or_else(|| Error::Invalid("missing watched source".into()))?;
411                stage_file(
412                    &j,
413                    id,
414                    &prepared_bytes[index],
415                    j.record.header.watches[index]
416                        .destination
417                        .fingerprint
418                        .as_ref()
419                        .ok_or_else(|| Error::Invalid("missing destination fingerprint".into()))?,
420                )?;
421            }
422            Role::Destination => match action {
423                Action::Apply | Action::Adopt => {
424                    let w = j
425                        .record
426                        .header
427                        .watches
428                        .iter()
429                        .find(|w| w.destination.path == path)
430                        .ok_or_else(|| Error::Invalid("missing watched destination".into()))?;
431                    fs::symlinkat(&w.source.path, &j.directory.file, stage_name(id).as_str())
432                        .map_err(|e| io_error("prepare managed link", &path, e))?;
433                }
434                Action::Keep => {
435                    let index = j
436                        .record
437                        .header
438                        .watches
439                        .iter()
440                        .position(|w| w.destination.path == path)
441                        .ok_or_else(|| Error::Invalid("missing watched destination".into()))?;
442                    stage_file(
443                        &j,
444                        id,
445                        &prepared_bytes[index],
446                        j.record.header.watches[index]
447                            .source
448                            .fingerprint
449                            .as_ref()
450                            .ok_or_else(|| Error::Invalid("missing source fingerprint".into()))?,
451                    )?;
452                }
453                Action::Remove => {}
454            },
455        }
456        j.directory.sync()?;
457        let staged = inspect(&stage_path(&j, id), role)?;
458        j.record.operations.push(Operation {
459            id,
460            role,
461            mutation,
462            before,
463            staged,
464            after: None,
465            progress: Progress::Pending,
466        });
467    }
468    j.record.phase = Phase::Running;
469    checkpoint(&mut j, &mut observer)?;
470    validate_scope(host, &j)?;
471    for id in 0..j.record.operations.len() {
472        validate_layout(host, &j)?;
473        j.record.operations[id].progress = Progress::Intent;
474        checkpoint(&mut j, &mut observer)?;
475        validate_layout(host, &j)?;
476        mutate(&j, id, false)?;
477        notify(&j, Boundary::Mutation, &mut observer)?;
478        let op = &j.record.operations[id];
479        let after = inspect(&op.before.path, op.role)?;
480        let ok = if op.mutation == Mutation::Withdraw {
481            after.kind == Kind::Missing
482        } else {
483            same(&op.staged, &after, false)
484        };
485        if !ok {
486            return Err(Error::Invalid("batch postcondition mismatch".into()));
487        }
488        j.record.operations[id].after = Some(after);
489        j.record.operations[id].progress = Progress::Done;
490        checkpoint(&mut j, &mut observer)?;
491    }
492    j.record.phase = Phase::Verifying;
493    checkpoint(&mut j, &mut observer)?;
494    validate_layout(host, &j)?;
495    j.record.phase = Phase::Completed;
496    checkpoint(&mut j, &mut observer)?;
497    Ok(Some(j.record.header.transaction_id))
498}
499
500fn check_parents(j: &Journal, entry: &Entry) -> Result<()> {
501    for p in &entry.parents {
502        let expected = j
503            .record
504            .header
505            .anchors
506            .iter()
507            .find(|e| e.path == p.path)
508            .map(|e| &e.fingerprint)
509            .or_else(|| {
510                j.record
511                    .operations
512                    .iter()
513                    .find(|o| o.role == Role::Directory && o.before.path == p.path)
514                    .and_then(|o| o.staged.fingerprint.as_ref())
515            });
516        if expected.is_none_or(|e| !parent_identity(e, &p.fingerprint)) {
517            return Err(Error::Invalid(
518                "parent identity/permissions changed; batch refused".into(),
519            ));
520        }
521    }
522    Ok(())
523}
524fn applied(j: &Journal, op: &Operation) -> Result<bool> {
525    let live = inspect(&op.before.path, op.role)?;
526    check_parents(j, &live)?;
527    let stage = inspect(&stage_path(j, op.id), op.role)?;
528    let strict = op.progress == Progress::Pending;
529    let before = same(&op.before, &live, strict) && same(&op.staged, &stage, strict);
530    let after = match op.mutation {
531        Mutation::Publish => same(&op.staged, &live, false) && stage.kind == Kind::Missing,
532        Mutation::Exchange => same(&op.staged, &live, false) && same(&op.before, &stage, false),
533        Mutation::Withdraw => live.kind == Kind::Missing && same(&op.before, &stage, false),
534    };
535    match op.progress {
536        Progress::Pending if before => Ok(false),
537        Progress::Intent | Progress::UndoIntent if before => Ok(false),
538        Progress::Intent | Progress::UndoIntent if after => Ok(true),
539        Progress::Done if after && op.after.as_ref().is_some_and(|e| same(e, &live, true)) => {
540            Ok(true)
541        }
542        Progress::Undone if before => Ok(false),
543        _ => Err(Error::Invalid(
544            "batch guard mismatch (file, stage or parent edited); recovery refused".into(),
545        )),
546    }
547}
548fn validate_layout(host: &HostContext, j: &Journal) -> Result<()> {
549    let h = &j.record.header;
550    journal::registered_root(host, &h.repository_id, &h.repository)?;
551    j.verify_backups()?;
552    let config = observation::inspect(&host.local_config_path(), false)?;
553    if !same(&h.local_config, &config, true) {
554        return Err(Error::Invalid(
555            "local configuration changed since approval".into(),
556        ));
557    }
558    check_parents(j, &config)?;
559    for w in &h.watches {
560        if h.action != Action::Adopt {
561            let source = observation::inspect(&w.source.path, true)?;
562            if !same(&w.source, &source, true) {
563                return Err(Error::Invalid(
564                    "repository source edited; batch/recovery refused".into(),
565                ));
566            }
567            check_parents(j, &source)?;
568        }
569        if !wire::changed(h, w) {
570            let current = observation::inspect(&w.destination.path, true)?;
571            if !same(&w.destination, &current, true) {
572                return Err(Error::Invalid("unchanged mapping drifted".into()));
573            }
574            check_parents(j, &current)?;
575        }
576    }
577    if h.action == Action::Apply {
578        let manifest = observation::read_manifest(&h.manifest.path)?.1;
579        if !same(&h.manifest, &manifest, true) {
580            return Err(Error::Invalid("manifest edited since approval".into()));
581        }
582        check_parents(j, &manifest)?;
583    }
584    let states: Vec<_> = j
585        .record
586        .operations
587        .iter()
588        .map(|o| applied(j, o))
589        .collect::<Result<_>>()?;
590    for op in j
591        .record
592        .operations
593        .iter()
594        .filter(|o| o.role == Role::Directory)
595    {
596        let path = if states[op.id] {
597            op.before.path.clone()
598        } else {
599            stage_path(j, op.id)
600        };
601        let mut expected: Vec<_> = j
602            .record
603            .operations
604            .iter()
605            .filter(|child| {
606                states[op.id]
607                    && states[child.id]
608                    && child.before.path.parent() == Some(op.before.path.as_path())
609            })
610            .map(|o| {
611                o.before
612                    .path
613                    .file_name()
614                    .map(|name| name.to_owned())
615                    .ok_or_else(|| Error::Invalid("missing managed file name".into()))
616            })
617            .collect::<Result<Vec<_>>>()?;
618        expected.sort();
619        if observation::names(&path, 4096)? != expected {
620            return Err(Error::Invalid(
621                "created/prepared destination directory contains unapproved entries".into(),
622            ));
623        }
624    }
625    Ok(())
626}
627fn mutate(j: &Journal, id: usize, undo: bool) -> Result<()> {
628    let op = &j.record.operations[id];
629    let live = observation::parent_handle(&op.before.path)?;
630    if live.missing {
631        return Err(Error::Invalid("operation parent is missing".into()));
632    }
633    let current = inspect(&op.before.path, op.role)?;
634    check_parents(j, &current)?;
635    if live.parents.len() != current.parents.len()
636        || live
637            .parents
638            .iter()
639            .zip(&current.parents)
640            .any(|(a, b)| a.path != b.path || !parent_identity(&a.fingerprint, &b.fingerprint))
641    {
642        return Err(Error::Invalid(
643            "parent substituted during batch mutation".into(),
644        ));
645    }
646    if applied(j, op)? != undo {
647        return Err(Error::Invalid("batch precondition changed".into()));
648    }
649    if undo && op.role == Role::Directory && !observation::names(&op.before.path, 1)?.is_empty() {
650        return Err(Error::Invalid(
651            "created destination parent is not empty".into(),
652        ));
653    }
654    let into_private = match op.mutation {
655        Mutation::Publish => undo,
656        Mutation::Exchange => false,
657        Mutation::Withdraw => !undo,
658    };
659    let flags = if op.mutation == Mutation::Exchange {
660        RenameFlags::EXCHANGE
661    } else {
662        RenameFlags::NOREPLACE
663    };
664    let result = if into_private {
665        fs::renameat_with(
666            &live.directory,
667            &live.name,
668            &j.directory.file,
669            stage_name(id).as_str(),
670            flags,
671        )
672    } else {
673        fs::renameat_with(
674            &j.directory.file,
675            stage_name(id).as_str(),
676            &live.directory,
677            &live.name,
678            flags,
679        )
680    };
681    result.map_err(|e| {
682        io_error(
683            "publish/invert batch rename (no unsafe fallback)",
684            &op.before.path,
685            e,
686        )
687    })?;
688    live.directory
689        .sync_all()
690        .map_err(|e| io_error("sync batch parent", &op.before.path, e))?;
691    j.directory.sync()
692}
693
694fn selected_mapping(a: &crate::model::ManagedFile, b: &crate::model::ManagedFile) -> bool {
695    journal::encode(a).ok() == journal::encode(b).ok()
696}
697
698// Independently bind journal paths to a validated original manifest and host protections.
699fn validate_scope(host: &HostContext, j: &Journal) -> Result<()> {
700    let h = &j.record.header;
701    journal::registered_root(host, &h.repository_id, &h.repository)?;
702    observation::validate_output_path(&h.repository)?;
703    if h.manifest.path != h.repository.join("dort.toml")
704        || h.local_config.path != host.local_config_path()
705    {
706        return Err(Error::Invalid("batch journal scope mismatch".into()));
707    }
708    // Preparing can only create private artifacts, including incomplete backups.
709    if j.record.operations.is_empty() {
710        return Ok(());
711    }
712    j.verify_backups()?;
713    let bytes = if h.action == Action::Apply {
714        checked_bytes(&h.manifest)?
715    } else {
716        let b = h
717            .backups
718            .iter()
719            .find(|b| b.path == h.manifest.path)
720            .ok_or_else(|| Error::Invalid("missing manifest backup".into()))?;
721        journal::read_bytes(&j.directory, &b.name)?
722    };
723    let manifest = Manifest::parse(
724        std::str::from_utf8(&bytes).map_err(|_| Error::Invalid("manifest must be UTF-8".into()))?,
725    )?;
726    let active = h.profiles.iter().cloned().collect();
727    manifest.validate_selection(host, &active, Some(&h.repository))?;
728    let mappings: Vec<_> = h.watches.iter().map(|w| w.mapping.clone()).collect();
729    if h.action == Action::Adopt {
730        let mut combined = manifest.clone();
731        batch::validate_adoptions(&mut combined, &mappings, host, &active, &h.repository)?;
732    } else {
733        for mapping in &mappings {
734            if !manifest.files.iter().any(|m| {
735                m.id == mapping.id
736                    && selected_mapping(m, mapping)
737                    && (h.action != Action::Apply
738                        || crate::profiles::selected(&m.profiles, &active))
739            }) {
740                return Err(Error::Invalid(
741                    "batch watches do not match active original mappings".into(),
742                ));
743            }
744        }
745    }
746    let mut snapshots = vec![];
747    for w in &h.watches {
748        let source = h.repository.join(
749            w.mapping
750                .overrides
751                .get(&host.platform)
752                .unwrap_or(&w.mapping.source),
753        );
754        if w.source.path != source
755            || w.destination.path != host.target_path(&w.mapping.target, Some(&h.repository))?
756        {
757            return Err(Error::Invalid(
758                "batch journal mapping scope mismatch".into(),
759            ));
760        }
761        snapshots.push(planner::Snapshot {
762            user_id: rustix::process::geteuid().as_raw(),
763            host: host.clone(),
764            repository: h.repository.clone(),
765            manifest: h.manifest.clone(),
766            local_config: h.local_config.clone(),
767            active_profiles: active.clone(),
768            temporary_profiles: vec![],
769            profiles: vec![],
770            inactive_links: vec![],
771            request: match h.action {
772                Action::Adopt => Request::Adopt {
773                    mapping: w.mapping.clone(),
774                },
775                Action::Apply => Request::Apply,
776                Action::Keep | Action::Remove => Request::Unmanage {
777                    id: w.mapping.id.clone(),
778                    mode: if h.action == Action::Keep {
779                        UnmanageMode::Keep
780                    } else {
781                        UnmanageMode::Remove
782                    },
783                },
784            },
785            files: vec![planner::FileSnapshot {
786                mapping: w.mapping.clone(),
787                source_path: w.source.path.clone(),
788                target_path: w.destination.path.clone(),
789                source: Some(w.source.clone()),
790                destination: Some(w.destination.clone()),
791                blockers: vec![],
792            }],
793        });
794    }
795    let plan = batch::plan(batch::Snapshot {
796        action: h.action,
797        items: snapshots,
798        blockers: vec![],
799    });
800    if plan.has_blockers() || batch::binding(&plan)? != h.approved_plan_sha256 {
801        return Err(Error::Invalid(
802            "batch journal does not reconstruct approved combined plan".into(),
803        ));
804    }
805    let edited = edit_manifest(&bytes, h, host)?;
806    if edited.as_ref().map(|b| journal::digest(b)) != h.new_manifest_sha256 {
807        return Err(Error::Invalid(
808            "batch manifest edit binding mismatch".into(),
809        ));
810    }
811    let expected = wire::expected(h)?;
812    if j.record.operations.len() != expected.len() {
813        return Err(Error::Invalid("batch operation scope mismatch".into()));
814    }
815    for (op, (role, mutation, path)) in j.record.operations.iter().zip(expected) {
816        if op.role != role
817            || op.mutation != mutation
818            || op.before.path != path
819            || op.staged.path != stage_path(j, op.id)
820        {
821            return Err(Error::Invalid("batch operation path/order mismatch".into()));
822        }
823    }
824    Ok(())
825}
826
827/// Read-only preflight and conservative inverse paths for the head-bound recovery service.
828pub(crate) fn rollback_preview(
829    host: &HostContext,
830    repository_id: &str,
831    transaction_id: &str,
832) -> Result<(String, Vec<PathBuf>)> {
833    let j = Journal::open(host, repository_id, transaction_id)?;
834    validate_scope(host, &j)?;
835    if !matches!(j.record.phase, Phase::Preparing | Phase::RolledBack) {
836        validate_layout(host, &j)?;
837    }
838    let effects = if matches!(j.record.phase, Phase::Preparing | Phase::RolledBack) {
839        vec![]
840    } else {
841        j.record
842            .operations
843            .iter()
844            .rev()
845            .filter(|o| o.progress != Progress::Undone)
846            .map(|o| o.before.path.clone())
847            .collect()
848    };
849    Ok((
850        journal::digest(journal::encode(&j.record)?.as_bytes()),
851        effects,
852    ))
853}
854
855/// Explicit/restartable guarded rollback of a schema-4 selected batch.
856/// Older schemas retain their independent executors and recovery validation.
857pub fn rollback(
858    host: &HostContext,
859    lock: &WriterLock,
860    repository_id: &str,
861    transaction_id: &str,
862    mut observer: impl FnMut(&Event) -> Result<()>,
863) -> Result<()> {
864    lock.check_context(host)?;
865    let mut j = Journal::open(host, repository_id, transaction_id)?;
866    validate_scope(host, &j)?;
867    if j.record.phase == Phase::RolledBack {
868        return Ok(());
869    }
870    if j.record.phase == Phase::Preparing {
871        j.record.phase = Phase::RolledBack;
872        return checkpoint(&mut j, &mut observer);
873    }
874    validate_layout(host, &j)?;
875    if j.record.phase != Phase::RollingBack {
876        j.record.phase = Phase::RollingBack;
877        checkpoint(&mut j, &mut observer)?;
878    }
879    for id in (0..j.record.operations.len()).rev() {
880        if j.record.operations[id].progress == Progress::Undone {
881            continue;
882        }
883        validate_layout(host, &j)?;
884        let was_applied = applied(&j, &j.record.operations[id])?;
885        j.record.operations[id].progress = Progress::UndoIntent;
886        checkpoint(&mut j, &mut observer)?;
887        validate_layout(host, &j)?;
888        if was_applied {
889            mutate(&j, id, true)?;
890            notify(&j, Boundary::Mutation, &mut observer)?;
891        }
892        j.record.operations[id].progress = Progress::Undone;
893        checkpoint(&mut j, &mut observer)?;
894    }
895    validate_layout(host, &j)?;
896    j.record.phase = Phase::RolledBack;
897    checkpoint(&mut j, &mut observer)
898}