Skip to main content

objects/transfer/
graph.rs

1// SPDX-License-Identifier: Apache-2.0
2use std::collections::{HashSet, VecDeque};
3#[cfg(feature = "async-source")]
4use std::sync::{
5    Arc,
6    atomic::{AtomicBool, Ordering},
7};
8#[cfg(feature = "async-source")]
9use std::time::Instant;
10
11use serde::{Deserialize, Serialize};
12
13#[cfg(feature = "async-source")]
14use crate::store::AsyncObjectSource;
15use crate::{
16    error::{HeddleError, Result},
17    object::{
18        AnnotatedTag, BindingDelta, ContentHash, RedactionsBlob, ReverseDependencyIndex,
19        SemanticEntryKind, SemanticIndexRoot, SemanticTreeNode, State, StateAttachment,
20        StateAttachmentBody, StateAttachmentId, StateAttachmentKind, StateId, TreeEntryTarget,
21        decode_tree_delta_header, is_delta_tree,
22    },
23    store::{ObjectSource, ObjectStore, pack::ObjectType as PackObjectType},
24};
25
26#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
27pub enum ObjectId {
28    Hash(ContentHash),
29    StateId(StateId),
30    StateAttachment {
31        state: StateId,
32        id: StateAttachmentId,
33        /// The attachment's kind, a pure projection of its body
34        /// ([`StateAttachmentBody::kind`]). Carried through the wire so
35        /// descriptors self-describe their kind; the dedup/identity key is
36        /// still `(state, id)`, and kind is coherent under `Eq`/`Hash` because
37        /// it is a deterministic function of the same record.
38        kind: StateAttachmentKind,
39    },
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize)]
43pub struct ObjectInfo {
44    pub id: ObjectId,
45    pub obj_type: ObjectType,
46    pub size: u64,
47    pub delta_base: Option<ContentHash>,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
51pub struct PlannedObject {
52    pub id: ObjectId,
53    pub obj_type: ObjectType,
54}
55
56#[derive(Debug, Clone)]
57pub struct StateClosureTransferObjects {
58    pub planned_objects: Vec<PlannedObject>,
59    pub full_objects: Option<Vec<ObjectInfo>>,
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
63pub enum ObjectType {
64    Blob,
65    Tree,
66    State,
67    Action,
68    AnnotatedTag,
69    /// A `RedactionsBlob` sidecar — the rmp-encoded record(s) declaring
70    /// that a specific blob has been redacted by a writer. Keyed on the
71    /// wire by `ObjectId::Hash` of
72    /// the *redacted blob*, since `Repository`'s sidecar store is
73    /// indexed that way.
74    Redaction,
75    /// An owner-authorized purge sidecar. It carries the same encoded
76    /// `RedactionsBlob` as `Redaction`, but is a distinct operation because
77    /// receiving it can irreversibly erase blob bytes.
78    Purge,
79    /// A `StateVisibilityBlob` sidecar — the rmp-encoded record(s)
80    /// declaring a non-public audience tier for a specific state. Keyed
81    /// on the wire by `ObjectId::StateId` of the state, since the
82    /// per-state sidecar store is indexed that way. Like `Redaction`, it
83    /// is a sidecar record that lives outside the content-addressed pack
84    /// and ships via the per-object transfer path, not the pack.
85    StateVisibility,
86    StateAttachment,
87    /// A content-addressed `KeyBindingRegistry` together with each binding's
88    /// revocation/liveness overlay. Hosted materializers append this object to
89    /// a closure and carry it out of pack because the native pack format has no
90    /// key-binding record kind.
91    KeyBinding,
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
95pub enum ObjectTypeBucket {
96    Blob,
97    Tree,
98    State,
99    Action,
100    AnnotatedTag,
101    Redaction,
102    Purge,
103    StateVisibility,
104    StateAttachment,
105    KeyBinding,
106}
107
108impl ObjectType {
109    pub fn wire_name(self) -> &'static str {
110        match self {
111            ObjectType::Blob => "blob",
112            ObjectType::Tree => "tree",
113            ObjectType::State => "state",
114            ObjectType::Action => "action",
115            ObjectType::AnnotatedTag => "annotated_tag",
116            ObjectType::Redaction => "redaction",
117            ObjectType::Purge => "purge",
118            ObjectType::StateVisibility => "state_visibility",
119            ObjectType::StateAttachment => "state_attachment",
120            ObjectType::KeyBinding => "key_binding",
121        }
122    }
123
124    pub fn from_wire(value: &str) -> Result<Self> {
125        match value {
126            "blob" => Ok(ObjectType::Blob),
127            "tree" => Ok(ObjectType::Tree),
128            "state" => Ok(ObjectType::State),
129            "action" => Ok(ObjectType::Action),
130            "annotated_tag" => Ok(ObjectType::AnnotatedTag),
131            "redaction" => Ok(ObjectType::Redaction),
132            "purge" => Ok(ObjectType::Purge),
133            "state_visibility" => Ok(ObjectType::StateVisibility),
134            "state_attachment" => Ok(ObjectType::StateAttachment),
135            "key_binding" => Ok(ObjectType::KeyBinding),
136            _ => Err(HeddleError::InvalidObject(format!(
137                "unknown object type: {value}"
138            ))),
139        }
140    }
141
142    /// Whether this object type can ride the content-addressed native pack in
143    /// general (the historical, direction-agnostic predicate). Sidecar records
144    /// (`Redaction`, `StateVisibility`) live outside `.heddle/objects/` and can
145    /// never be packed; everything else can.
146    ///
147    /// Prefer [`ObjectType::packable_for_push`] /
148    /// [`ObjectType::packable_for_pull`] at transfer sites: packability is
149    /// direction-dependent for `StateAttachment` (see those methods). This
150    /// method retains the pull/general semantics so pack construction,
151    /// have-set, and local-copy planners are unchanged.
152    pub fn packable(self) -> bool {
153        !matches!(
154            self,
155            ObjectType::Redaction
156                | ObjectType::Purge
157                | ObjectType::StateVisibility
158                | ObjectType::KeyBinding
159        )
160    }
161
162    /// Whether this object type may ride the client→server **push** pack.
163    ///
164    /// `StateAttachment` is deliberately excluded on push even though it is a
165    /// content-addressed object: a deployed server rejects any pack-carried
166    /// attachment as a forgery-prevention measure (weft#549). Pushed
167    /// attachments must instead ride the out-of-pack **sidecar** lane (the same
168    /// lane as `Redaction`/`StateVisibility`), where the server can verify them
169    /// per-kind at finalize while the pack itself stays forgery-sealed. Every
170    /// other type keeps its [`ObjectType::packable`] answer.
171    pub fn packable_for_push(self) -> bool {
172        self.packable() && !matches!(self, ObjectType::StateAttachment)
173    }
174
175    /// Whether this object type may ride the server→client **pull/clone** pack.
176    ///
177    /// Same boolean as [`ObjectType::packable`] so planners still list
178    /// `StateAttachment`. Weft does not put those records in the native pack:
179    /// it streams `PullServerFrame::StateAttachment`. Discussions attachments
180    /// are not the live transport (v2 chain vs this client's v1 blob); clone
181    /// treats an advertised-but-unconsumable pack as a ListByState fallback.
182    pub fn packable_for_pull(self) -> bool {
183        self.packable()
184    }
185
186    pub fn pack_object_type(self) -> Result<PackObjectType> {
187        match self {
188            ObjectType::Blob => Ok(PackObjectType::Blob),
189            ObjectType::Tree => Ok(PackObjectType::Tree),
190            ObjectType::State => Ok(PackObjectType::State),
191            ObjectType::Action => Ok(PackObjectType::Action),
192            ObjectType::AnnotatedTag => Ok(PackObjectType::AnnotatedTag),
193            ObjectType::StateAttachment => Ok(PackObjectType::StateAttachment),
194            ObjectType::Redaction => Err(HeddleError::InvalidObject(
195                "Redaction sidecar records cannot be packed into the content-addressed object pack"
196                    .to_string(),
197            )),
198            ObjectType::Purge => Err(HeddleError::InvalidObject(
199                "Purge sidecar records cannot be packed into the content-addressed object pack"
200                    .to_string(),
201            )),
202            ObjectType::StateVisibility => Err(HeddleError::InvalidObject(
203                "StateVisibility sidecar records cannot be packed into the content-addressed object pack"
204                    .to_string(),
205            )),
206            ObjectType::KeyBinding => Err(HeddleError::InvalidObject(
207                "KeyBinding registry objects cannot be packed into the content-addressed object pack"
208                    .to_string(),
209            )),
210        }
211    }
212
213    pub fn bucket(self) -> ObjectTypeBucket {
214        match self {
215            ObjectType::Blob => ObjectTypeBucket::Blob,
216            ObjectType::Tree => ObjectTypeBucket::Tree,
217            ObjectType::State => ObjectTypeBucket::State,
218            ObjectType::Action => ObjectTypeBucket::Action,
219            ObjectType::AnnotatedTag => ObjectTypeBucket::AnnotatedTag,
220            ObjectType::Redaction => ObjectTypeBucket::Redaction,
221            ObjectType::Purge => ObjectTypeBucket::Purge,
222            ObjectType::StateVisibility => ObjectTypeBucket::StateVisibility,
223            ObjectType::StateAttachment => ObjectTypeBucket::StateAttachment,
224            ObjectType::KeyBinding => ObjectTypeBucket::KeyBinding,
225        }
226    }
227}
228
229#[derive(Debug, Clone, Default)]
230pub struct StateClosureOptions {
231    pub depth: Option<u32>,
232    pub exclude_states: Vec<StateId>,
233}
234
235pub fn enumerate_state_closure(
236    store: &impl ObjectStore,
237    state_id: StateId,
238) -> Result<Vec<ObjectInfo>> {
239    enumerate_state_closure_with_options(store, state_id, StateClosureOptions::default())
240}
241
242pub fn enumerate_state_closure_with_options(
243    store: &impl ObjectStore,
244    state_id: StateId,
245    options: StateClosureOptions,
246) -> Result<Vec<ObjectInfo>> {
247    let mut out = Vec::new();
248    walk_state_closure(store, state_id, options, |event| {
249        if let Some(info) = object_info_from_event(store, event)? {
250            out.push(info);
251        }
252        Ok(())
253    })?;
254    for (hash, tag) in annotated_tags_for_state(store, state_id)? {
255        out.push(annotated_tag_info(hash, &tag));
256    }
257
258    Ok(out)
259}
260
261pub fn enumerate_state_closure_plan(
262    store: &impl ObjectStore,
263    state_id: StateId,
264) -> Result<Vec<PlannedObject>> {
265    enumerate_state_closure_plan_with_options(store, state_id, StateClosureOptions::default())
266}
267
268pub fn enumerate_state_closure_plan_with_options(
269    store: &impl ObjectStore,
270    state_id: StateId,
271    options: StateClosureOptions,
272) -> Result<Vec<PlannedObject>> {
273    let mut out = Vec::new();
274    walk_state_closure(store, state_id, options, |event| {
275        if let Some(object) = planned_object_from_event(store, event)? {
276            out.push(object);
277        }
278        Ok(())
279    })?;
280    out.extend(
281        annotated_tags_for_state(store, state_id)?
282            .into_iter()
283            .map(|(hash, _)| PlannedObject {
284                id: ObjectId::Hash(hash),
285                obj_type: ObjectType::AnnotatedTag,
286            }),
287    );
288
289    Ok(out)
290}
291
292pub fn enumerate_state_closure_transfer_with_options(
293    store: &impl ObjectStore,
294    state_id: StateId,
295    options: StateClosureOptions,
296    full_descriptor_object_threshold: usize,
297) -> Result<StateClosureTransferObjects> {
298    let mut planned_objects = Vec::new();
299    let mut full_objects = Some(Vec::new());
300
301    walk_state_closure(store, state_id, options, |event| {
302        if let Some(object) = planned_object_from_event(store, event)? {
303            planned_objects.push(object);
304        }
305
306        if full_objects.is_some() && planned_objects.len() > full_descriptor_object_threshold {
307            full_objects = None;
308        }
309        if let Some(objects) = full_objects.as_mut()
310            && let Some(info) = object_info_from_event(store, event)?
311        {
312            objects.push(info);
313        }
314
315        Ok(())
316    })?;
317    let tags = annotated_tags_for_state(store, state_id)?;
318    planned_objects.extend(tags.iter().map(|(hash, _)| PlannedObject {
319        id: ObjectId::Hash(*hash),
320        obj_type: ObjectType::AnnotatedTag,
321    }));
322    if full_objects.is_some() && planned_objects.len() > full_descriptor_object_threshold {
323        full_objects = None;
324    }
325    if let Some(objects) = full_objects.as_mut() {
326        objects.extend(
327            tags.iter()
328                .map(|(hash, tag)| annotated_tag_info(*hash, tag)),
329        );
330    }
331
332    Ok(StateClosureTransferObjects {
333        planned_objects,
334        full_objects,
335    })
336}
337
338fn annotated_tags_for_state(
339    store: &impl ObjectStore,
340    state_id: StateId,
341) -> Result<Vec<(ContentHash, AnnotatedTag)>> {
342    let mut roots = Vec::new();
343    for hash in store.list_annotated_tags()? {
344        let Some(tag) = store.get_annotated_tag(&hash)? else {
345            continue;
346        };
347        if tag
348            .marker()
349            .is_some_and(|marker| marker.peeled_state == state_id)
350        {
351            roots.push((hash, tag));
352        }
353    }
354
355    let mut tags = Vec::new();
356    let mut seen = HashSet::new();
357    let mut stack = roots;
358    while let Some((hash, tag)) = stack.pop() {
359        if !seen.insert(hash) {
360            continue;
361        }
362        if let Some(inner_hash) = tag.target_tag() {
363            let inner = store.get_annotated_tag(&inner_hash)?.ok_or_else(|| {
364                HeddleError::NotFound(format!(
365                    "annotated tag {hash} references missing inner tag {inner_hash}"
366                ))
367            })?;
368            stack.push((inner_hash, inner));
369        }
370        tags.push((hash, tag));
371    }
372    Ok(tags)
373}
374
375fn annotated_tag_info(hash: ContentHash, tag: &AnnotatedTag) -> ObjectInfo {
376    ObjectInfo {
377        id: ObjectId::Hash(hash),
378        obj_type: ObjectType::AnnotatedTag,
379        size: tag.encode_current_msgpack().len() as u64,
380        delta_base: None,
381    }
382}
383
384/// Enumerate a transfer delta while treating `boundary_states` as complete
385/// server-held roots. Unlike [`StateClosureOptions::exclude_states`], this does
386/// not expand each boundary's tree/history to build a hash exclusion set: the
387/// walk stops as soon as it reaches the boundary state. Objects reused by the
388/// new tip may still be advertised, and the receiver's have-set filters them.
389/// This keeps incremental push planning proportional to the new history.
390pub fn enumerate_state_closure_transfer_from_boundaries(
391    store: &impl ObjectStore,
392    state_id: StateId,
393    boundary_states: &[StateId],
394    full_descriptor_object_threshold: usize,
395) -> Result<StateClosureTransferObjects> {
396    let mut planned_objects = Vec::new();
397    let mut full_objects = Some(Vec::new());
398    let excluded_states = boundary_states.iter().copied().collect();
399
400    walk_state_closure_with_exclusions(
401        store,
402        state_id,
403        None,
404        excluded_states,
405        HashSet::new(),
406        |event| {
407            if let Some(object) = planned_object_from_event(store, event)? {
408                planned_objects.push(object);
409            }
410
411            if full_objects.is_some() && planned_objects.len() > full_descriptor_object_threshold {
412                full_objects = None;
413            }
414            if let Some(objects) = full_objects.as_mut()
415                && let Some(info) = object_info_from_event(store, event)?
416            {
417                objects.push(info);
418            }
419
420            Ok(())
421        },
422    )?;
423
424    Ok(StateClosureTransferObjects {
425        planned_objects,
426        full_objects,
427    })
428}
429
430#[derive(Debug, Clone, Copy)]
431enum StateClosureEvent<'a> {
432    State {
433        id: StateId,
434        state: &'a State,
435    },
436    Tree {
437        hash: ContentHash,
438        storage_size: u64,
439        delta_base: Option<ContentHash>,
440    },
441    Blob {
442        hash: ContentHash,
443    },
444    Redaction {
445        blob: ContentHash,
446    },
447    StateVisibility {
448        state: StateId,
449    },
450    StateAttachment {
451        state: StateId,
452        attachment: &'a StateAttachment,
453    },
454    ExcludedState {
455        id: StateId,
456    },
457    ExcludedHash {
458        hash: ContentHash,
459    },
460}
461
462fn walk_state_closure(
463    store: &impl ObjectStore,
464    state_id: StateId,
465    options: StateClosureOptions,
466    visit: impl for<'event> FnMut(StateClosureEvent<'event>) -> Result<()>,
467) -> Result<()> {
468    let (excluded_states, excluded_hashes) = collect_excluded(store, &options.exclude_states)?;
469
470    walk_state_closure_with_exclusions(
471        store,
472        state_id,
473        options.depth,
474        excluded_states,
475        excluded_hashes,
476        visit,
477    )
478}
479
480fn walk_state_closure_with_exclusions(
481    store: &impl ObjectStore,
482    state_id: StateId,
483    max_depth: Option<u32>,
484    excluded_states: HashSet<StateId>,
485    excluded_hashes: HashSet<ContentHash>,
486    mut visit: impl for<'event> FnMut(StateClosureEvent<'event>) -> Result<()>,
487) -> Result<()> {
488    let mut seen_states: HashSet<StateId> = HashSet::new();
489    let mut seen_hashes: HashSet<ContentHash> = HashSet::new();
490    let mut queue: VecDeque<(StateId, u32)> = VecDeque::new();
491    queue.push_back((state_id, 0));
492
493    while let Some((id, depth)) = queue.pop_front() {
494        if excluded_states.contains(&id) {
495            visit(StateClosureEvent::ExcludedState { id })?;
496            continue;
497        }
498        if !seen_states.insert(id) {
499            continue;
500        }
501
502        let state = store
503            .get_state(&id)?
504            .ok_or_else(|| HeddleError::MissingObject {
505                object_type: "state".to_string(),
506                id: id.to_string(),
507            })?;
508
509        visit(StateClosureEvent::State { id, state: &state })?;
510        if store.has_state_visibility_for_state(&id)? {
511            visit(StateClosureEvent::StateVisibility { state: id })?;
512        }
513        for attachment in store.list_state_attachments(&id)? {
514            visit(StateClosureEvent::StateAttachment {
515                state: id,
516                attachment: &attachment,
517            })?;
518            match attachment.body {
519                StateAttachmentBody::Context(root) => walk_tree_closure_filtered(
520                    store,
521                    root,
522                    &excluded_hashes,
523                    &mut seen_hashes,
524                    &mut visit,
525                )?,
526                StateAttachmentBody::RiskSignals(hash)
527                | StateAttachmentBody::ReviewSignatures(hash)
528                | StateAttachmentBody::Discussions(hash)
529                | StateAttachmentBody::StructuredConflicts(hash)
530                | StateAttachmentBody::ContextConsumption(hash) => {
531                    walk_blob_filtered(store, hash, &excluded_hashes, &mut seen_hashes, &mut visit)?
532                }
533                StateAttachmentBody::SemanticIndex(root) => walk_semantic_index_closure(
534                    store,
535                    root,
536                    &excluded_hashes,
537                    &mut seen_hashes,
538                    &mut visit,
539                )?,
540                StateAttachmentBody::Signature(_) => {}
541            }
542        }
543
544        if max_depth.map(|max| depth < max).unwrap_or(true) {
545            for parent in &state.parents {
546                queue.push_back((*parent, depth + 1));
547            }
548        }
549
550        walk_tree_closure_filtered(
551            store,
552            state.tree,
553            &excluded_hashes,
554            &mut seen_hashes,
555            &mut visit,
556        )?;
557        if let Some(provenance_root) = state.provenance {
558            walk_tree_closure_filtered(
559                store,
560                provenance_root,
561                &excluded_hashes,
562                &mut seen_hashes,
563                &mut visit,
564            )?;
565        }
566    }
567
568    Ok(())
569}
570
571fn walk_tree_closure_filtered(
572    store: &impl ObjectStore,
573    tree_hash: ContentHash,
574    excluded: &HashSet<ContentHash>,
575    seen: &mut HashSet<ContentHash>,
576    visit: &mut impl for<'event> FnMut(StateClosureEvent<'event>) -> Result<()>,
577) -> Result<()> {
578    if excluded.contains(&tree_hash) {
579        visit(StateClosureEvent::ExcludedHash { hash: tree_hash })?;
580        return Ok(());
581    }
582    if !seen.insert(tree_hash) {
583        return Ok(());
584    }
585
586    let tree = store
587        .get_tree(&tree_hash)?
588        .ok_or_else(|| HeddleError::MissingObject {
589            object_type: "tree".to_string(),
590            id: tree_hash.to_hex(),
591        })?;
592
593    let (storage_size, delta_base) = tree_storage_metadata(store, tree_hash)?;
594    visit(StateClosureEvent::Tree {
595        hash: tree_hash,
596        storage_size,
597        delta_base,
598    })?;
599
600    if let Some(anchor) = delta_base {
601        walk_tree_storage_anchor(store, anchor, seen, visit)?;
602    }
603
604    for entry in tree.entries() {
605        match entry.target() {
606            TreeEntryTarget::Blob { hash, .. } | TreeEntryTarget::Symlink { hash } => {
607                walk_blob_filtered(store, *hash, excluded, seen, visit)?;
608            }
609            TreeEntryTarget::Tree { hash } => {
610                walk_tree_closure_filtered(store, *hash, excluded, seen, visit)?;
611            }
612            TreeEntryTarget::Gitlink { .. } => {}
613            // Native child-spool edge: its target lives in a separate spool
614            // object graph, not this store, so it is not walked here.
615            TreeEntryTarget::Spoollink { .. } => {}
616        }
617    }
618
619    Ok(())
620}
621
622fn tree_storage_metadata(
623    store: &impl ObjectStore,
624    tree_hash: ContentHash,
625) -> Result<(u64, Option<ContentHash>)> {
626    let body =
627        store
628            .get_tree_serialized(&tree_hash)?
629            .ok_or_else(|| HeddleError::MissingObject {
630                object_type: "tree".to_string(),
631                id: tree_hash.to_hex(),
632            })?;
633    let delta_base = if is_delta_tree(&body) {
634        let header = decode_tree_delta_header(&body)?;
635        if header.anchor == tree_hash {
636            return Err(HeddleError::InvalidObject(
637                "HDC1 result id must differ from its anchor id".to_string(),
638            ));
639        }
640        Some(header.anchor)
641    } else {
642        None
643    };
644    Ok((body.len() as u64, delta_base))
645}
646
647fn walk_tree_storage_anchor(
648    store: &impl ObjectStore,
649    anchor_hash: ContentHash,
650    seen: &mut HashSet<ContentHash>,
651    visit: &mut impl for<'event> FnMut(StateClosureEvent<'event>) -> Result<()>,
652) -> Result<()> {
653    if !seen.insert(anchor_hash) {
654        return Ok(());
655    }
656    if store.get_tree(&anchor_hash)?.is_none() {
657        return Err(HeddleError::MissingObject {
658            object_type: "tree delta anchor".to_string(),
659            id: anchor_hash.to_hex(),
660        });
661    }
662    let (storage_size, delta_base) = tree_storage_metadata(store, anchor_hash)?;
663    if delta_base.is_some() {
664        return Err(HeddleError::InvalidObject(
665            "HDC1 anchor must be materialized; delta chains are forbidden".to_string(),
666        ));
667    }
668    visit(StateClosureEvent::Tree {
669        hash: anchor_hash,
670        storage_size,
671        delta_base: None,
672    })
673}
674
675fn walk_blob_filtered(
676    store: &impl ObjectStore,
677    blob_hash: ContentHash,
678    excluded: &HashSet<ContentHash>,
679    seen: &mut HashSet<ContentHash>,
680    visit: &mut impl for<'event> FnMut(StateClosureEvent<'event>) -> Result<()>,
681) -> Result<()> {
682    if excluded.contains(&blob_hash) {
683        visit(StateClosureEvent::ExcludedHash { hash: blob_hash })?;
684        return Ok(());
685    }
686    if !seen.insert(blob_hash) {
687        return Ok(());
688    }
689    visit(StateClosureEvent::Blob { hash: blob_hash })?;
690    if store.has_redactions_for_blob(&blob_hash)? {
691        visit(StateClosureEvent::Redaction { blob: blob_hash })?;
692    }
693    Ok(())
694}
695
696/// Walk the merkle semantic-index closure rooted at `root_hash` (a
697/// `SemanticIndexRoot` blob), emitting every reachable semantic node blob.
698///
699/// All semantic-index nodes (root, tree nodes, file nodes) are stored as
700/// ordinary content-addressed blobs, so replication just enumerates them.
701/// Opaque entries point back at raw source blobs already covered by the state's
702/// tree closure, so they are not re-walked here.
703///
704/// Iterative (explicit stack) so a crafted deep `SemanticTreeNode` chain in a
705/// pushed state can't overflow the stack. A missing or undecodable node in the
706/// closure is a HARD failure (`ObjectNotFound`/`Serialization`) — a partial or
707/// corrupt semantic closure must never be shipped silently.
708fn walk_semantic_index_closure(
709    store: &impl ObjectStore,
710    root_hash: ContentHash,
711    excluded: &HashSet<ContentHash>,
712    seen: &mut HashSet<ContentHash>,
713    visit: &mut impl for<'event> FnMut(StateClosureEvent<'event>) -> Result<()>,
714) -> Result<()> {
715    // Stack of (node_hash, is_tree_node): the root and dir nodes must be decoded
716    // to enumerate their children; file/opaque leaves are emitted only.
717    let mut stack: Vec<ContentHash> = vec![root_hash];
718    while let Some(node_hash) = stack.pop() {
719        if !emit_semantic_blob(store, node_hash, excluded, seen, visit)? {
720            continue; // excluded (present on the far side) or already seen.
721        }
722        let blob = store
723            .get_blob(&node_hash)?
724            .ok_or_else(|| missing_blob(node_hash))?;
725        // The root and tree nodes decode to the same `SemanticTreeNode.entries`
726        // shape after the root's one indirection; walk uniformly by decoding
727        // every interior node as a tree node, tolerating the root shape.
728        let node = decode_semantic_container(&blob, node_hash)?;
729        for child in node {
730            match child {
731                SemanticChild::Interior(hash) => stack.push(hash),
732                SemanticChild::Leaf(hash) => {
733                    // Emit the leaf (file node) blob; it has no children.
734                    emit_semantic_blob(store, hash, excluded, seen, visit)?;
735                }
736                SemanticChild::BindingDelta(hash) => {
737                    // Binding deltas are state-scoped attachments. Emit this
738                    // state's direct delta; ancestor states contribute their
739                    // own deltas when (and only when) the state walk reaches
740                    // them. Following `delta.parent` here would cross a
741                    // shallow-clone boundary.
742                    emit_binding_delta(store, hash, excluded, seen, visit)?;
743                }
744                SemanticChild::ImporterIndex(hash) => {
745                    emit_importer_index(store, hash, excluded, seen, visit)?;
746                }
747            }
748        }
749    }
750    Ok(())
751}
752
753/// Child kinds encountered while walking a state's semantic closure.
754enum SemanticChild {
755    Interior(ContentHash),
756    Leaf(ContentHash),
757    BindingDelta(ContentHash),
758    ImporterIndex(ContentHash),
759}
760
761/// Decode a semantic-closure node — the root (which points at a tree node) or a
762/// tree node — into the child hashes to walk. Missing/corrupt is a hard error.
763fn decode_semantic_container(
764    blob: &crate::object::Blob,
765    node_hash: ContentHash,
766) -> Result<Vec<SemanticChild>> {
767    // Try the root shape first (it has an extra `tree` indirection), then the
768    // tree-node shape. Content-addressed hashes make this unambiguous in
769    // practice; a blob that decodes as neither is corrupt.
770    if let Ok(root) = SemanticIndexRoot::decode(blob.content()) {
771        let mut children = vec![SemanticChild::Interior(root.tree)];
772        if let Some(binding_delta) = root.binding_delta {
773            children.push(SemanticChild::BindingDelta(binding_delta));
774        }
775        if let Some(importer_index) = root.importer_index {
776            children.push(SemanticChild::ImporterIndex(importer_index));
777        }
778        return Ok(children);
779    }
780    let node = SemanticTreeNode::decode(blob.content())
781        .map_err(|err| HeddleError::Serialization(format!("semantic node {node_hash}: {err}")))?;
782    Ok(node
783        .entries
784        .iter()
785        .filter_map(|entry| match entry.kind {
786            SemanticEntryKind::Dir => Some(SemanticChild::Interior(entry.node)),
787            SemanticEntryKind::File => Some(SemanticChild::Leaf(entry.node)),
788            // Opaque `node` is the raw source blob, already in the tree closure.
789            SemanticEntryKind::Opaque => None,
790        })
791        .collect())
792}
793
794fn emit_binding_delta(
795    store: &impl ObjectStore,
796    hash: ContentHash,
797    excluded: &HashSet<ContentHash>,
798    seen: &mut HashSet<ContentHash>,
799    visit: &mut impl for<'event> FnMut(StateClosureEvent<'event>) -> Result<()>,
800) -> Result<()> {
801    if !emit_semantic_blob(store, hash, excluded, seen, visit)? {
802        return Ok(());
803    }
804    let blob = store.get_blob(&hash)?.ok_or_else(|| missing_blob(hash))?;
805    BindingDelta::decode(blob.content()).map_err(|err| {
806        HeddleError::Serialization(format!("semantic binding delta {hash}: {err}"))
807    })?;
808    Ok(())
809}
810
811fn emit_importer_index(
812    store: &impl ObjectStore,
813    hash: ContentHash,
814    excluded: &HashSet<ContentHash>,
815    seen: &mut HashSet<ContentHash>,
816    visit: &mut impl for<'event> FnMut(StateClosureEvent<'event>) -> Result<()>,
817) -> Result<()> {
818    if !emit_semantic_blob(store, hash, excluded, seen, visit)? {
819        return Ok(());
820    }
821    let blob = store.get_blob(&hash)?.ok_or_else(|| missing_blob(hash))?;
822    ReverseDependencyIndex::decode(blob.content()).map_err(|err| {
823        HeddleError::Serialization(format!("semantic reverse-dependency index {hash}: {err}"))
824    })?;
825    Ok(())
826}
827
828/// Emit a semantic node blob as state metadata. Returns `true` when the blob
829/// was newly visited (so the caller may descend into it), `false` when it was
830/// excluded (present on the far side) or already seen. A blob that is neither
831/// excluded nor present is a HARD failure — the closure must be complete.
832fn emit_semantic_blob(
833    store: &impl ObjectStore,
834    hash: ContentHash,
835    excluded: &HashSet<ContentHash>,
836    seen: &mut HashSet<ContentHash>,
837    visit: &mut impl for<'event> FnMut(StateClosureEvent<'event>) -> Result<()>,
838) -> Result<bool> {
839    if excluded.contains(&hash) {
840        visit(StateClosureEvent::ExcludedHash { hash })?;
841        return Ok(false);
842    }
843    if !seen.insert(hash) {
844        return Ok(false);
845    }
846    if store.get_blob(&hash)?.is_none() {
847        return Err(missing_blob(hash));
848    }
849    visit(StateClosureEvent::Blob { hash })?;
850    Ok(true)
851}
852
853/// Collect every semantic-index node blob hash reachable from `root_hash` into
854/// `excluded`, for the have-set computation. Iterative + tolerant (a broken
855/// have-set index is not fatal — it just means fewer objects are marked
856/// already-present, which is safe over-fetching, not corruption).
857fn collect_semantic_hashes(
858    store: &impl ObjectStore,
859    root_hash: ContentHash,
860    excluded: &mut HashSet<ContentHash>,
861) -> Result<()> {
862    let mut stack: Vec<ContentHash> = vec![root_hash];
863    while let Some(node_hash) = stack.pop() {
864        if !excluded.insert(node_hash) {
865            continue;
866        }
867        let Some(blob) = store.get_blob(&node_hash)? else {
868            continue;
869        };
870        let children = match decode_semantic_container(&blob, node_hash) {
871            Ok(children) => children,
872            Err(_) => continue,
873        };
874        for child in children {
875            match child {
876                SemanticChild::Interior(hash) => stack.push(hash),
877                SemanticChild::Leaf(hash) => {
878                    excluded.insert(hash);
879                }
880                SemanticChild::BindingDelta(hash) | SemanticChild::ImporterIndex(hash) => {
881                    excluded.insert(hash);
882                }
883            }
884        }
885    }
886    Ok(())
887}
888
889fn object_info_from_event(
890    store: &impl ObjectStore,
891    event: StateClosureEvent<'_>,
892) -> Result<Option<ObjectInfo>> {
893    match event {
894        StateClosureEvent::State { id, state } => {
895            let state_bytes = state.encode_current_msgpack()?;
896            Ok(Some(ObjectInfo {
897                id: ObjectId::StateId(id),
898                obj_type: ObjectType::State,
899                size: state_bytes.len() as u64,
900                delta_base: None,
901            }))
902        }
903        StateClosureEvent::Tree {
904            hash,
905            storage_size,
906            delta_base,
907        } => Ok(Some(ObjectInfo {
908            id: ObjectId::Hash(hash),
909            obj_type: ObjectType::Tree,
910            size: storage_size,
911            delta_base,
912        })),
913        StateClosureEvent::Blob { hash, .. } => {
914            let Some(blob) = store.get_blob(&hash)? else {
915                if blob_has_purge_evidence(store, &hash)? {
916                    return Ok(None);
917                }
918                return Err(missing_blob(hash));
919            };
920            Ok(Some(ObjectInfo {
921                id: ObjectId::Hash(hash),
922                obj_type: ObjectType::Blob,
923                size: blob.size() as u64,
924                delta_base: None,
925            }))
926        }
927        StateClosureEvent::Redaction { blob } => Ok(store
928            .get_redactions_bytes_for_blob(&blob)?
929            .map(|bytes| ObjectInfo {
930                id: ObjectId::Hash(blob),
931                obj_type: ObjectType::Redaction,
932                size: bytes.len() as u64,
933                delta_base: None,
934            })),
935        StateClosureEvent::StateVisibility { state } => Ok(store
936            .get_state_visibility_bytes_for_state(&state)?
937            .map(|bytes| ObjectInfo {
938                id: ObjectId::StateId(state),
939                obj_type: ObjectType::StateVisibility,
940                size: bytes.len() as u64,
941                delta_base: None,
942            })),
943        StateClosureEvent::StateAttachment { state, attachment } => {
944            let bytes = attachment.encode_current_msgpack()?;
945            Ok(Some(ObjectInfo {
946                id: ObjectId::StateAttachment {
947                    state,
948                    id: attachment.id(),
949                    kind: attachment.body.kind(),
950                },
951                obj_type: ObjectType::StateAttachment,
952                size: bytes.len() as u64,
953                delta_base: None,
954            }))
955        }
956        StateClosureEvent::ExcludedState { id } => {
957            let _ = id;
958            Ok(None)
959        }
960        StateClosureEvent::ExcludedHash { hash } => {
961            let _ = hash;
962            Ok(None)
963        }
964    }
965}
966
967fn planned_object_from_event(
968    store: &impl ObjectStore,
969    event: StateClosureEvent<'_>,
970) -> Result<Option<PlannedObject>> {
971    match event {
972        StateClosureEvent::State { id, .. } => Ok(Some(PlannedObject {
973            id: ObjectId::StateId(id),
974            obj_type: ObjectType::State,
975        })),
976        StateClosureEvent::Tree { hash, .. } => Ok(Some(PlannedObject {
977            id: ObjectId::Hash(hash),
978            obj_type: ObjectType::Tree,
979        })),
980        StateClosureEvent::Blob { hash, .. } => {
981            if store.get_blob(&hash)?.is_none() {
982                if blob_has_purge_evidence(store, &hash)? {
983                    return Ok(None);
984                }
985                return Err(missing_blob(hash));
986            }
987            Ok(Some(PlannedObject {
988                id: ObjectId::Hash(hash),
989                obj_type: ObjectType::Blob,
990            }))
991        }
992        StateClosureEvent::Redaction { blob } => Ok(Some(PlannedObject {
993            id: ObjectId::Hash(blob),
994            obj_type: ObjectType::Redaction,
995        })),
996        StateClosureEvent::StateVisibility { state } => Ok(Some(PlannedObject {
997            id: ObjectId::StateId(state),
998            obj_type: ObjectType::StateVisibility,
999        })),
1000        StateClosureEvent::StateAttachment { state, attachment } => Ok(Some(PlannedObject {
1001            id: ObjectId::StateAttachment {
1002                state,
1003                id: attachment.id(),
1004                kind: attachment.body.kind(),
1005            },
1006            obj_type: ObjectType::StateAttachment,
1007        })),
1008        StateClosureEvent::ExcludedState { id } => {
1009            let _ = id;
1010            Ok(None)
1011        }
1012        StateClosureEvent::ExcludedHash { hash } => {
1013            let _ = hash;
1014            Ok(None)
1015        }
1016    }
1017}
1018
1019/// A purged blob is intentionally absent from the object closure; its sidecar
1020/// remains and is verified by the receiver before the absence is accepted.
1021/// Mere redaction never excuses a missing blob.
1022fn missing_blob(hash: ContentHash) -> HeddleError {
1023    HeddleError::MissingObject {
1024        object_type: "blob".to_string(),
1025        id: hash.to_hex(),
1026    }
1027}
1028
1029fn blob_has_purge_evidence(store: &impl ObjectStore, hash: &ContentHash) -> Result<bool> {
1030    let Some(bytes) = store.get_redactions_bytes_for_blob(hash)? else {
1031        return Ok(false);
1032    };
1033    let redactions = RedactionsBlob::decode(&bytes).map_err(|error| {
1034        HeddleError::InvalidObject(format!(
1035            "invalid redaction sidecar for missing blob {}: {error}",
1036            hash.to_hex()
1037        ))
1038    })?;
1039    Ok(redactions
1040        .redactions
1041        .iter()
1042        .any(|redaction| redaction.redacted_blob == *hash && redaction.is_purged()))
1043}
1044
1045pub fn missing_blobs_in_tree(
1046    store: &impl ObjectStore,
1047    tree_hash: ContentHash,
1048) -> Result<Vec<ContentHash>> {
1049    let mut missing = Vec::new();
1050    collect_missing_blobs_recursive(store, &tree_hash, &mut missing)?;
1051    Ok(missing)
1052}
1053
1054fn collect_missing_blobs_recursive(
1055    store: &impl ObjectStore,
1056    tree_hash: &ContentHash,
1057    missing: &mut Vec<ContentHash>,
1058) -> Result<()> {
1059    let tree = store.require_tree(tree_hash)?;
1060
1061    for entry in tree.entries() {
1062        match entry.target() {
1063            TreeEntryTarget::Blob { hash, .. } | TreeEntryTarget::Symlink { hash } => {
1064                if !store.has_blob(hash).map_err(|err| {
1065                    HeddleError::InvalidObject(format!(
1066                        "check blob {} while collecting lazy hydration missing blobs: {err}",
1067                        hash.to_hex()
1068                    ))
1069                })? {
1070                    missing.push(*hash);
1071                }
1072            }
1073            TreeEntryTarget::Tree { hash } => {
1074                collect_missing_blobs_recursive(store, hash, missing)?;
1075            }
1076            TreeEntryTarget::Gitlink { .. } => {}
1077            // Native child-spool edge: its target lives in a separate spool
1078            // object graph, not this store, so it is not walked here.
1079            TreeEntryTarget::Spoollink { .. } => {}
1080        }
1081    }
1082    Ok(())
1083}
1084
1085fn collect_excluded(
1086    store: &impl ObjectStore,
1087    roots: &[StateId],
1088) -> Result<(HashSet<StateId>, HashSet<ContentHash>)> {
1089    if roots.is_empty() {
1090        return Ok((HashSet::new(), HashSet::new()));
1091    }
1092
1093    let mut excluded_states: HashSet<StateId> = HashSet::new();
1094    let mut excluded_hashes: HashSet<ContentHash> = HashSet::new();
1095    let mut queue: VecDeque<StateId> = VecDeque::new();
1096
1097    for id in roots {
1098        queue.push_back(*id);
1099    }
1100
1101    while let Some(id) = queue.pop_front() {
1102        if !excluded_states.insert(id) {
1103            continue;
1104        }
1105
1106        let state = match store.get_state(&id)? {
1107            Some(state) => state,
1108            None => continue,
1109        };
1110
1111        for parent in &state.parents {
1112            queue.push_back(*parent);
1113        }
1114
1115        collect_tree_hashes(store, state.tree, &mut excluded_hashes)?;
1116        if let Some(provenance_root) = state.provenance {
1117            collect_tree_hashes(store, provenance_root, &mut excluded_hashes)?;
1118        }
1119        for attachment in store.list_state_attachments(&id)? {
1120            match attachment.body {
1121                StateAttachmentBody::Context(root) => {
1122                    collect_tree_hashes(store, root, &mut excluded_hashes)?
1123                }
1124                StateAttachmentBody::RiskSignals(hash)
1125                | StateAttachmentBody::ReviewSignatures(hash)
1126                | StateAttachmentBody::Discussions(hash)
1127                | StateAttachmentBody::StructuredConflicts(hash)
1128                | StateAttachmentBody::ContextConsumption(hash) => {
1129                    excluded_hashes.insert(hash);
1130                }
1131                StateAttachmentBody::SemanticIndex(root) => {
1132                    collect_semantic_hashes(store, root, &mut excluded_hashes)?;
1133                }
1134                StateAttachmentBody::Signature(_) => {}
1135            }
1136        }
1137    }
1138
1139    Ok((excluded_states, excluded_hashes))
1140}
1141
1142fn collect_tree_hashes(
1143    store: &impl ObjectStore,
1144    tree_hash: ContentHash,
1145    excluded: &mut HashSet<ContentHash>,
1146) -> Result<()> {
1147    if !excluded.insert(tree_hash) {
1148        return Ok(());
1149    }
1150
1151    let tree = store.require_tree(&tree_hash)?;
1152
1153    for entry in tree.entries() {
1154        match entry.target() {
1155            TreeEntryTarget::Blob { hash, .. } | TreeEntryTarget::Symlink { hash } => {
1156                excluded.insert(*hash);
1157            }
1158            TreeEntryTarget::Tree { hash } => {
1159                collect_tree_hashes(store, *hash, excluded)?;
1160            }
1161            TreeEntryTarget::Gitlink { .. } => {}
1162            // Native child-spool edge: its target lives in a separate spool
1163            // object graph, not this store, so it is not walked here.
1164            TreeEntryTarget::Spoollink { .. } => {}
1165        }
1166    }
1167
1168    Ok(())
1169}
1170
1171pub fn is_ancestor(
1172    store: &impl ObjectStore,
1173    ancestor: StateId,
1174    descendant: StateId,
1175) -> Result<bool> {
1176    walk_ancestor(ancestor, descendant, |id| ObjectStore::get_state(store, id))
1177}
1178
1179/// Walk ancestry against a read-only object source, including hosted stores.
1180pub fn is_ancestor_from_source(
1181    source: &(impl ObjectSource + ?Sized),
1182    ancestor: StateId,
1183    descendant: StateId,
1184) -> Result<bool> {
1185    walk_ancestor(ancestor, descendant, |id| source.get_state(id))
1186}
1187
1188/// Caller-owned limits for an async ancestry traversal. The source controls
1189/// its own I/O timeout; these checks run between completed reads.
1190#[cfg(feature = "async-source")]
1191#[derive(Clone, Debug)]
1192pub struct AncestryBudget {
1193    pub max_states: usize,
1194    pub cancelled: Arc<AtomicBool>,
1195    pub deadline: Option<Instant>,
1196}
1197
1198#[cfg(feature = "async-source")]
1199#[derive(Debug, thiserror::Error)]
1200pub enum AncestryError {
1201    #[error("ancestry traversal cancelled")]
1202    Cancelled,
1203    #[error("ancestry traversal deadline exceeded")]
1204    Deadline,
1205    #[error("ancestry work limit exhausted")]
1206    WorkLimit,
1207    #[error(transparent)]
1208    Source(#[from] HeddleError),
1209}
1210
1211/// Walk ancestry with caller-supplied work and interruption bounds. Missing
1212/// states (including parents) terminate only that branch; `Ok(false)` means
1213/// all reachable branches completed under the supplied budget.
1214#[cfg(feature = "async-source")]
1215pub async fn is_ancestor_async_bounded<S>(
1216    source: &S,
1217    ancestor: &StateId,
1218    descendant: &StateId,
1219    budget: &AncestryBudget,
1220) -> std::result::Result<bool, AncestryError>
1221where
1222    S: AsyncObjectSource + ?Sized,
1223{
1224    if ancestor == descendant {
1225        return Ok(true);
1226    }
1227    let check_interruption = || {
1228        if budget.cancelled.load(Ordering::Acquire) {
1229            return Err(AncestryError::Cancelled);
1230        }
1231        if budget
1232            .deadline
1233            .is_some_and(|deadline| Instant::now() >= deadline)
1234        {
1235            return Err(AncestryError::Deadline);
1236        }
1237        Ok(())
1238    };
1239    let mut seen = HashSet::new();
1240    let mut stack = vec![*descendant];
1241    while let Some(id) = stack.pop() {
1242        check_interruption()?;
1243        if !seen.insert(id) {
1244            continue;
1245        }
1246        if seen.len() > budget.max_states {
1247            return Err(AncestryError::WorkLimit);
1248        }
1249        let state = source.get_state(&id).await?;
1250        check_interruption()?;
1251        let Some(state) = state else {
1252            continue;
1253        };
1254        heddle_perf_contract::record_history_object_decode();
1255        if id == *ancestor {
1256            return Ok(true);
1257        }
1258        stack.extend(state.parents);
1259    }
1260    Ok(false)
1261}
1262
1263/// Unbounded compatibility entry point for local callers. Hosted callers
1264/// should use [`is_ancestor_async_bounded`].
1265#[cfg(feature = "async-source")]
1266pub async fn is_ancestor_async<S>(
1267    source: &S,
1268    ancestor: &StateId,
1269    descendant: &StateId,
1270) -> Result<bool>
1271where
1272    S: AsyncObjectSource + ?Sized,
1273{
1274    let budget = AncestryBudget {
1275        max_states: usize::MAX,
1276        cancelled: Arc::new(AtomicBool::new(false)),
1277        deadline: None,
1278    };
1279    is_ancestor_async_bounded(source, ancestor, descendant, &budget)
1280        .await
1281        .map_err(|error| match error {
1282            AncestryError::Source(error) => error,
1283            other => HeddleError::InvalidObject(other.to_string()),
1284        })
1285}
1286
1287fn walk_ancestor(
1288    ancestor: StateId,
1289    descendant: StateId,
1290    mut get_state: impl FnMut(&StateId) -> Result<Option<State>>,
1291) -> Result<bool> {
1292    if ancestor == descendant {
1293        return Ok(true);
1294    }
1295
1296    let mut seen: HashSet<StateId> = HashSet::new();
1297    let mut queue: VecDeque<StateId> = VecDeque::new();
1298    queue.push_back(descendant);
1299
1300    while let Some(id) = queue.pop_front() {
1301        if !seen.insert(id) {
1302            continue;
1303        }
1304        let state = match get_state(&id)? {
1305            Some(s) => s,
1306            None => return Ok(false),
1307        };
1308        for parent in state.parents {
1309            if parent == ancestor {
1310                return Ok(true);
1311            }
1312            queue.push_back(parent);
1313        }
1314    }
1315
1316    Ok(false)
1317}
1318
1319#[cfg(all(test, feature = "async-source"))]
1320mod async_ancestry_tests {
1321    use std::{
1322        collections::HashMap,
1323        future::Future,
1324        sync::atomic::AtomicUsize,
1325        task::{Context, Poll, Waker},
1326    };
1327
1328    use super::*;
1329    use crate::object::{Attribution, Blob, Principal, Tree};
1330
1331    struct Source {
1332        states: HashMap<StateId, State>,
1333        reads: AtomicUsize,
1334        fail: Option<StateId>,
1335        cancel: Option<Arc<AtomicBool>>,
1336    }
1337
1338    impl AsyncObjectSource for Source {
1339        async fn get_tree(&self, _: &ContentHash) -> Result<Option<Tree>> {
1340            Ok(None)
1341        }
1342        async fn get_blob(&self, _: &ContentHash) -> Result<Option<Blob>> {
1343            Ok(None)
1344        }
1345        async fn get_state(&self, id: &StateId) -> Result<Option<State>> {
1346            self.reads.fetch_add(1, Ordering::Relaxed);
1347            if self.fail == Some(*id) {
1348                return Err(HeddleError::InvalidObject("source failed".into()));
1349            }
1350            if let Some(cancel) = &self.cancel {
1351                cancel.store(true, Ordering::Release);
1352            }
1353            Ok(self.states.get(id).cloned())
1354        }
1355    }
1356
1357    fn run<T>(future: impl Future<Output = T>) -> T {
1358        let mut future = Box::pin(future);
1359        let mut context = Context::from_waker(Waker::noop());
1360        loop {
1361            match future.as_mut().poll(&mut context) {
1362                Poll::Ready(value) => return value,
1363                Poll::Pending => std::thread::yield_now(),
1364            }
1365        }
1366    }
1367
1368    fn state(name: &str, parents: Vec<StateId>) -> State {
1369        State::new(
1370            Tree::new().hash(),
1371            parents,
1372            Attribution::human(Principal::new(name, "test@example.com")),
1373        )
1374    }
1375
1376    fn budget(limit: usize) -> AncestryBudget {
1377        AncestryBudget {
1378            max_states: limit,
1379            cancelled: Arc::new(AtomicBool::new(false)),
1380            deadline: None,
1381        }
1382    }
1383
1384    #[test]
1385    fn bounded_walk_distinguishes_complete_missing_error_and_interruption() {
1386        let root = state("root", vec![]);
1387        let left = state("left", vec![root.id()]);
1388        let right = state("right", vec![root.id()]);
1389        let merge = state("merge", vec![left.id(), right.id()]);
1390        let missing = state("missing", vec![]).id();
1391        let states = [root.clone(), left.clone(), right.clone(), merge.clone()]
1392            .into_iter()
1393            .map(|state| (state.id(), state))
1394            .collect();
1395        let mut source = Source {
1396            states,
1397            reads: AtomicUsize::new(0),
1398            fail: None,
1399            cancel: None,
1400        };
1401        assert!(
1402            run(is_ancestor_async_bounded(
1403                &source,
1404                &merge.id(),
1405                &merge.id(),
1406                &budget(0)
1407            ))
1408            .unwrap()
1409        );
1410        assert_eq!(source.reads.load(Ordering::Relaxed), 0);
1411
1412        assert!(
1413            run(is_ancestor_async_bounded(
1414                &source,
1415                &root.id(),
1416                &merge.id(),
1417                &budget(4)
1418            ))
1419            .unwrap()
1420        );
1421        source.states.remove(&root.id());
1422        assert!(
1423            !run(is_ancestor_async_bounded(
1424                &source,
1425                &root.id(),
1426                &merge.id(),
1427                &budget(4)
1428            ))
1429            .unwrap()
1430        );
1431        source.states.insert(root.id(), root.clone());
1432        assert!(
1433            !run(is_ancestor_async_bounded(
1434                &source,
1435                &merge.id(),
1436                &left.id(),
1437                &budget(4)
1438            ))
1439            .unwrap()
1440        );
1441        assert!(
1442            !run(is_ancestor_async_bounded(
1443                &source,
1444                &missing,
1445                &merge.id(),
1446                &budget(5)
1447            ))
1448            .unwrap()
1449        );
1450        assert!(matches!(
1451            run(is_ancestor_async_bounded(
1452                &source,
1453                &root.id(),
1454                &merge.id(),
1455                &budget(1)
1456            )),
1457            Err(AncestryError::WorkLimit)
1458        ));
1459
1460        source.fail = Some(merge.id());
1461        assert!(matches!(
1462            run(is_ancestor_async_bounded(
1463                &source,
1464                &root.id(),
1465                &merge.id(),
1466                &budget(4)
1467            )),
1468            Err(AncestryError::Source(_))
1469        ));
1470        source.fail = None;
1471
1472        let cancelled = budget(4);
1473        cancelled.cancelled.store(true, Ordering::Release);
1474        let before = source.reads.load(Ordering::Relaxed);
1475        assert!(matches!(
1476            run(is_ancestor_async_bounded(
1477                &source,
1478                &root.id(),
1479                &merge.id(),
1480                &cancelled
1481            )),
1482            Err(AncestryError::Cancelled)
1483        ));
1484        assert_eq!(source.reads.load(Ordering::Relaxed), before);
1485
1486        let mut expired = budget(4);
1487        expired.deadline = Some(Instant::now());
1488        assert!(matches!(
1489            run(is_ancestor_async_bounded(
1490                &source,
1491                &root.id(),
1492                &merge.id(),
1493                &expired
1494            )),
1495            Err(AncestryError::Deadline)
1496        ));
1497
1498        let mid_cancel = budget(4);
1499        source.cancel = Some(mid_cancel.cancelled.clone());
1500        assert!(matches!(
1501            run(is_ancestor_async_bounded(
1502                &source,
1503                &root.id(),
1504                &merge.id(),
1505                &mid_cancel
1506            )),
1507            Err(AncestryError::Cancelled)
1508        ));
1509    }
1510}