Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

191 KB
Raw Blame
use crate::engine::runtime::get_runtime;
use crate::prelude::*;
use crate::state_store::WriteScope;
use std::collections::{HashMap, HashSet};
use std::pin::Pin;
use std::sync::Weak;

use crate::engine::context::FnCallContext;
use crate::engine::context::{
    AppContext, ComponentProcessingAction, ComponentProcessingMode, ComponentProcessorContext,
    MemoStatesPayload, PreviewActionCollector,
};
use crate::engine::deadline::DeadlineContext;
use crate::engine::execution::{
    ChildDeletes, OpenDescendantsVerdict, RestoredComponentMemo, cleanup_tombstone,
    delete_component_memo, eager_existence_upsert, post_submit_for_build, submit,
    update_component_memo_states, use_or_invalidate_component_memoization,
    validate_open_descendants,
};
use crate::engine::profile::EngineProfile;
use crate::engine::stats::ProcessingStats;
use crate::engine::target_state::{TargetStateProvider, TargetStateProviderRegistry};
use crate::state::component_selector::{ComponentSelection, ComponentSelector, MountDecision};
use crate::state::stable_path::{StablePath, StablePathRef};
use crate::state::stable_path_set::StablePathSet;
use crate::state::target_state_path::{TargetProviderDeps, TargetStatePath};
use cocoindex_utils::error::{SharedError, SharedResult, SharedResultExt};
use cocoindex_utils::fingerprint::Fingerprint;

/// Async on-error callback for background-style component execution.
///
/// Invoked by `run_in_background` / `delete` when the spawned task fails
/// (other than via cancellation, which is filtered). The callback can
/// either:
///
/// - Return `Ok(())` to swallow the failure (mount-style; the spawned
///   task returns Ok and `handle.ready()` resolves Ok). This is what
///   the Python-side exception handler chain does when at least one
///   handler returns normally.
/// - Return `Err(err)` to propagate the failure (the spawned task
///   returns Err and `handle.ready()` raises). This is what the chain
///   does when every handler re-raises, and what `app.drop()`'s
///   built-in raising handler does to surface root-delete failures.
///
/// Cancellation is never delivered to the handler β€” it's filtered
/// before this is invoked. The "no chain registered" case logs at
/// ERROR and swallows; only an explicitly-installed handler causes
/// propagation.
pub type OnError = Arc<
    dyn Fn(Error) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>
        + Send
        + Sync
        + 'static,
>;

#[derive(Debug, Clone)]
pub struct ComponentProcessorInfo {
    pub name: String,
}

impl ComponentProcessorInfo {
    pub fn new(name: String) -> Self {
        Self { name }
    }
}

pub trait ComponentProcessor<Prof: EngineProfile>: Send + Sync + 'static {
    // TODO: Add method to expose function info and arguments, for tracing purpose & no-change detection.

    /// Run the logic to build the component.
    ///
    /// We expect the implementation of this method to spawn the logic to a separate thread or task when needed.
    fn process(
        &self,
        host_runtime_ctx: &Prof::HostRuntimeCtx,
        comp_ctx: &ComponentProcessorContext<Prof>,
    ) -> Result<impl Future<Output = Result<Prof::FunctionData>> + Send + 'static>;

    /// Fingerprint of the memoization key. When matching, re-processing can be skipped.
    /// When None, memoization is not enabled for the component.
    fn memo_key_fingerprint(&self) -> Option<Fingerprint>;

    fn processor_info(&self) -> &ComponentProcessorInfo;

    /// Whether this processor has a memo state handler for post-fingerprint validation.
    fn has_memo_state_handler(&self) -> bool {
        false
    }

    /// Whether `handle_memo_states(None)` has initial states to collect after
    /// a miss. A processor whose handler only validates on a hit (one with
    /// neither argument nor context state functions, attached because a
    /// stored entry may carry data dependencies) returns false, and the miss
    /// path skips the call.
    fn collects_initial_states(&self) -> bool {
        self.has_memo_state_handler()
    }

    /// Validate or collect memo states after a fingerprint match.
    /// `stored_states`: `Some(payload)` on cache hit, `None` on cache miss (collect initial states).
    /// Returns `(new_states, can_reuse, states_changed)`:
    /// - `can_reuse`: when true, the cached value is valid and can be returned without re-execution.
    /// - `states_changed`: when true, the new states differ from stored states and must be persisted.
    ///   This can be true even when `can_reuse` is true (e.g. mtime changed but content hash unchanged).
    ///
    /// The payload carries both positional (argument-borne) and context-borne memo states.
    /// The core crate treats everything inside as opaque blobs β€” state functions themselves
    /// live Python-side in the Python profile.
    fn handle_memo_states(
        &self,
        host_runtime_ctx: &Prof::HostRuntimeCtx,
        comp_ctx: &ComponentProcessorContext<Prof>,
        stored_states: Option<MemoStatesPayload<Prof>>,
    ) -> Result<impl Future<Output = Result<(MemoStatesPayload<Prof>, bool, bool)>> + Send + 'static>
    {
        let _ = (host_runtime_ctx, comp_ctx, stored_states);
        Ok(async { Ok((MemoStatesPayload::default(), true, false)) })
    }
}

struct ComponentInner<Prof: EngineProfile> {
    app_ctx: AppContext<Prof>,
    stable_path: StablePath,

    /// Strong reference to the parent component. Keeps the parent (and its
    /// ancestors) alive as long as this child is alive. On Drop, removes
    /// this child's Weak entry from the parent's active_children.
    parent: Option<Component<Prof>>,

    /// Serializes runs of this component. A run holds the permit from before
    /// its body starts until its memo is stored (see `execute_once`), so two
    /// runs never overlap, and the memo one run stores is in place before the
    /// next decides whether to execute its body.
    build_semaphore: tokio::sync::Semaphore,
    /// The memo most recently stored under `build_semaphore`, if any. A run
    /// that finds its own key here on acquiring the permit, stored since its
    /// memo fast path looked, knows a same-key run just completed and stored
    /// its result, so it re-checks the memo instead of executing again β€” under
    /// `full_reprocess` only when that run belonged to the same operation (see
    /// `execute_once`).
    last_stored_memos: Mutex<LastStoredMemos>,

    /// Identity registry of child components, keyed by their full StablePath,
    /// so a re-mount of a path whose component is still referenced shares the
    /// same `ComponentInner` (and thus its `build_semaphore`). Weak: entries
    /// are removed by the child's Drop impl. This map says nothing about
    /// activity β€” see `active_ops`.
    ///
    /// `parking_lot::Mutex` (non-poisoning): the Drop impl below acquires this
    /// lock, and a poisoned `std::sync::Mutex` would cascade panics through
    /// every subsequent Drop on the same parent's children map.
    active_children: parking_lot::Mutex<HashMap<StablePath, Weak<ComponentInner<Prof>>>>,

    /// Shared state for a live component running at this path.
    /// `parking_lot::Mutex` (non-poisoning): symmetric with `active_children`,
    /// since cancel/drain paths can lock this from `Drop` as well.
    live_state:
        parking_lot::Mutex<Option<Arc<crate::engine::live_component::LiveComponentState<Prof>>>>,

    /// Number of processing tasks in flight in this component's subtree
    /// (itself and every descendant), maintained by [`ActivityGuard`]. This β€”
    /// not the reference count of `inner` β€” is what "active" means: anything
    /// may hold a `Component` or a processor context for as long as it likes
    /// (a host-language exception traceback, a stored handle) without keeping
    /// the component active.
    active_ops: std::sync::atomic::AtomicUsize,
    /// Signaled when `active_ops` drops to zero (see `wait_until_inactive`).
    inactive: tokio::sync::Notify,
    /// Number of runs of this component itself (not its descendants) in
    /// flight, maintained by [`RunGuard`]. A run that starts while another is
    /// in flight will queue on `build_semaphore` behind it, so it is admitted
    /// to the in-flight pool lazily, only if it turns out to execute.
    active_runs: std::sync::atomic::AtomicUsize,
}

/// Marks a processing task as in flight on a component for the guard's
/// lifetime. A task's entry point creates it before spawning the task and drops
/// it when the task ends β€” on every exit path, including cancellation and
/// panics β€” so activity is accounted for deterministically, independent of who
/// else holds the component.
///
/// Counts on the component and each of its ancestors, so a component is active
/// while anything in its subtree runs (`wait_until_inactive`, [`StatsGroup`]
/// member liveness).
pub(crate) struct ActivityGuard<Prof: EngineProfile> {
    component: Component<Prof>,
}

impl<Prof: EngineProfile> ActivityGuard<Prof> {
    pub(crate) fn new(component: Component<Prof>) -> Self {
        for inner in component.self_and_ancestors() {
            inner
                .active_ops
                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        }
        Self { component }
    }
}

/// Counts a run of a component (`ComponentInner::active_runs`) from its
/// entry point until it ends.
struct RunGuard<Prof: EngineProfile> {
    component: Component<Prof>,
    /// Another run of the same component was in flight when this one started.
    concurrent: bool,
}

impl<Prof: EngineProfile> RunGuard<Prof> {
    fn new(component: Component<Prof>) -> Self {
        let previous = component
            .inner
            .active_runs
            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        Self {
            component,
            concurrent: previous > 0,
        }
    }
}

impl<Prof: EngineProfile> Drop for RunGuard<Prof> {
    fn drop(&mut self) {
        self.component
            .inner
            .active_runs
            .fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
    }
}

/// What a processing task holds from its entry point until it ends
/// (see [`Component::start_task`]).
struct StartedTask<Prof: EngineProfile> {
    /// Keeps the component and its ancestors active; the task drops it right
    /// before resolving child readiness.
    activity: ActivityGuard<Prof>,
    /// Counts this run on the component; dropped with `activity`.
    run: RunGuard<Prof>,
    /// Registration with the parent's readiness accumulator; `None` for the root.
    child_readiness: Option<ComponentBgChildReadinessChildGuard>,
}

impl<Prof: EngineProfile> Drop for ActivityGuard<Prof> {
    fn drop(&mut self) {
        for inner in self.component.self_and_ancestors() {
            if inner
                .active_ops
                .fetch_sub(1, std::sync::atomic::Ordering::SeqCst)
                == 1
            {
                inner.inactive.notify_waiters();
            }
        }
    }
}

impl<Prof: EngineProfile> Drop for ComponentInner<Prof> {
    fn drop(&mut self) {
        if let Some(parent) = &self.parent {
            // Identity check: only remove our own entry. A previous
            // `get_child(stable_path)` may have observed our `Weak` failing to
            // upgrade (strong_count hit zero) and inserted a *new* `Weak` at
            // the same key BEFORE this Drop ran. Removing by key alone would
            // erroneously delete the new entry. Compare the stored Weak's
            // pointer against `self` to remove only if the slot still
            // identifies us.
            let mut children = parent.inner.active_children.lock();
            if let Some(weak) = children.get(&self.stable_path)
                && std::ptr::eq(weak.as_ptr(), self as *const ComponentInner<Prof>)
            {
                children.remove(&self.stable_path);
            }
        }
    }
}

#[derive(Clone)]
pub struct Component<Prof: EngineProfile> {
    inner: Arc<ComponentInner<Prof>>,
}

struct ComponentBgChildReadinessState {
    remaining_count: usize,
    build_done: bool,
    is_readiness_set: bool,
    outcome: ComponentRunOutcome,
}

impl ComponentBgChildReadinessState {
    fn maybe_set_readiness(
        &mut self,
        result: Option<Result<ComponentRunOutcome, SharedError>>,
        readiness: &tokio::sync::SetOnce<SharedResult<ComponentRunOutcome>>,
    ) {
        if self.is_readiness_set {
            return;
        }
        if let Some(result) = result {
            if let Ok(outcome) = result {
                self.outcome.merge(outcome);
            } else {
                self.is_readiness_set = true;
                readiness.set(result).expect("readiness set more than once");
                return;
            }
        }
        if self.remaining_count == 0 && self.build_done {
            self.is_readiness_set = true;
            readiness
                .set(Ok(std::mem::take(&mut self.outcome)))
                .expect("readiness set more than once");
        }
    }
}

#[derive(Debug, Default, Clone)]
pub(crate) struct ComponentRunOutcome {
    has_exception: bool,
    logic_deps: HashSet<Fingerprint>,
    target_provider_deps: TargetProviderDeps,
    /// The component, or a descendant, recorded data dependencies. A parent
    /// stores its memo flagged `has_open_descendants` and lists the child
    /// among its `open_children`; its next probe reuses the memo only after
    /// validating that child's records from the child's own row, since a
    /// reuse carries the child over without mounting it. Records themselves
    /// never travel upward.
    cannot_skip: bool,
    /// In a parent's accumulated children outcome: the paths, relative to the
    /// parent, of the direct children that reported `cannot_skip`. Set by the
    /// child's readiness guard when the child's outcome is merged (see
    /// `ComponentBgChildReadinessChildGuard::resolve_result`), so an
    /// outcome's own list is never what a component reports upward about
    /// itself: a component is listed by its parent, not by its own outcome.
    open_children: Vec<StablePath>,
    /// A selector left out a child of the component or of a descendant, so the
    /// subtree is not up to date: no memo may say it is.
    left_out_children: bool,
}

impl ComponentRunOutcome {
    fn exception() -> Self {
        Self {
            has_exception: true,
            ..Default::default()
        }
    }

    /// Outcome for a component that hit its memo cache: no exception, but it
    /// still reports the stored logic dependency set so a mounting parent's
    /// memo depends on this subtree β€” and likewise its target-provider deps, so
    /// a parent that later memo-hits (and therefore never mounts this child)
    /// still re-checks the provider generations this child declared against.
    fn reused(
        logic_deps: Vec<Fingerprint>,
        target_provider_deps: TargetProviderDeps,
        cannot_skip: bool,
    ) -> Self {
        Self {
            has_exception: false,
            logic_deps: logic_deps.into_iter().collect(),
            target_provider_deps,
            cannot_skip,
            open_children: Vec::new(),
            left_out_children: false,
        }
    }

    fn merge(&mut self, other: Self) {
        self.has_exception |= other.has_exception;
        self.logic_deps.extend(other.logic_deps);
        self.target_provider_deps.extend(other.target_provider_deps);
        self.cannot_skip |= other.cannot_skip;
        self.open_children.extend(other.open_children);
        self.left_out_children |= other.left_out_children;
    }
}

struct ComponentBgChildReadinessInner {
    state: Mutex<ComponentBgChildReadinessState>,
    readiness: tokio::sync::SetOnce<SharedResult<ComponentRunOutcome>>,
}

#[derive(Clone)]
pub struct ComponentBgChildReadiness {
    inner: Arc<ComponentBgChildReadinessInner>,
}

pub struct ComponentBgChildReadinessChildGuard {
    readiness: ComponentBgChildReadiness,
    /// The child this guard stands for, relative to the component whose
    /// readiness this is: `Some` for a component's run, `None` for a
    /// forwarded aggregate (a `StatsGroup`, a live component's registration),
    /// whose outcome already carries the right `open_children`.
    child: Option<StablePath>,
    resolved: bool,
}

impl Drop for ComponentBgChildReadinessChildGuard {
    fn drop(&mut self) {
        if self.resolved {
            return;
        }
        let mut state = self.readiness.state().lock().unwrap();
        state.remaining_count -= 1;
        // state.maybe_set_readiness(None, self.readiness.readiness());
        state.maybe_set_readiness(
            Some(Err(SharedError::new(internal_error!(
                "Child component build cancelled"
            )))),
            self.readiness.readiness(),
        );
    }
}

impl ComponentBgChildReadinessChildGuard {
    pub(crate) fn resolve(self, outcome: ComponentRunOutcome) {
        self.resolve_result(Ok(outcome));
    }

    /// Like `resolve`, but propagates a full `SharedResult`: `Ok` merges the
    /// outcome (logic deps), `Err` fails the enclosing readiness. Used by a
    /// `StatsGroup` to forward its members' aggregate readiness to its parent.
    ///
    /// For a component's own guard the outcome's `open_children` is rewritten
    /// here: it becomes this child's relative path when the child reported
    /// `cannot_skip`, and empty otherwise. The outcome a component returns
    /// from `execute_once` is its *children* outcome (its own list), which
    /// must not leak into the parent's.
    pub(crate) fn resolve_result(mut self, mut result: SharedResult<ComponentRunOutcome>) {
        if let Some(child) = self.child.take()
            && let Ok(outcome) = &mut result
        {
            outcome.open_children = if outcome.cannot_skip {
                vec![child]
            } else {
                Vec::new()
            };
        }
        {
            let mut state = self.readiness.state().lock().unwrap();
            state.remaining_count -= 1;
            state.maybe_set_readiness(Some(result), self.readiness.readiness());
        }
        self.resolved = true;
    }
}

impl Default for ComponentBgChildReadiness {
    fn default() -> Self {
        Self {
            inner: Arc::new(ComponentBgChildReadinessInner {
                state: Mutex::new(ComponentBgChildReadinessState {
                    remaining_count: 0,
                    is_readiness_set: false,
                    build_done: false,
                    outcome: Default::default(),
                }),
                readiness: tokio::sync::SetOnce::new(),
            }),
        }
    }
}

impl ComponentBgChildReadiness {
    fn state(&self) -> &Mutex<ComponentBgChildReadinessState> {
        &self.inner.state
    }

    fn readiness(&self) -> &tokio::sync::SetOnce<SharedResult<ComponentRunOutcome>> {
        &self.inner.readiness
    }

    /// Register one pending child. `child` is the child's path relative to
    /// the component whose readiness this is, for a component's run; `None`
    /// for an aggregate forwarded as a unit (see
    /// `ComponentBgChildReadinessChildGuard::child`).
    pub fn add_child(self, child: Option<StablePath>) -> ComponentBgChildReadinessChildGuard {
        self.state().lock().unwrap().remaining_count += 1;
        ComponentBgChildReadinessChildGuard {
            readiness: self,
            child,
            resolved: false,
        }
    }

    fn set_build_done(&self) {
        let mut state = self.state().lock().unwrap();
        state.build_done = true;
        state.maybe_set_readiness(None, self.readiness());
    }
}

/// A named, separate stats aggregation scope created by `coco.stats_group(...)`.
/// Components mounted within the scope report into `stats` (split out of the
/// enclosing aggregate), register their initial readiness into `readiness`, and
/// are tracked for liveness in `active_members`. Shared (`Arc`) between the
/// substituted context view (which pushes members) and the spawned
/// group-lifecycle task (which awaits readiness, then the members' inactivity).
pub(crate) struct StatsGroup<Prof: EngineProfile> {
    stats: ProcessingStats,
    readiness: ComponentBgChildReadiness,
    active_members: parking_lot::Mutex<Vec<Weak<ComponentInner<Prof>>>>,
}

impl<Prof: EngineProfile> StatsGroup<Prof> {
    pub(crate) fn new(parent: &ProcessingStats) -> Self {
        Self {
            stats: ProcessingStats::new_in(parent),
            readiness: ComponentBgChildReadiness::default(),
            active_members: parking_lot::Mutex::new(Vec::new()),
        }
    }

    pub(crate) fn stats(&self) -> &ProcessingStats {
        &self.stats
    }

    pub(crate) fn readiness(&self) -> &ComponentBgChildReadiness {
        &self.readiness
    }

    /// Register a direct member for liveness tracking.
    pub(crate) fn push_member(&self, child: &Component<Prof>) {
        self.active_members.lock().push(child.downgrade_inner());
    }

    /// The most recently registered member that is still active, pruning
    /// finished members (inactive, or dropped) off the back as it scans. A
    /// member only becomes active again by being mounted again, which
    /// registers it again, so pruning is safe; each entry is removed at most
    /// once β‡’ amortized O(1) per registered member.
    fn last_active_member(&self) -> Option<Component<Prof>> {
        let mut members = self.active_members.lock();
        while let Some(last) = members.last() {
            if let Some(inner) = last.upgrade()
                && inner.active_ops.load(std::sync::atomic::Ordering::SeqCst) > 0
            {
                return Some(Component { inner });
            }
            members.pop();
        }
        None
    }

    /// Wait until no member (nor anything in a member's subtree) has a
    /// processing task in flight β€” the group's analogue of
    /// `Component::wait_until_inactive`.
    pub(crate) async fn wait_until_members_inactive(&self) {
        while let Some(member) = self.last_active_member() {
            member.wait_until_inactive().await;
        }
    }
}

impl<Prof: EngineProfile> ComponentProcessorContext<Prof> {
    /// Open a stats group rooted at this context. Returns a derived context view
    /// (whose mounts report into the group and register liveness with it) and
    /// the group's `ProcessingStats` (for the Python handle / watch).
    ///
    /// Spawns the group-lifecycle task, which mirrors the root's
    /// `notify_ready β†’ wait_until_inactive β†’ notify_terminated` flow but resolves
    /// the parent-readiness guard at READY (not at termination) so a live member
    /// can never deadlock the enclosing component's initial readiness.
    pub fn begin_stats_group(
        &self,
        title: String,
        report_to_stdout: bool,
        refresh_interval_secs: Option<f64>,
    ) -> (ComponentProcessorContext<Prof>, ProcessingStats) {
        let group = Arc::new(StatsGroup::new(self.processing_stats()));
        let group_stats = group.stats().clone();

        // The group counts as one pending child of the enclosing readiness, so
        // the parent component (or outer group) waits for it as a unit.
        let parent_guard = self.components_readiness().clone().add_child(None);

        let cancel_token = self.app_ctx().cancellation_token();
        let live = self.live();
        let lifecycle_group = group.clone();
        get_runtime().spawn(async move {
            // Fires once registration is closed (`set_build_done` via
            // `end_stats_group`) AND every member reached initial readiness.
            let outcome = lifecycle_group.readiness().readiness().wait().await.clone();
            lifecycle_group.stats().notify_ready();
            // Propagate readiness/logic-deps upward AT READY β€” decoupled from
            // termination, matching the root (app.rs).
            parent_guard.resolve_result(outcome);

            if live && !cancel_token.is_cancelled() {
                // Cancel-aware wait for the group's members to finish (the
                // group's analogue of `wait_until_inactive`).
                tokio::select! {
                    () = lifecycle_group.wait_until_members_inactive() => {}
                    () = cancel_token.cancelled() => {}
                }
            }
            lifecycle_group.stats().notify_terminated();
        });

        if report_to_stdout {
            crate::engine::progress_display::report_group_stats(
                group_stats.clone(),
                title,
                live,
                refresh_interval_secs,
            );
        }

        (self.with_stats_group(&group), group_stats)
    }

    /// Close the group opened by `begin_stats_group` for member registration.
    /// Non-blocking β€” readiness then resolves once the members finish.
    pub fn end_stats_group(&self) {
        self.components_readiness().set_build_done();
    }
}

pub struct ComponentMountRunHandle<Prof: EngineProfile> {
    join_handle: tokio::task::JoinHandle<Result<ComponentBuildOutput<Prof>>>,
    /// The waiting caller's deadline, checked post-wait in `result()`
    /// (caller-attributed: the child's committed success is preserved).
    /// Root runs store NONE here β€” the root's post-update observation
    /// point is `AppOpHandle::result()`.
    caller_deadline: DeadlineContext,
}

impl<Prof: EngineProfile> ComponentMountRunHandle<Prof> {
    pub async fn result(
        self,
        parent_context: Option<&ComponentProcessorContext<Prof>>,
    ) -> Result<Prof::FunctionData> {
        let output = self.join_handle.await??;
        if let Some(parent_context) = parent_context {
            parent_context.update_building_state(|building_state| {
                for target_state_path in
                    output.built_target_states_providers.curr_target_state_paths
                {
                    let Some(provider) = output
                        .built_target_states_providers
                        .providers
                        .get(&target_state_path)
                    else {
                        error!(
                            "target states provider not found for path {}",
                            target_state_path
                        );
                        continue;
                    };
                    building_state
                        .target_states
                        .provider_registry
                        .add(target_state_path, provider.clone())?;
                }
                Ok(())
            })?;
        }
        self.caller_deadline.check()?;
        Ok(output.ret)
    }
}

/// Whether a run reached every component under it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunCompleteness {
    /// The component and every component under it ran without a failure.
    Complete,
    /// The component or one under it failed, and the failure went to an
    /// exception handler that absorbed it, or to the log, rather than to the
    /// caller; or the run was cancelled.
    Incomplete,
}

pub struct ComponentExecutionHandle {
    fut: Pin<Box<dyn Future<Output = SharedResult<()>> + Send + Sync>>,
}

impl ComponentExecutionHandle {
    pub fn new(fut: impl Future<Output = SharedResult<()>> + Send + Sync + 'static) -> Self {
        Self { fut: Box::pin(fut) }
    }

    /// A handle for a mount that does nothing: there is nothing to wait for.
    pub(crate) fn finished() -> Self {
        Self::new(async { Ok(()) })
    }

    pub async fn ready(self) -> Result<()> {
        self.fut.await.into_result()
    }
}

struct ComponentBuildOutput<Prof: EngineProfile> {
    ret: Prof::FunctionData,
    built_target_states_providers: TargetStateProviderRegistry<Prof>,
}

/// A memo stored by a run of a component under its `build_semaphore`: the
/// operation that stored it and the key it was stored under.
#[derive(Clone, Copy, PartialEq, Eq)]
struct StoredMemo {
    operation_generation: u64,
    memo_fp: Fingerprint,
}

/// The latest memo a component stored in each place a run can read: LMDB,
/// which every run reads, and the overlay of one run that persists nothing
/// (a preview), which only that run reads. Kept apart so a preview's memo
/// does not displace the persisted one a queued update re-checks.
#[derive(Default)]
struct LastStoredMemos {
    persisted: Option<StoredMemo>,
    in_run: Option<(u64, StoredMemo)>,
}

impl LastStoredMemos {
    fn record(&mut self, scope: WriteScope, memo: StoredMemo) {
        match scope {
            WriteScope::Persisted => self.persisted = Some(memo),
            WriteScope::Run(run) => self.in_run = Some((run, memo)),
        }
    }

    /// Forget the memo recorded for `scope`: its row was deleted.
    fn forget(&mut self, scope: WriteScope) {
        match scope {
            WriteScope::Persisted => self.persisted = None,
            WriteScope::Run(run) => {
                if matches!(self.in_run, Some((r, _)) if r == run) {
                    self.in_run = None;
                }
            }
        }
    }

    /// The latest memo a run reading through `app_store` can find.
    fn readable_by(&self, app_store: &crate::state_store::AppStore) -> Option<StoredMemo> {
        match self.in_run {
            Some((run, memo)) if app_store.write_scope() == WriteScope::Run(run) => Some(memo),
            _ => self.persisted,
        }
    }
}

/// Result of looking up a component's memo for the processor about to run.
enum MemoLookup<Prof: EngineProfile> {
    /// A valid memo stands in for a run: report the stored run's outcome and
    /// output.
    Reuse(ComponentRunOutcome, ComponentBuildOutput<Prof>),
    /// No usable memo. `revalidated_states` is `Some` when a memo matched the
    /// key but its memo states no longer validate: the states collected during
    /// validation are then stored with the new memo, instead of being
    /// collected again once the body has run.
    Miss {
        revalidated_states: Option<MemoStatesPayload<Prof>>,
    },
}

/// How the permit-guarded part of `execute_once` ended.
enum GuardedRun<Prof: EngineProfile> {
    /// The body did not run: a run with the same memo key completed under the
    /// permit while this one waited for it, and its memo was reused.
    Reused(ComponentRunOutcome, ComponentBuildOutput<Prof>),
    /// The body ran (build mode), or the component was deleted (delete mode).
    Executed {
        children_outcome: ComponentRunOutcome,
        build_output: Option<ComponentBuildOutput<Prof>>,
        touched_previous_states: bool,
    },
}

/// The component's own memo states after its handler validated them as
/// reusable (see `lookup_component_memo`).
struct ValidatedOwnStates<Prof: EngineProfile> {
    /// The states as the handler returned them: the stored ones, or refreshed
    /// where a state moved while staying valid.
    states: MemoStatesPayload<Prof>,
    /// Some state moved; `states` should replace the stored ones on a reuse.
    states_changed: bool,
}

/// Look up the memo stored for `comp_ctx`'s component and, when `processor`
/// has a memo state handler, validate the stored memo states through it. A
/// stored memo whose key is not `memo_fp` β€” or any stored memo, when the
/// processor is not memoized (`memo_fp` is `None`) β€” is invalidated. A failure
/// to read or decode the memo is logged and counts as a miss; a failure in the
/// state handler propagates.
async fn lookup_component_memo<Prof: EngineProfile>(
    comp_ctx: &ComponentProcessorContext<Prof>,
    processor: &Prof::ComponentProc,
    memo_fp: Option<Fingerprint>,
) -> Result<MemoLookup<Prof>> {
    let memo = match use_or_invalidate_component_memoization(comp_ctx, memo_fp).await {
        Ok(memo) => memo,
        Err(err) => {
            error!("component memoization restore failed: {err:?}");
            None
        }
    };
    let Some(RestoredComponentMemo {
        ret,
        memo_states,
        logic_deps: stored_logic_deps,
        target_provider_deps: stored_provider_deps,
        row_fp,
        has_open_descendants,
        open_children,
    }) = memo
    else {
        return Ok(MemoLookup::Miss {
            revalidated_states: None,
        });
    };
    let has_own_data_deps = !memo_states.data_deps.is_empty();
    // The component's own entry first: its states and records, through its
    // processor. On a miss the states ride into the new memo; the data
    // dependencies do not: the body about to run records the set that
    // replaces them.
    let mut own_validation: Option<ValidatedOwnStates<Prof>> = None;
    if processor.has_memo_state_handler() && !memo_states.is_empty() {
        let fut = processor.handle_memo_states(
            comp_ctx.app_ctx().env().host_runtime_ctx(),
            comp_ctx,
            Some(memo_states),
        )?;
        let (states, can_reuse, states_changed) = fut.await?;
        if !can_reuse {
            return Ok(MemoLookup::Miss {
                revalidated_states: Some(MemoStatesPayload {
                    data_deps: Vec::new(),
                    ..states
                }),
            });
        }
        own_validation = Some(ValidatedOwnStates {
            states,
            states_changed,
        });
    }
    if has_open_descendants {
        // A descendant recorded data dependencies. Everything else a reuse
        // would carry over unvalidated is already covered here: a
        // descendant's logic and target-provider deps were merged into this
        // row when it was stored (`execute_once`), and its argument and
        // context memo states are the ancestor's inputs' doing, as for a
        // closed descendant. Its data-dependency records are the one thing
        // only its own row holds, so they are validated from there, by path,
        // down through every open descendant.
        if let OpenDescendantsVerdict::NotReusable(reason) =
            validate_open_descendants(comp_ctx, &open_children).await?
        {
            debug!("memo of {} is not reused: {reason}", comp_ctx.stable_path());
            return Ok(MemoLookup::Miss {
                revalidated_states: own_validation.map(|own| MemoStatesPayload {
                    data_deps: Vec::new(),
                    ..own.states
                }),
            });
        }
    }
    // Reusable, but the states themselves moved (e.g. an mtime changed
    // while the content hash did not): refresh them in the stored memo.
    if let Some(ValidatedOwnStates {
        states,
        states_changed: true,
    }) = &own_validation
    {
        let row_fp = row_fp.ok_or_else(|| {
            internal_error!("memo states changed for a memo row that stores none")
        })?;
        update_component_memo_states(comp_ctx.app_store(), comp_ctx.stable_path(), states, row_fp)
            .await?;
    }
    // Report the stored dependency sets upward even on a memo hit, so a
    // mounting parent's memo depends on this whole subtree (see
    // `merge_logic_deps` in `execute_once`). The bit too: a reused ancestor
    // of open descendants is still one, and its parent's row must list it.
    Ok(MemoLookup::Reuse(
        ComponentRunOutcome::reused(
            stored_logic_deps,
            stored_provider_deps,
            has_own_data_deps || has_open_descendants,
        ),
        ComponentBuildOutput {
            ret,
            built_target_states_providers: Default::default(),
        },
    ))
}

impl<Prof: EngineProfile> Component<Prof> {
    pub(crate) fn new(
        app_ctx: AppContext<Prof>,
        stable_path: StablePath,
        parent: Option<Component<Prof>>,
    ) -> Self {
        Self {
            inner: Arc::new(ComponentInner {
                app_ctx,
                stable_path,
                parent,
                build_semaphore: tokio::sync::Semaphore::const_new(1),
                last_stored_memos: Mutex::new(LastStoredMemos::default()),
                active_children: parking_lot::Mutex::new(HashMap::new()),
                live_state: parking_lot::Mutex::new(None),
                active_ops: std::sync::atomic::AtomicUsize::new(0),
                inactive: tokio::sync::Notify::new(),
                active_runs: std::sync::atomic::AtomicUsize::new(0),
            }),
        }
    }

    fn self_and_ancestors(&self) -> impl Iterator<Item = &ComponentInner<Prof>> {
        std::iter::successors(Some(&*self.inner), |inner| {
            inner.parent.as_ref().map(|parent| &*parent.inner)
        })
    }

    /// Begin a processing task on this component: count it as in flight, then
    /// register it with the parent view β€” as a pending child for readiness and
    /// as a member of every enclosing stats group. Activity is counted first,
    /// so a member is never registered inactive (a concurrent group scan would
    /// prune it before its task had started); readiness and membership are
    /// registered together, so a group can never see a member become ready
    /// without also tracking its activity.
    fn start_task(&self, context: &ComponentProcessorContext<Prof>) -> Result<StartedTask<Prof>> {
        let activity = ActivityGuard::new(self.clone());
        let run = RunGuard::new(self.clone());
        let child_readiness = match context.parent_context() {
            Some(parent_ctx) => {
                parent_ctx.push_active_member(self);
                let relative_path: StablePath = self.relative_path()?.into();
                Some(
                    parent_ctx
                        .components_readiness()
                        .clone()
                        .add_child(Some(relative_path)),
                )
            }
            None => None,
        };
        Ok(StartedTask {
            activity,
            run,
            child_readiness,
        })
    }

    /// Admit a run to the in-flight pool before its task is spawned, so a
    /// mount waits while the pool is empty (and the parent's token is lent):
    /// that is what bounds how far a parent can run ahead of its children.
    ///
    /// Skipped for a run that starts while another run of the same component
    /// is in flight β€” a second owner of a shared component, or an update
    /// overlapping the previous one. Such a run queues on the component's
    /// `build_semaphore`; it is admitted in `execute_once`, only once it
    /// knows it will execute rather than reuse the memo the first run stores.
    async fn admit_before_spawn(
        &self,
        context: &ComponentProcessorContext<Prof>,
        started: &StartedTask<Prof>,
    ) -> Result<()> {
        if started.run.concurrent {
            return Ok(());
        }
        context.admission().admit().await
    }

    pub fn mount_child(&self, fn_ctx: &FnCallContext, stable_path: StablePath) -> Result<Self> {
        fn_ctx.update(|inner| inner.has_child_components = true);
        Ok(self.get_child(stable_path))
    }

    /// Mount and run a child in the foreground (use_mount path).
    /// Inherits live from the parent context.
    ///
    /// `deadline` is the deadline for the CHILD, taken from the caller's
    /// current scope, and cannot be read from `parent_ctx.deadline`: that is
    /// the caller's own base, frozen at the caller's mount, while narrowing
    /// (`with coco.timeout(...)`) lives in the SDK's per-task carrier β€”
    /// concurrent tasks within one component can hold different narrowed
    /// scopes at the same moment, so the current value must travel with each
    /// call. It is threaded through the child's execution checkpoints and
    /// captured by the returned handle for the post-wait check; it is never
    /// stored on the ctx (the deadline only ever travels, never rests).
    pub async fn use_mount(
        self,
        parent_ctx: &ComponentProcessorContext<Prof>,
        processor: Prof::ComponentProc,
        deadline: DeadlineContext,
    ) -> Result<ComponentMountRunHandle<Prof>> {
        // An unselected child runs for its value, not to be reprocessed.
        let selector = parent_ctx.component_selector();
        let unselected = selector.is_some_and(|selector| {
            selector.classify(self.stable_path()) == ComponentSelection::Unselected
        });
        let child_ctx = self.new_processor_context_for_build(
            Some(parent_ctx),
            parent_ctx.processing_stats().clone(),
            parent_ctx.full_reprocess() && !unselected,
            parent_ctx.live(), // use_mount inherits live from parent
            parent_ctx.preview_collector().cloned(),
            parent_ctx.host_ctx().clone(),
            // No build-mode on_error: use_mount is foreground; failures
            // propagate as `Err` to the awaiting parent via `.result()`.
            // Orphan-delete failures during this child's commit fall
            // through to the framework's default `error!` log.
            None,
            // A use_mount child always runs, selected or not: its parent is
            // waiting for its value.
            ComponentSelector::scoped_to(selector, self.stable_path()),
        )?;
        self.run(processor, child_ctx, deadline, deadline).await
    }

    /// Mount and run a child in the background (mount path).
    /// Inherits live from the parent context.
    pub async fn mount(
        self,
        parent_ctx: &ComponentProcessorContext<Prof>,
        processor: Prof::ComponentProc,
        on_error: Option<OnError>,
    ) -> Result<ComponentExecutionHandle> {
        // An unselected child stops here: not run, and the parent's commit
        // keeps what the store holds for it (`reconcile_child_existence`).
        let component_selector =
            match ComponentSelector::for_mount(parent_ctx.component_selector(), self.stable_path())
            {
                MountDecision::Skip => {
                    parent_ctx.record_skipped_mount(self.stable_path())?;
                    return Ok(ComponentExecutionHandle::finished());
                }
                MountDecision::Run(component_selector) => component_selector,
            };
        // Store `on_error` on the child's build context too, so the
        // commit-phase GC sweep can cascade it to orphan deletes. The
        // same handler is also passed to `run_in_background` for the
        // child's own task failure β€” one handler, two surfaces.
        let child_ctx = self.new_processor_context_for_build(
            Some(parent_ctx),
            parent_ctx.processing_stats().clone(),
            parent_ctx.full_reprocess(),
            parent_ctx.live(), // mount inherits live from parent
            parent_ctx.preview_collector().cloned(),
            parent_ctx.host_ctx().clone(),
            on_error.clone(),
            component_selector,
        )?;
        self.run_in_background(processor, child_ctx, on_error).await
    }

    pub fn get_child(&self, stable_path: StablePath) -> Self {
        let mut children = self.inner.active_children.lock();
        if let Some(weak) = children.get(&stable_path)
            && let Some(inner) = weak.upgrade()
        {
            return Self { inner };
        }
        let child = Self::new(
            self.app_ctx().clone(),
            stable_path.clone(),
            Some(self.clone()),
        );
        children.insert(stable_path, Arc::downgrade(&child.inner));
        child
    }

    pub fn app_ctx(&self) -> &AppContext<Prof> {
        &self.inner.app_ctx
    }

    pub fn stable_path(&self) -> &StablePath {
        &self.inner.stable_path
    }

    /// A `Weak` to this component's inner, for membership tracking by a
    /// [`StatsGroup`]; the member counts as active while `active_ops > 0`.
    fn downgrade_inner(&self) -> Weak<ComponentInner<Prof>> {
        Arc::downgrade(&self.inner)
    }

    pub fn set_live_state(
        &self,
        state: Arc<crate::engine::live_component::LiveComponentState<Prof>>,
    ) {
        *self.inner.live_state.lock() = Some(state);
    }

    pub fn live_state(
        &self,
    ) -> Option<Arc<crate::engine::live_component::LiveComponentState<Prof>>> {
        self.inner.live_state.lock().clone()
    }

    /// True while a processing task is in flight on this component or any
    /// descendant (see [`ActivityGuard`]).
    pub fn is_active(&self) -> bool {
        self.inner
            .active_ops
            .load(std::sync::atomic::Ordering::SeqCst)
            > 0
    }

    /// Wait until no processing task is in flight in this component's
    /// subtree. Event-driven: returns as soon as the last [`ActivityGuard`]
    /// in the subtree drops.
    pub async fn wait_until_inactive(&self) {
        loop {
            // Create the future before checking: a `Notified` receives
            // `notify_waiters` from the moment it exists, so a guard dropped
            // between the check and the await still wakes us.
            let inactive = self.inner.inactive.notified();
            if !self.is_active() {
                return;
            }
            inactive.await;
        }
    }

    pub fn parent(&self) -> Option<&Component<Prof>> {
        self.inner.parent.as_ref()
    }

    pub(crate) fn relative_path(&self) -> Result<StablePathRef<'_>> {
        if let Some(parent) = self.parent() {
            self.stable_path()
                .as_ref()
                .strip_parent(parent.stable_path().as_ref())
        } else {
            Ok(self.stable_path().as_ref())
        }
    }

    /// `deadline` governs this component's own execution checkpoints;
    /// `caller_deadline` is stored in the returned handle for the post-wait
    /// check. They coincide for use_mount; the root passes NONE as
    /// `caller_deadline` since AppOpHandle owns the root's post-result check.
    pub(crate) async fn run(
        self,
        processor: Prof::ComponentProc,
        context: ComponentProcessorContext<Prof>,
        deadline: DeadlineContext,
        caller_deadline: DeadlineContext,
    ) -> Result<ComponentMountRunHandle<Prof>> {
        let started = self.start_task(&context)?;
        self.admit_before_spawn(&context, &started).await?;
        let StartedTask {
            activity,
            run,
            child_readiness: child_readiness_guard,
        } = started;

        let relative_path = self.relative_path()?;
        let span = info_span!("component.run", component_path = %relative_path);
        let cancel_token = self.app_ctx().cancellation_token();
        let join_handle = get_runtime().spawn(
            async move {
                // Race the work against app-level cancellation. On cancel, the
                // work future is dropped, which cascades drop into from_py_future
                // β†’ CancelOnDropPy and cancels the underlying Python task.
                let result = tokio::select! {
                    r = self.execute_once(&context, Some(&processor), deadline) => r,
                    _ = cancel_token.cancelled() => Err(internal_error!("operation cancelled")),
                };
                let (outcome, output) = match result {
                    Ok((outcome, output)) => (outcome, Ok(output)),
                    Err(err) => (ComponentRunOutcome::exception(), Err(err)),
                };
                // Give the in-flight token back before anyone can observe
                // the run as over.
                context.admission().finish();
                drop(processor);
                drop(context);
                drop(self);
                // Mark the task over before readiness resolves, so whoever
                // observes readiness also observes the component as inactive.
                drop(run);
                drop(activity);
                if let Some(guard) = child_readiness_guard {
                    guard.resolve(outcome)
                }
                output?
                    .ok_or_else(|| internal_error!("component deletion can only run in background"))
            }
            .instrument(span),
        );
        Ok(ComponentMountRunHandle {
            join_handle,
            caller_deadline,
        })
    }

    pub(crate) async fn run_in_background(
        self,
        processor: Prof::ComponentProc,
        context: ComponentProcessorContext<Prof>,
        on_error: Option<OnError>,
    ) -> Result<ComponentExecutionHandle> {
        let run = self
            .run_in_background_to_completeness(processor, context, on_error)
            .await?;
        Ok(ComponentExecutionHandle::new(async move {
            run.await.map(|_| ())
        }))
    }

    /// [`Self::run_in_background`], resolving to whether the run reached every
    /// component under it.
    pub(crate) async fn run_in_background_to_completeness(
        self,
        processor: Prof::ComponentProc,
        context: ComponentProcessorContext<Prof>,
        on_error: Option<OnError>,
    ) -> Result<impl Future<Output = SharedResult<RunCompleteness>> + Send + Sync + 'static> {
        // TODO: Skip building and reuse cached result if the component is already built and up to date.
        let started = self.start_task(&context)?;
        self.admit_before_spawn(&context, &started).await?;
        let StartedTask {
            activity,
            run,
            child_readiness: child_readiness_guard,
        } = started;

        let cancel_token = self.app_ctx().cancellation_token();
        let join_handle = get_runtime().spawn(async move {
            // Race the work against app-level cancellation. On cancel, the
            // work future is dropped, which cascades drop into from_py_future
            // β†’ CancelOnDropPy and cancels the underlying Python task.
            let result = tokio::select! {
                // Background components are deadline-isolated by design.
                r = self.execute_once(&context, Some(&processor), DeadlineContext::NONE) => r,
                _ = cancel_token.cancelled() => Err(internal_error!("operation cancelled")),
            };
            // Background-style error handling:
            // - Cancellation is always swallowed (no handler call, no
            //   propagation) β€” Ctrl+C / shutdown / re-mount shouldn't
            //   surface as a user-visible error.
            // - With a handler registered: invoke it. The handler's
            //   Result decides propagation β€” Ok = swallow (mount-style),
            //   Err = propagate via task_result. This lets the Python
            //   exception handler chain control propagation: handlers
            //   that return normally β†’ swallow; chain exhausted via
            //   raises β†’ propagate.
            // - No handler: log at ERROR, swallow. Matches the existing
            //   "no chain registered β†’ not propagated" contract.
            let (outcome, task_result) = match result {
                Ok((outcome, _)) => (outcome, Ok(())),
                Err(err) => {
                    let task_result = if cancel_token.is_cancelled() || err.is_cancelled() {
                        trace!("component build cancelled");
                        Ok(())
                    } else if let Some(handler) = &on_error {
                        match handler(err).await {
                            Ok(()) => Ok(()),
                            Err(propagated) => Err(SharedError::from(propagated)),
                        }
                    } else {
                        error!("component build failed at {}:\n{err:?}", self.stable_path());
                        context.processing_stats().record_unhandled_failure();
                        Ok(())
                    };
                    (ComponentRunOutcome::exception(), task_result)
                }
            };
            let completeness = if outcome.has_exception {
                RunCompleteness::Incomplete
            } else {
                RunCompleteness::Complete
            };
            context.admission().finish();
            drop(processor);
            drop(context);
            drop(self);
            // See `run` for why this precedes readiness resolution.
            drop(run);
            drop(activity);
            if let Some(guard) = child_readiness_guard {
                guard.resolve(outcome);
            }
            task_result.map(|()| completeness)
        });
        Ok(async move {
            join_handle
                .await
                .map_err(|e| SharedError::new(internal_error!("task panicked: {e}")))?
        })
    }

    pub fn delete(
        self,
        context: ComponentProcessorContext<Prof>,
    ) -> Result<ComponentExecutionHandle> {
        // A delete run is admitted to the in-flight pool inside its task
        // (`execute_once`), not here: `delete` is synchronous, and a parent
        // sweeping its tombstones spawns every child delete at once. The
        // children then run as the pool and the parent's token allow.
        let StartedTask {
            activity,
            run,
            child_readiness: child_readiness_guard,
        } = self.start_task(&context)?;
        // Pull on_error out of the delete context so the spawned task
        // can invoke it. The context still carries the same handler for
        // descendant GC sweeps to read and cascade.
        let on_error = context.delete_action_on_error();
        let join_handle: tokio::task::JoinHandle<SharedResult<()>> =
            get_runtime().spawn(async move {
                trace!("deleting component at {}", self.stable_path());
                // Delete/GC runs must never be deadline-bounded.
                let result = self
                    .execute_once(&context, None, DeadlineContext::NONE)
                    .await;
                // Same error model as `run_in_background`: cancellation
                // filtered; with-handler delegates propagation to the
                // handler's Result (Ok = swallow, Err = propagate);
                // without-handler logs + swallow.
                let (outcome, task_result) = match result {
                    Ok((outcome, _)) => (outcome, Ok(())),
                    Err(err) => {
                        let task_result = if err.is_cancelled() {
                            trace!("component delete cancelled");
                            Ok(())
                        } else if let Some(handler) = &on_error {
                            match handler(err).await {
                                Ok(()) => Ok(()),
                                Err(propagated) => Err(SharedError::from(propagated)),
                            }
                        } else {
                            error!(
                                "component delete failed at {}:\n{err:?}",
                                self.stable_path()
                            );
                            context.processing_stats().record_unhandled_failure();
                            Ok(())
                        };
                        (ComponentRunOutcome::exception(), task_result)
                    }
                };
                // Drop profile-specific objects BEFORE resolving child readiness.
                // See run_in_background for the rationale (PyGILState finalization fix).
                context.admission().finish();
                drop(context);
                drop(self);
                // See `run` for why this precedes readiness resolution.
                drop(run);
                drop(activity);
                if let Some(guard) = child_readiness_guard {
                    guard.resolve(outcome);
                }
                task_result
            });
        Ok(ComponentExecutionHandle::new(async move {
            join_handle
                .await
                .map_err(|e| SharedError::new(internal_error!("task panicked: {e}")))?
        }))
    }

    async fn execute_once(
        &self,
        processor_context: &ComponentProcessorContext<Prof>,
        processor: Option<&Prof::ComponentProc>,
        deadline: DeadlineContext,
    ) -> Result<(ComponentRunOutcome, Option<ComponentBuildOutput<Prof>>)> {
        let mut reported_processor_name: Option<Cow<'_, str>> = None;
        let mut memo_fp_to_store: Option<Fingerprint> = None;
        // Memo states collected from state validation (on cache hit with invalid states)
        // or to be collected after execution (on cache miss).
        let mut memo_states_for_store: Option<MemoStatesPayload<Prof>> = None;
        // What `last_stored_memos` held when the fast path below looked; the
        // re-check under the permit compares against it (see there).
        let mut memo_seen_by_fast_path: Option<StoredMemo> = None;
        let processing_stats = processor_context.processing_stats();

        if let Some(processor) = processor {
            let processor_name = processor.processor_info().name.as_str();
            memo_fp_to_store = processor.memo_key_fingerprint();
            deadline.check()?;

            // Fast-path: component memoization check does not require acquiring the build permit.
            // If it hits, we can immediately return without processing/submitting/waiting.
            // Under `full_reprocess` a stored memo may only be reused when this very
            // operation stored it, which only the permit-holding re-check below can
            // tell, so the fast-path is skipped.
            if !processor_context.full_reprocess() {
                // Read before the lookup: a store that races with the lookup
                // then shows as new under the permit and costs one more probe,
                // rather than going unseen and costing a second execution.
                memo_seen_by_fast_path = self
                    .inner
                    .last_stored_memos
                    .lock()
                    .unwrap()
                    .readable_by(processor_context.app_store());
                match lookup_component_memo(processor_context, processor, memo_fp_to_store).await? {
                    MemoLookup::Reuse(outcome, output) => {
                        processing_stats.update(processor_name, |stats| {
                            stats.num_execution_starts += 1;
                            stats.num_unchanged += 1;
                        });
                        return Ok((outcome, Some(output)));
                    }
                    MemoLookup::Miss { revalidated_states } => {
                        memo_states_for_store = revalidated_states;
                    }
                }
            }

            processing_stats.update(processor_name, |stats| {
                stats.num_execution_starts += 1;
            });
            reported_processor_name = Some(Cow::Borrowed(processor_name));
        }

        let result = {
            let reported_processor_name = &mut reported_processor_name;
            async move {
                // The permit is held until the memo is stored (or, in delete
                // mode, the tombstone cleaned up), not only across `process()`
                // and `submit()`: a run queued behind this one must find the
                // stored memo once it gets the permit, so it can reuse it
                // instead of executing again.
                let _permit = loop {
                    let permit = self.inner.build_semaphore.acquire().await?;

                    // A run with the same memo key completed under the permit
                    // while this one waited for it β€” e.g. two `App::update`
                    // calls on one app that both missed the fast-path above
                    // before either had stored a memo. Re-check the memo now;
                    // a failed run stores none (and records none), so a miss
                    // falls through to executing. Only a memo stored since the
                    // fast path looked qualifies: the one it saw, it already
                    // probed, and a long-lived component object (the app's
                    // root, a live component) holds that one on every rerun,
                    // so probing again would run every memo-state and
                    // data-dependency validator a second time to the same
                    // verdict. A store that repeats the seen memo exactly,
                    // operation and key alike, reads as nothing new: the body
                    // runs again, which is only redundant. Under
                    // `full_reprocess`, which skips the fast path, only a memo
                    // stored by this same operation qualifies: that is the
                    // operation's own execution of the component, not a cache
                    // from a previous run.
                    let last_stored_memo = self
                        .inner
                        .last_stored_memos
                        .lock()
                        .unwrap()
                        .readable_by(processor_context.app_store());
                    let qualifies_for_recheck = |stored: StoredMemo| {
                        if processor_context.full_reprocess() {
                            stored.operation_generation == processor_context.operation_generation()
                        } else {
                            Some(stored) != memo_seen_by_fast_path
                        }
                    };
                    if let Some(processor) = processor
                        && let Some(memo_fp) = memo_fp_to_store
                        && let Some(stored) = last_stored_memo
                        && stored.memo_fp == memo_fp
                        && qualifies_for_recheck(stored)
                    {
                        match lookup_component_memo(processor_context, processor, memo_fp_to_store)
                            .await?
                        {
                            MemoLookup::Reuse(outcome, output) => {
                                return Ok(GuardedRun::Reused(outcome, output));
                            }
                            MemoLookup::Miss { revalidated_states } => {
                                memo_states_for_store = revalidated_states;
                            }
                        }
                    }

                    // The run executes, so it holds an in-flight token from
                    // here until the memo is stored. A run admitted before its
                    // task was spawned already has one; a run that queued on
                    // the permit behind another run of this component, or a
                    // delete, takes one now (see `admit_before_spawn`) β€” with
                    // the permit released while it waits. A run never waits
                    // for a token while holding the permit: another run of
                    // this component may hold a token and wait for the
                    // permit, and with no other token to come, the two would
                    // wait for each other. Once admitted, the memo is checked
                    // again under a fresh permit.
                    if !processor_context.admission().needs_token() {
                        break permit;
                    }
                    drop(permit);
                    processor_context.admission().admit().await?;
                };

                // Build mode only: write the component's own existence bit
                // (and ancestor chain) into the parent in its own txn,
                // before the user processor runs. Maintains the invariant
                // that existence βŠ‡ tracked state and eliminates the
                // dual-writer conflict with the parent's commit-time
                // existence reconciliation. See `internal_states.md` Β§3.1.
                if processor_context.mode() == ComponentProcessingMode::Build {
                    eager_existence_upsert(processor_context).await?;
                }

                // Eagerly load all function-memo and user-state entries for
                // this component into the per-build cache (one read txn), so
                // every subsequent fn-call probe and `use_state` serves from
                // memory. Skipped under `full_reprocess` and in delete mode
                // (no `ComponentBuildingState`); see the cache flush logic
                // for how those cases are handled at commit time.
                processor_context.prefetch_states().await?;

                // The earlier deadline check guards memo lookup. A component can still
                // spend time waiting for the build semaphore, existence upsert, or state
                // prefetch before the user body starts, so check again at the actual
                // processor-entry boundary.
                deadline.check()?;

                let ret: Result<Option<Prof::FunctionData>> = match &processor {
                    Some(processor) => processor
                        .process(
                            processor_context.app_ctx().env().host_runtime_ctx(),
                            processor_context,
                        )?
                        .await
                        .map(Some),
                    None => Ok(None),
                };

                // Wait until children components ready before submitting this
                // component's target states and child-existence reconciliation.
                let components_readiness = processor_context.components_readiness();
                components_readiness.set_build_done();
                let mut children_outcome = components_readiness
                    .readiness()
                    .wait()
                    .await
                    .clone()
                    .into_result()?;

                // Merge children's logic deps into this component's context. The
                // full set (own fp βˆͺ all descendants) is taken once after
                // memo-state collection below and used for both this component's
                // own memo and the outcome reported to its parent.
                processor_context
                    .merge_logic_deps(std::mem::take(&mut children_outcome.logic_deps));
                processor_context.merge_target_provider_deps(std::mem::take(
                    &mut children_outcome.target_provider_deps,
                ));

                let ret = ret?;
                deadline.check()?;
                let submit_output = submit(processor_context, processor, |name| {
                    if reported_processor_name.is_none() {
                        processing_stats.update(name, |stats| {
                            stats.num_execution_starts += 1;
                        });
                        *reported_processor_name = Some(Cow::Owned(name.to_string()));
                    }
                })
                .await?;
                // A child delete that the commit's GC sweep owed failed. Its
                // tombstone stays under this component, and only a later run
                // of this component sweeps it again, so count it as a failed
                // descendant: a build stores no memo (and its ancestors none,
                // through the outcome), so the next update runs it again; a
                // delete keeps its own tombstone, so its parent's next sweep
                // deletes it again. The GC-spawned deletes register with this
                // component's readiness only after it resolved, so their
                // outcomes never reach `children_outcome`.
                if submit_output.child_deletes == ChildDeletes::Pending {
                    children_outcome.has_exception = true;
                }

                let build_output = match ret {
                    Some(ret) => {
                        // Two cases leave this subtree owing work to a later
                        // run, so a memo would wrongly tell the next update
                        // that it is up to date: a selector left out a child
                        // here or below (the outcome carries this up, so no
                        // ancestor stores one either), or a child delete is
                        // still owed. Drop the stored memo whether or not a
                        // descendant failed: a failure only skips storing a
                        // new one, and under `full_reprocess` the next update
                        // has the same memo key and would hit the old one.
                        children_outcome.left_out_children |=
                            processor_context.left_out_children();
                        if (children_outcome.left_out_children
                            || submit_output.child_deletes == ChildDeletes::Pending)
                            && memo_fp_to_store.is_some()
                        {
                            delete_component_memo(processor_context).await?;
                            self.inner
                                .last_stored_memos
                                .lock()
                                .unwrap()
                                .forget(processor_context.app_store().write_scope());
                        }
                        if !children_outcome.has_exception {
                            // Collect initial memo states on cache miss if processor has a state handler.
                            let memo_states: MemoStatesPayload<Prof> = if let Some(processor) =
                                processor
                                && (memo_states_for_store.is_some()
                                    || processor.collects_initial_states())
                            {
                                if let Some(states) = memo_states_for_store.take() {
                                    // From invalid cache hit path
                                    states
                                } else {
                                    // Cache miss β€” collect initial states
                                    let fut = processor.handle_memo_states(
                                        processor_context.app_ctx().env().host_runtime_ctx(),
                                        processor_context,
                                        None,
                                    )?;
                                    let (initial_states, _, _) = fut.await?;
                                    initial_states
                                }
                            } else {
                                MemoStatesPayload::default()
                            };

                            let comp_memo = memo_fp_to_store.map(|fp| (fp, &ret, &memo_states));
                            // Take the full dependency set once (O(1) move). It
                            // must run after the memo-state collection above, which
                            // reads the set via `collect_context_initial_states`.
                            // Serves both this component's own memo (sorted inside
                            // `post_submit_for_build`, only when memoizing) and the
                            // outcome reported to the parent across the mount
                            // boundary β€” so the parent's memo depends on this whole
                            // subtree's logic.
                            let logic_deps = processor_context.take_logic_deps();
                            let target_provider_deps =
                                processor_context.take_target_provider_deps();
                            let data_deps = processor_context.take_data_deps();
                            // The direct children that reported the bit, in
                            // path order for deterministic storage. Taken, so
                            // this component's list never leaks into the
                            // parent's accumulated outcome (the parent's
                            // guard would rewrite it anyway).
                            let mut open_children =
                                std::mem::take(&mut children_outcome.open_children);
                            open_children.sort();
                            open_children.dedup();
                            let has_open_descendants = !open_children.is_empty();
                            let data_dep_conflict = data_deps.conflict();
                            if let Some((kind_fp, key_fp)) = data_dep_conflict {
                                debug!(
                                    "{} observed data dependency (kind {kind_fp:?}, key {key_fp:?}) in two states; storing no memo",
                                    processor_context.stable_path()
                                );
                            }
                            // A run that observed one key in two states stores
                            // no memo and drops the previous one: submit has
                            // replaced the target states, so an older entry's
                            // return value must not be reused, and no stored
                            // state can validate its output. A run that left
                            // out a child stores none either; its old one is
                            // already dropped above.
                            let comp_memo = if children_outcome.left_out_children {
                                None
                            } else if data_dep_conflict.is_some() {
                                if memo_fp_to_store.is_some() {
                                    delete_component_memo(processor_context).await?;
                                    self.inner
                                        .last_stored_memos
                                        .lock()
                                        .unwrap()
                                        .forget(processor_context.app_store().write_scope());
                                }
                                None
                            } else {
                                comp_memo
                            };
                            let data_dep_records = data_deps.into_sorted_records();
                            post_submit_for_build(
                                processor_context,
                                comp_memo,
                                &logic_deps,
                                &target_provider_deps,
                                &data_dep_records,
                                &open_children,
                            )
                            .await?;
                            children_outcome.cannot_skip =
                                has_open_descendants || !data_dep_records.is_empty();
                            // Record the store for a run queued on the permit
                            // (see the re-check above). Still under the permit,
                            // so this is the component's latest memo.
                            if let Some(memo_fp) = memo_fp_to_store
                                && comp_memo.is_some()
                            {
                                self.inner.last_stored_memos.lock().unwrap().record(
                                    processor_context.app_store().write_scope(),
                                    StoredMemo {
                                        operation_generation: processor_context
                                            .operation_generation(),
                                        memo_fp,
                                    },
                                );
                            }
                            children_outcome.logic_deps = logic_deps;
                            children_outcome.target_provider_deps = target_provider_deps;
                        }
                        Some(ComponentBuildOutput {
                            ret,
                            built_target_states_providers: submit_output
                                .built_target_states_providers
                                .ok_or_else(|| {
                                    internal_error!("expect built target states providers")
                                })?,
                        })
                    }
                    None => {
                        // Delete path. When any descendant delete failed
                        // (including a child delete the GC sweep left
                        // owed, see above), skip `cleanup_tombstone`
                        // (symmetric with the build branch skipping
                        // `post_submit_for_build`) β€” that preserves the
                        // tombstone for the next reconcile to retry, and
                        // with it the way back to the child tombstones
                        // keyed under this component.
                        //
                        // We do NOT propagate via `Err` from here.
                        // Descendant-failure propagation to awaiting
                        // callers (notably `App.drop()`) happens via
                        // the cascading `on_error` plumbed through the
                        // GC sweep β€” see `execution.rs::launch_child_component_gc`.
                        // That's the single, unified error-handling
                        // channel; this branch just preserves metadata.
                        if !children_outcome.has_exception {
                            cleanup_tombstone(processor_context).await?;
                        }
                        None
                    }
                };
                Ok::<_, Error>(GuardedRun::Executed {
                    children_outcome,
                    build_output,
                    touched_previous_states: submit_output.touched_previous_states,
                })
            }
            .await
        };

        let final_processor_name = reported_processor_name
            .as_ref()
            .map(|s| s.as_ref())
            .unwrap_or(db_schema::UNKNOWN_PROCESSOR_NAME);
        match result {
            Ok(GuardedRun::Reused(outcome, output)) => {
                // The execution start was counted before the permit; the run
                // ends like a fast-path memo hit.
                processing_stats.update(final_processor_name, |stats| {
                    stats.num_unchanged += 1;
                });
                Ok((outcome, Some(output)))
            }
            Ok(GuardedRun::Executed {
                children_outcome,
                build_output,
                touched_previous_states,
            }) => {
                processing_stats.update(final_processor_name, |stats| {
                    if reported_processor_name.is_none() {
                        stats.num_execution_starts += 1;
                    }
                    match processor_context.mode() {
                        ComponentProcessingMode::Build => {
                            if touched_previous_states {
                                stats.num_reprocesses += 1;
                            } else {
                                stats.num_adds += 1;
                            }
                        }
                        ComponentProcessingMode::Delete => {
                            stats.num_deletes += 1;
                        }
                    }
                });
                Ok((children_outcome, build_output))
            }
            Err(err) => {
                if !err.is_cancelled() {
                    processing_stats.record_failure(crate::engine::stats::FailureRecord {
                        processor: final_processor_name.to_string(),
                        component: self.stable_path().clone(),
                        message: crate::engine::stats::failure_message(&err),
                    });
                }
                processing_stats.update(final_processor_name, |stats| {
                    if reported_processor_name.is_none() {
                        stats.num_execution_starts += 1;
                    }
                    stats.num_errors += 1;
                });
                Err(err)
            }
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub fn new_processor_context_for_build(
        &self,
        parent_ctx: Option<&ComponentProcessorContext<Prof>>,
        processing_stats: ProcessingStats,
        full_reprocess: bool,
        live: bool,
        preview_collector: Option<PreviewActionCollector<Prof>>,
        host_ctx: Arc<Prof::HostCtx>,
        on_error: Option<OnError>,
        component_selector: Option<ComponentSelector>,
    ) -> Result<ComponentProcessorContext<Prof>> {
        let providers = if let Some(parent_ctx) = parent_ctx {
            let sub_path = self
                .stable_path()
                .as_ref()
                .strip_parent(parent_ctx.stable_path().as_ref())?;
            parent_ctx.update_building_state(|building_state| {
                building_state
                    .child_path_set
                    .add_child(sub_path, StablePathSet::Component)?;
                Ok(building_state
                    .target_states
                    .provider_registry
                    .providers
                    .clone())
            })?
        } else {
            self.app_ctx()
                .env()
                .target_states_providers()
                .lock()
                .unwrap()
                .providers
                .clone()
        };
        Ok(ComponentProcessorContext::new(
            self.clone(),
            parent_ctx.cloned(),
            processing_stats,
            host_ctx,
            ComponentProcessingAction::new_build(
                providers,
                full_reprocess,
                live,
                on_error,
                preview_collector,
                component_selector,
            ),
        ))
    }

    pub fn new_processor_context_for_delete(
        &self,
        providers: rpds::HashTrieMapSync<TargetStatePath, TargetStateProvider<Prof>>,
        parent_ctx: Option<&ComponentProcessorContext<Prof>>,
        processing_stats: ProcessingStats,
        host_ctx: Arc<Prof::HostCtx>,
        on_error: Option<OnError>,
    ) -> ComponentProcessorContext<Prof> {
        // A delete that a preview launches previews too.
        let preview_collector = parent_ctx.and_then(|parent| parent.preview_collector().cloned());
        ComponentProcessorContext::new(
            self.clone(),
            parent_ctx.cloned(),
            processing_stats,
            host_ctx,
            ComponentProcessingAction::new_delete(providers, on_error, preview_collector),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::{
        ActivityGuard, Component, ComponentBgChildReadiness, ComponentProcessor,
        ComponentProcessorInfo, ComponentRunOutcome, StatsGroup,
    };
    use crate::engine::app::{App, AppUpdateOptions};
    use crate::engine::context::{
        ComponentProcessingAction, ComponentProcessorContext, FnCallContext, MemoStatesPayload,
        PreviewActionCollector,
    };
    use crate::engine::deadline::{
        DeadlineContext, testing_advance_deadline_clock, testing_deadline_clock_lock,
        testing_disable_deadline_clock, testing_reset_deadline_clock,
    };
    use crate::engine::environment::Environment;
    use crate::engine::execution::{
        declare_target_state, declare_target_state_with_child, register_root_target_state_provider,
        submit,
    };
    use crate::engine::live_component::{MountLiveResult, mount_live_prepare};
    use crate::engine::profile::{DataDepsValidation, EngineProfile, Persist};
    use crate::engine::stats::ProcessingStats;
    use crate::engine::target_state::{
        ChildHandling, TargetActionSink, TargetActionSinkKeeper, TargetActionWithChildSlot,
        TargetHandler, TargetReconcileOutput, TargetStateProvider, TargetStateProviderRegistry,
    };
    use crate::inspect::db_inspect::StablePathNodeType;
    use crate::state::component_selector::ComponentSelector;
    use crate::state::stable_path::{StableKey, StablePath};
    use crate::state_store::StorageSettings;
    use crate::state_store::test_support::hold_write_batch;
    use async_trait::async_trait;
    use cocoindex_utils::fingerprint::Fingerprint;
    use std::hash::{Hash, Hasher};
    use std::pin::Pin;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

    fn key_path(parent: &Component<TestProfile>, key: &str) -> StablePath {
        parent
            .stable_path()
            .concat_part(StableKey::Str(Arc::from(key)))
    }

    /// Activity is explicit: a task's `ActivityGuard` counts on the component
    /// and its ancestors, and dropping it wakes `wait_until_inactive`. Holding
    /// `Component`s has no effect on either.
    #[test]
    fn the_cannot_skip_bit_merges_upward_and_a_reused_memo_reports_its_own() {
        let mut parent = ComponentRunOutcome::default();
        parent.merge(ComponentRunOutcome::reused(
            vec![],
            Default::default(),
            false,
        ));
        assert!(!parent.cannot_skip);
        parent.merge(ComponentRunOutcome::reused(
            vec![],
            Default::default(),
            true,
        ));
        assert!(parent.cannot_skip);
        // A failed child reports no bit: its parent stores no memo at all.
        assert!(!ComponentRunOutcome::exception().cannot_skip);
        let mut grandparent = ComponentRunOutcome::default();
        grandparent.merge(parent);
        assert!(grandparent.cannot_skip);
    }

    /// A parent's accumulated outcome lists the direct children that reported
    /// the bit, by the relative path their readiness guard was registered
    /// with. A child's own list (its children) is replaced by the guard, so it
    /// never leaks a level up; a forwarded aggregate (a stats group's) passes
    /// its list through, since its members are the parent's direct children.
    #[tokio::test]
    async fn a_parents_outcome_lists_the_children_that_reported_the_bit() {
        fn relative(key: &str) -> StablePath {
            StablePath::root().concat_part(StableKey::Str(Arc::from(key)))
        }
        let readiness = ComponentBgChildReadiness::default();
        let open_child = readiness.clone().add_child(Some(relative("open")));
        let closed_child = readiness.clone().add_child(Some(relative("closed")));
        let group = readiness.clone().add_child(None);

        // An open child whose own children were open too: its outcome still
        // carries its list, which must not become the parent's.
        let mut open_outcome = ComponentRunOutcome::reused(vec![], Default::default(), true);
        open_outcome.open_children = vec![relative("grandchild")];
        open_child.resolve(open_outcome);
        closed_child.resolve(ComponentRunOutcome::reused(
            vec![],
            Default::default(),
            false,
        ));
        let mut aggregate = ComponentRunOutcome::default();
        aggregate.merge({
            let mut member = ComponentRunOutcome::reused(vec![], Default::default(), true);
            member.open_children = vec![relative("member")];
            member
        });
        group.resolve(aggregate);
        readiness.set_build_done();

        let outcome = readiness
            .readiness()
            .wait()
            .await
            .clone()
            .expect("readiness resolved with an error");
        assert!(outcome.cannot_skip);
        let mut listed = outcome.open_children.clone();
        listed.sort();
        assert_eq!(listed, vec![relative("member"), relative("open")]);
    }

    #[tokio::test]
    async fn activity_propagates_up_the_parent_chain_and_wakes_waiters() {
        let (app, _dir) = test_app("activity_guard").await;
        let root = Component::new(app.app_ctx().clone(), StablePath::root(), None);
        let child = root.get_child(key_path(&root, "child"));
        let grandchild = child.get_child(key_path(&child, "grandchild"));
        let chain = [&root, &child, &grandchild];
        assert!(!chain.iter().any(|c| c.is_active()));

        let activity = ActivityGuard::new(grandchild.clone());
        assert!(chain.iter().all(|c| c.is_active()));

        let waiter = tokio::spawn({
            let root = root.clone();
            async move { root.wait_until_inactive().await }
        });
        tokio::time::sleep(Duration::from_millis(20)).await;
        assert!(
            !waiter.is_finished(),
            "must keep waiting while the grandchild's task is in flight"
        );
        drop(activity);
        tokio::time::timeout(Duration::from_secs(5), waiter)
            .await
            .expect("wait_until_inactive must wake when the last task ends")
            .unwrap();
        assert!(!chain.iter().any(|c| c.is_active()));
    }

    #[tokio::test]
    async fn stats_group_prunes_finished_members_even_while_still_referenced() {
        let (app, _dir) = test_app("stats_group_members").await;
        let root = Component::new(app.app_ctx().clone(), StablePath::root(), None);
        let member = root.get_child(key_path(&root, "member"));
        let group = StatsGroup::<TestProfile>::new(&ProcessingStats::new());

        let activity = ActivityGuard::new(member.clone());
        group.push_member(&member);
        assert!(group.last_active_member().is_some());

        drop(activity);
        // `member` is still held (as a retained host-language context would
        // hold it), yet it is finished: pruned, nothing left to wait for.
        assert!(group.last_active_member().is_none());
        assert!(group.active_members.lock().is_empty());
        group.wait_until_members_inactive().await;
    }

    #[derive(Clone, Debug, Default, Eq, PartialEq, Hash)]
    struct TestProfile;

    #[derive(Clone, Debug, Eq, PartialEq)]
    struct TestData(Vec<u8>);

    impl Persist for TestData {
        fn to_bytes(&self) -> crate::prelude::Result<bytes::Bytes> {
            Ok(bytes::Bytes::from(self.0.clone()))
        }

        fn from_bytes(data: &[u8]) -> crate::prelude::Result<Self> {
            Ok(Self(data.to_vec()))
        }
    }

    /// Applies nothing but counts its `apply` calls. With `children`, it
    /// provides a `CountingHandler` counting into the given counter for every
    /// child-bearing action, in the given way: from `child_handlers` or by
    /// fulfilling the slots in `apply`. With `failing`, `apply` fails (after
    /// counting) while the flag is set.
    #[derive(Default)]
    struct NoopSink {
        apply_calls: Arc<AtomicUsize>,
        children: Option<(ChildHandling, Arc<AtomicUsize>)>,
        failing: Option<Arc<AtomicBool>>,
        /// `apply` appends its name to a shared list of applied sinks.
        recording: Option<Recording>,
    }

    /// Where a [`NoopSink`] records its `apply` calls, and under which name.
    struct Recording {
        applied: Arc<Mutex<Vec<String>>>,
        name: String,
    }

    impl NoopSink {
        fn container(child_handling: ChildHandling) -> (Self, Arc<AtomicUsize>, Arc<AtomicUsize>) {
            let apply_calls = Arc::new(AtomicUsize::new(0));
            let child_reconcile_calls = Arc::new(AtomicUsize::new(0));
            let sink = Self {
                apply_calls: apply_calls.clone(),
                children: Some((child_handling, child_reconcile_calls.clone())),
                failing: None,
                recording: None,
            };
            (sink, apply_calls, child_reconcile_calls)
        }

        fn child_handler(&self) -> CountingHandler {
            let (_, child_reconcile_calls) = self.children.as_ref().expect("a container sink");
            let child_sink = NoopSink {
                recording: self.recording.as_ref().map(|recording| Recording {
                    applied: recording.applied.clone(),
                    name: format!("{}/rows", recording.name),
                }),
                ..Default::default()
            };
            CountingHandler {
                reconcile_calls: child_reconcile_calls.clone(),
                sink: TargetActionSinkKeeper::new(child_sink),
                reject: false,
                change_only: false,
                plans_deletes: false,
            }
        }
    }

    #[async_trait]
    impl TargetActionSink<TestProfile> for NoopSink {
        fn child_handling(&self) -> ChildHandling {
            self.children
                .as_ref()
                .map_or(ChildHandling::Leaf, |(child_handling, _)| *child_handling)
        }

        async fn child_handlers(
            &self,
            _host_runtime_ctx: &(),
            _host_ctx: Arc<()>,
            actions: &[&()],
        ) -> crate::prelude::Result<Vec<CountingHandler>> {
            Ok(actions.iter().map(|_| self.child_handler()).collect())
        }

        async fn apply(
            &self,
            _host_runtime_ctx: &(),
            _host_ctx: Arc<()>,
            actions: &[TargetActionWithChildSlot<TestProfile>],
        ) -> crate::prelude::Result<()> {
            self.apply_calls.fetch_add(1, Ordering::SeqCst);
            if let Some(recording) = &self.recording {
                recording
                    .applied
                    .lock()
                    .unwrap()
                    .push(recording.name.clone());
            }
            if let Some(failing) = &self.failing
                && failing.load(Ordering::SeqCst)
            {
                cocoindex_utils::client_bail!("injected sink failure");
            }
            for slot in actions.iter().filter_map(|(_, slot)| slot.as_ref()) {
                slot.fulfill(self.child_handler())?;
            }
            Ok(())
        }
    }

    /// Plans an action for every desired target state (for a deletion, only
    /// with `plans_deletes`) and counts its `reconcile` calls. With `reject`,
    /// it rejects every desired target state instead, as a connector
    /// rejecting a declared value does.
    struct CountingHandler {
        reconcile_calls: Arc<AtomicUsize>,
        sink: TargetActionSinkKeeper<TestProfile>,
        reject: bool,
        /// Plan an action only for a change, as a real connector does:
        /// nothing for a desired target state the stored records already
        /// hold, and a deletion for one no longer declared.
        change_only: bool,
        plans_deletes: bool,
    }

    impl TargetHandler<TestProfile> for CountingHandler {
        fn reconcile(
            &self,
            key: StableKey,
            desired_target_state: Option<&()>,
            prev_possible_records: &[TestData],
            prev_may_be_missing: bool,
        ) -> crate::prelude::Result<Option<TargetReconcileOutput<TestProfile>>> {
            self.reconcile_calls.fetch_add(1, Ordering::SeqCst);
            if self.reject && desired_target_state.is_some() {
                cocoindex_utils::client_bail!("target state {key:?} rejected");
            }
            if self.change_only {
                if desired_target_state.is_some()
                    && !prev_may_be_missing
                    && !prev_possible_records.is_empty()
                {
                    return Ok(None);
                }
                return Ok(Some(TargetReconcileOutput {
                    action: (),
                    sink: self.sink.clone(),
                    tracking_record: desired_target_state.map(|_| TestData(Vec::new())),
                    child_invalidation: None,
                }));
            }
            if desired_target_state.is_none() && !self.plans_deletes {
                return Ok(None);
            }
            Ok(Some(TargetReconcileOutput {
                action: (),
                sink: self.sink.clone(),
                tracking_record: desired_target_state.map(|_| TestData(Vec::new())),
                child_invalidation: None,
            }))
        }
    }

    impl Hash for TestProcessor {
        fn hash<H: Hasher>(&self, state: &mut H) {
            self.memo_fp.hash(state);
        }
    }

    impl PartialEq for TestProcessor {
        fn eq(&self, other: &Self) -> bool {
            self.memo_fp == other.memo_fp
        }
    }

    impl Eq for TestProcessor {}

    impl EngineProfile for TestProfile {
        type HostRuntimeCtx = ();
        type HostCtx = ();
        type ComponentProc = TestProcessor;
        type FunctionData = TestData;
        type TargetHdl = CountingHandler;
        type TargetStateTrackingRecord = TestData;
        type TargetAction = ();
        type TargetActionSink = NoopSink;
        type TargetStateValue = ();

        /// The test profile registers no kinds, so no record validates.
        fn validate_data_deps(
            _host_runtime_ctx: &(),
            _verdicts: Arc<crate::engine::context::DataDepVerdicts>,
            _path: &StablePath,
            records: Vec<crate::engine::context::DataDepRecord>,
        ) -> crate::prelude::Result<
            impl Future<Output = crate::prelude::Result<DataDepsValidation>> + Send + 'static,
        > {
            Ok(async move {
                Ok(DataDepsValidation {
                    records,
                    can_reuse: false,
                    states_changed: false,
                })
            })
        }
    }

    /// Optional processor body, given the component's processor context.
    type ProcessHook = Arc<
        dyn Fn(
                ComponentProcessorContext<TestProfile>,
            )
                -> Pin<Box<dyn Future<Output = crate::prelude::Result<TestData>> + Send>>
            + Send
            + Sync,
    >;

    struct TestProcessor {
        info: ComponentProcessorInfo,
        memo_fp: Fingerprint,
        body_started: Arc<AtomicBool>,
        advance_clock_in_state_handler: bool,
        /// What the memo state handler reports as `can_reuse` on a memo hit.
        memo_states_reusable: bool,
        /// What the memo state handler reports as `states_changed`.
        memo_states_changed: bool,
        /// Whether the processor has a memo key (`memo_fp`); a processor
        /// without one re-runs every time and stores no component memo.
        memoized: bool,
        /// Counts the memo state handler's validations of stored states (a
        /// memo probe); the initial collection after a body run is not one.
        validations: Arc<AtomicUsize>,
        on_process: Option<ProcessHook>,
    }

    impl TestProcessor {
        fn new(
            name: &str,
            memo_fp: Fingerprint,
            body_started: Arc<AtomicBool>,
            advance_clock_in_state_handler: bool,
        ) -> Self {
            Self {
                info: ComponentProcessorInfo::new(name.to_string()),
                memo_fp,
                body_started,
                advance_clock_in_state_handler,
                memo_states_reusable: false,
                memo_states_changed: false,
                memoized: true,
                validations: Arc::new(AtomicUsize::new(0)),
                on_process: None,
            }
        }

        /// No memo key: the component re-runs on every update.
        fn without_memo(mut self) -> Self {
            self.memoized = false;
            self
        }

        fn with_reusable_memo_states(mut self) -> Self {
            self.memo_states_reusable = true;
            self
        }

        /// Reusable memo states that moved (e.g. an mtime): a memo hit
        /// rewrites them in place.
        fn with_reusable_changed_memo_states(mut self) -> Self {
            self.memo_states_reusable = true;
            self.memo_states_changed = true;
            self
        }

        fn with_on_process(mut self, hook: ProcessHook) -> Self {
            self.on_process = Some(hook);
            self
        }

        /// Share `counter` across the processors of several runs.
        fn with_validation_counter(mut self, counter: Arc<AtomicUsize>) -> Self {
            self.validations = counter;
            self
        }
    }

    impl ComponentProcessor<TestProfile> for TestProcessor {
        fn process(
            &self,
            _host_runtime_ctx: &(),
            comp_ctx: &ComponentProcessorContext<TestProfile>,
        ) -> crate::prelude::Result<
            impl Future<Output = crate::prelude::Result<TestData>> + Send + 'static,
        > {
            let body_started = self.body_started.clone();
            let hook = self
                .on_process
                .as_ref()
                .map(|hook| (hook.clone(), comp_ctx.clone()));
            Ok(async move {
                body_started.store(true, Ordering::SeqCst);
                match hook {
                    Some((hook, comp_ctx)) => hook(comp_ctx).await,
                    None => Ok(TestData(b"ret".to_vec())),
                }
            })
        }

        fn memo_key_fingerprint(&self) -> Option<Fingerprint> {
            self.memoized.then_some(self.memo_fp)
        }

        fn processor_info(&self) -> &ComponentProcessorInfo {
            &self.info
        }

        fn has_memo_state_handler(&self) -> bool {
            true
        }

        fn handle_memo_states(
            &self,
            _host_runtime_ctx: &(),
            _comp_ctx: &ComponentProcessorContext<TestProfile>,
            stored_states: Option<MemoStatesPayload<TestProfile>>,
        ) -> crate::prelude::Result<
            impl Future<Output = crate::prelude::Result<(MemoStatesPayload<TestProfile>, bool, bool)>>
            + Send
            + 'static,
        > {
            let advance_clock = self.advance_clock_in_state_handler;
            let reusable = self.memo_states_reusable;
            let changed = self.memo_states_changed;
            if stored_states.is_some() {
                self.validations.fetch_add(1, Ordering::SeqCst);
            }
            Ok(async move {
                if advance_clock {
                    testing_advance_deadline_clock(Duration::from_secs(2));
                }
                // Moved states differ from every earlier report.
                static MOVES: AtomicUsize = AtomicUsize::new(0);
                let state = if changed {
                    format!("state/{}", MOVES.fetch_add(1, Ordering::SeqCst)).into_bytes()
                } else {
                    b"state".to_vec()
                };
                Ok((
                    MemoStatesPayload {
                        positional: vec![TestData(state)],
                        by_context_fp: Vec::new(),
                        data_deps: Vec::new(),
                    },
                    reusable,
                    changed,
                ))
            })
        }
    }

    struct TestClockGuard {
        _guard: std::sync::MutexGuard<'static, ()>,
    }

    impl TestClockGuard {
        fn new() -> Self {
            let guard = testing_deadline_clock_lock();
            testing_reset_deadline_clock();
            Self { _guard: guard }
        }
    }

    impl Drop for TestClockGuard {
        fn drop(&mut self) {
            testing_disable_deadline_clock();
        }
    }

    async fn test_app(name: &str) -> (App<TestProfile>, tempfile::TempDir) {
        test_app_with_options(name, 1 << 24, None).await
    }

    async fn test_app_with_options(
        name: &str,
        lmdb_map_size: usize,
        max_inflight_components: Option<usize>,
    ) -> (App<TestProfile>, tempfile::TempDir) {
        let dir = tempfile::tempdir().unwrap();
        let settings = StorageSettings {
            db_path: dir.path().join("lmdb"),
            lmdb_max_dbs: 64,
            lmdb_map_size,
        };
        let providers = Arc::new(Mutex::new(TargetStateProviderRegistry::new(
            Default::default(),
        )));
        let env = Environment::<TestProfile>::new(settings, providers, ())
            .await
            .unwrap();
        let app = App::new(name, env, max_inflight_components).await.unwrap();
        (app, dir)
    }

    /// Every run in a chain of `use_mount`s borrows its parent's in-flight
    /// token, so a hierarchy of any depth completes on a single pool token.
    #[tokio::test]
    async fn a_chain_of_mounts_runs_on_one_pool_token() {
        fn chain(depth: usize, tokens_at_leaf: Arc<Mutex<Option<Option<usize>>>>) -> TestProcessor {
            let memo_fp = Fingerprint::from(&format!("chain_one_token/{depth}")).unwrap();
            TestProcessor::new("chain", memo_fp, Arc::new(AtomicBool::new(false)), false)
                .with_on_process(Arc::new(move |ctx| {
                    let tokens_at_leaf = tokens_at_leaf.clone();
                    Box::pin(async move {
                        if depth == 0 {
                            *tokens_at_leaf.lock().unwrap() =
                                Some(ctx.app_ctx().admission_pool().available_tokens());
                            return Ok(TestData(b"leaf".to_vec()));
                        }
                        let child = ctx.component().mount_child(
                            &FnCallContext::new(true),
                            key_path(ctx.component(), "child"),
                        )?;
                        let handle = child
                            .use_mount(
                                &ctx,
                                chain(depth - 1, tokens_at_leaf),
                                DeadlineContext::NONE,
                            )
                            .await?;
                        handle.result(Some(&ctx)).await
                    })
                }))
        }

        let (app, _dir) = test_app_with_options("chain_one_token", 1 << 24, Some(1)).await;
        let tokens_at_leaf = Arc::new(Mutex::new(None));
        let (handle, _) = app
            .update(
                chain(8, tokens_at_leaf.clone()),
                AppUpdateOptions::default(),
                Arc::new(()),
                None,
            )
            .unwrap();
        tokio::time::timeout(Duration::from_secs(10), handle.result())
            .await
            .expect("a chain of mounts must not deadlock on one token")
            .unwrap();
        assert_eq!(
            *tokens_at_leaf.lock().unwrap(),
            Some(Some(0)),
            "the leaf ran on a chain of loans from the one pool token"
        );
        assert_eq!(app.app_ctx().admission_pool().available_tokens(), Some(1));
    }

    /// With one token in the pool, the root's run holds it and lends it to the
    /// child's first run, whose body blocks. A second run of the same child
    /// started meanwhile β€” what a second owner mounting a shared component
    /// starts β€” needs no token: it queues on the child's permit, and once the
    /// first run is released it reuses the memo that run stored.
    #[tokio::test]
    async fn a_second_run_of_a_running_component_waits_without_a_token() {
        let (app, _dir) = test_app_with_options("second_run_no_token", 1 << 24, Some(1)).await;
        let child_path = StablePath::root().concat_part(StableKey::Str(Arc::from("child")));
        let child_memo_fp = Fingerprint::from(&"second_run_no_token/child").unwrap();
        let body_runs = Arc::new(AtomicUsize::new(0));
        let release = Arc::new(tokio::sync::Notify::new());
        let body: ProcessHook = {
            let body_runs = body_runs.clone();
            let release = release.clone();
            Arc::new(move |_ctx| {
                let body_runs = body_runs.clone();
                let release = release.clone();
                Box::pin(async move {
                    body_runs.fetch_add(1, Ordering::SeqCst);
                    release.notified().await;
                    Ok(TestData(b"ret".to_vec()))
                })
            })
        };
        let child_processor = move || {
            TestProcessor::new(
                "child",
                child_memo_fp,
                Arc::new(AtomicBool::new(false)),
                false,
            )
            .with_reusable_memo_states()
            .with_on_process(body.clone())
        };
        let child_processors = Mutex::new(Some((child_processor(), child_processor())));
        let results: Arc<Mutex<Option<[crate::prelude::Result<TestData>; 2]>>> = Default::default();
        let root_processor = {
            let results = results.clone();
            let body_runs = body_runs.clone();
            let release = release.clone();
            TestProcessor::new(
                "root",
                Fingerprint::from(&"second_run_no_token/root").unwrap(),
                Arc::new(AtomicBool::new(false)),
                false,
            )
            .with_on_process(Arc::new(move |ctx| {
                let (first, second) = child_processors.lock().unwrap().take().unwrap();
                let child_path = child_path.clone();
                let results = results.clone();
                let body_runs = body_runs.clone();
                let release = release.clone();
                Box::pin(async move {
                    let pool = ctx.app_ctx().admission_pool().clone();
                    assert_eq!(pool.available_tokens(), Some(0), "the root holds the token");
                    let child = ctx
                        .component()
                        .mount_child(&FnCallContext::new(true), child_path)?;
                    let first = child
                        .clone()
                        .use_mount(&ctx, first, DeadlineContext::NONE)
                        .await?;
                    // The first run borrows the root's token and blocks in
                    // its body.
                    while body_runs.load(Ordering::SeqCst) == 0 {
                        tokio::time::sleep(Duration::from_millis(5)).await;
                    }
                    assert_eq!(pool.available_tokens(), Some(0));
                    let second_ctx = ComponentProcessorContext::new(
                        child.clone(),
                        Some(ctx.clone()),
                        ctx.processing_stats().clone(),
                        ctx.host_ctx().clone(),
                        ComponentProcessingAction::new_build(
                            ctx.target_states_providers()?,
                            ctx.full_reprocess(),
                            ctx.live(),
                            None,
                            None,
                            None,
                        ),
                    );
                    // No token is free and the root's is lent, yet the
                    // second run starts: it needs none to queue.
                    let second = tokio::time::timeout(
                        Duration::from_secs(2),
                        child.run(
                            second,
                            second_ctx,
                            DeadlineContext::NONE,
                            DeadlineContext::NONE,
                        ),
                    )
                    .await
                    .expect("a second run of a running component must not wait for a token")?;
                    release.notify_one();
                    let first = first.result(Some(&ctx)).await;
                    let second = second.result(Some(&ctx)).await;
                    *results.lock().unwrap() = Some([first, second]);
                    Ok(TestData(b"root".to_vec()))
                })
            }))
        };
        let (handle, _) = app
            .update(
                root_processor,
                AppUpdateOptions::default(),
                Arc::new(()),
                None,
            )
            .unwrap();
        tokio::time::timeout(Duration::from_secs(10), handle.result())
            .await
            .expect("the update must complete")
            .unwrap();
        let [first, second] = results.lock().unwrap().take().expect("root processor ran");
        assert_eq!(first.unwrap(), TestData(b"ret".to_vec()));
        assert_eq!(
            second.unwrap(),
            TestData(b"ret".to_vec()),
            "the second run reused the first run's memo"
        );
        assert_eq!(body_runs.load(Ordering::SeqCst), 1);
        assert_eq!(app.app_ctx().admission_pool().available_tokens(), Some(1));
    }

    /// Two runs of one child start while the root's token is lent to a
    /// sibling and the pool is empty: the first waits for a token before its
    /// task spawns, the second (concurrent, so admitted lazily) takes the
    /// build permit first. The second must not hold the permit while it waits
    /// for a token: when the sibling ends, the token goes to the first run,
    /// which would then wait for the permit forever.
    #[tokio::test]
    async fn runs_of_one_component_never_wait_for_a_token_under_the_permit() {
        let (app, _dir) = test_app_with_options("token_under_permit", 1 << 24, Some(1)).await;
        let sibling_path = StablePath::root().concat_part(StableKey::Str(Arc::from("sibling")));
        let child_path = StablePath::root().concat_part(StableKey::Str(Arc::from("child")));
        let child_memo_fp = Fingerprint::from(&"token_under_permit/child").unwrap();
        let release_sibling = Arc::new(tokio::sync::Notify::new());
        let sibling_started = Arc::new(AtomicBool::new(false));
        let body_runs = Arc::new(AtomicUsize::new(0));
        let sibling_processor = {
            let release_sibling = release_sibling.clone();
            TestProcessor::new(
                "sibling",
                Fingerprint::from(&"token_under_permit/sibling").unwrap(),
                sibling_started.clone(),
                false,
            )
            .with_on_process(Arc::new(move |_ctx| {
                let release_sibling = release_sibling.clone();
                Box::pin(async move {
                    release_sibling.notified().await;
                    Ok(TestData(b"sibling".to_vec()))
                })
            }))
        };
        let child_processor = {
            let body = counting_body(body_runs.clone(), Duration::from_millis(10));
            move || {
                TestProcessor::new(
                    "child",
                    child_memo_fp,
                    Arc::new(AtomicBool::new(false)),
                    false,
                )
                .with_reusable_memo_states()
                .with_on_process(body.clone())
            }
        };
        let processors = Mutex::new(Some((
            sibling_processor,
            child_processor(),
            child_processor(),
        )));
        let root_processor = TestProcessor::new(
            "root",
            Fingerprint::from(&"token_under_permit/root").unwrap(),
            Arc::new(AtomicBool::new(false)),
            false,
        )
        .with_on_process(Arc::new(move |ctx| {
            let (sibling, first, second) = processors.lock().unwrap().take().unwrap();
            let sibling_path = sibling_path.clone();
            let child_path = child_path.clone();
            let release_sibling = release_sibling.clone();
            let sibling_started = sibling_started.clone();
            Box::pin(async move {
                let sibling = ctx
                    .component()
                    .mount_child(&FnCallContext::new(true), sibling_path)?
                    .use_mount(&ctx, sibling, DeadlineContext::NONE)
                    .await?;
                while !sibling_started.load(Ordering::SeqCst) {
                    tokio::time::sleep(Duration::from_millis(5)).await;
                }
                // The root's token is lent to the sibling; the pool is empty.
                let child = ctx
                    .component()
                    .mount_child(&FnCallContext::new(true), child_path)?;
                let first = tokio::spawn({
                    let child = child.clone();
                    let ctx = ctx.clone();
                    async move {
                        let handle = child.use_mount(&ctx, first, DeadlineContext::NONE).await?;
                        handle.result(Some(&ctx)).await
                    }
                });
                tokio::time::sleep(Duration::from_millis(20)).await;
                let second_ctx = ComponentProcessorContext::new(
                    child.clone(),
                    Some(ctx.clone()),
                    ctx.processing_stats().clone(),
                    ctx.host_ctx().clone(),
                    ComponentProcessingAction::new_build(
                        ctx.target_states_providers()?,
                        ctx.full_reprocess(),
                        ctx.live(),
                        None,
                        None,
                        None,
                    ),
                );
                let second = child
                    .run(
                        second,
                        second_ctx,
                        DeadlineContext::NONE,
                        DeadlineContext::NONE,
                    )
                    .await?;
                tokio::time::sleep(Duration::from_millis(20)).await;
                release_sibling.notify_one();
                sibling.result(Some(&ctx)).await?;
                let first = first.await.unwrap()?;
                let second = second.result(Some(&ctx)).await?;
                assert_eq!(first, TestData(b"ret".to_vec()));
                assert_eq!(second, TestData(b"ret".to_vec()));
                Ok(TestData(b"root".to_vec()))
            })
        }));
        let (handle, _) = app
            .update(
                root_processor,
                AppUpdateOptions::default(),
                Arc::new(()),
                None,
            )
            .unwrap();
        tokio::time::timeout(Duration::from_secs(10), handle.result())
            .await
            .expect("the two runs must not wait for each other")
            .unwrap();
        assert_eq!(body_runs.load(Ordering::SeqCst), 1);
        assert_eq!(app.app_ctx().admission_pool().available_tokens(), Some(1));
    }

    #[tokio::test]
    async fn deadline_rechecked_after_memo_state_handler_before_processor_body() {
        let _clock = TestClockGuard::new();
        let memo_fp = Fingerprint::from(&"processor-entry-deadline").unwrap();
        let (app, _dir) = test_app("deadline_pre_body").await;

        let first_body_started = Arc::new(AtomicBool::new(false));
        let first_processor = TestProcessor::new(
            "deadline_pre_body",
            memo_fp,
            first_body_started.clone(),
            false,
        );
        let (handle, _) = app
            .update(
                first_processor,
                AppUpdateOptions::default(),
                Arc::new(()),
                None,
            )
            .unwrap();
        handle.result().await.unwrap();
        assert!(first_body_started.load(Ordering::SeqCst));

        let second_body_started = Arc::new(AtomicBool::new(false));
        let second_processor = TestProcessor::new(
            "deadline_pre_body",
            memo_fp,
            second_body_started.clone(),
            true,
        );
        let deadline = DeadlineContext::NONE.with_timeout(Duration::from_secs(1));
        let (handle, _) = app
            .update(
                second_processor,
                AppUpdateOptions {
                    deadline,
                    ..AppUpdateOptions::default()
                },
                Arc::new(()),
                None,
            )
            .unwrap();
        let err = handle.result().await.unwrap_err();
        assert!(err.is_deadline_exceeded());
        assert!(
            !second_body_started.load(Ordering::SeqCst),
            "processor body must not start after memo-state validation expires the deadline"
        );
    }

    /// A processor context retained after its component's processing task
    /// ends β€” in the host language, an exception traceback keeping a frame
    /// that holds it, or a stored handle β€” keeps the component's identity
    /// alive but not active, so live-mode termination is unaffected.
    #[tokio::test]
    async fn retained_context_does_not_keep_component_active() {
        let (app, _dir) = test_app("retained_ctx").await;
        let child_path = StablePath::root().concat_part(StableKey::Str(Arc::from("child")));

        let retained_child_ctx: Arc<Mutex<Option<ComponentProcessorContext<TestProfile>>>> =
            Default::default();
        let root_component: Arc<Mutex<Option<Component<TestProfile>>>> = Default::default();

        let child_processor = {
            let retained = retained_child_ctx.clone();
            TestProcessor::new(
                "child",
                Fingerprint::from(&"retained_ctx/child").unwrap(),
                Arc::new(AtomicBool::new(false)),
                false,
            )
            .with_on_process(Arc::new(move |ctx| {
                *retained.lock().unwrap() = Some(ctx);
                Box::pin(async { Ok(TestData(b"child".to_vec())) })
            }))
        };
        let root_processor = {
            let root_component = root_component.clone();
            let child_path = child_path.clone();
            let child_processor = Mutex::new(Some(child_processor));
            TestProcessor::new(
                "root",
                Fingerprint::from(&"retained_ctx/root").unwrap(),
                Arc::new(AtomicBool::new(false)),
                false,
            )
            .with_on_process(Arc::new(move |ctx| {
                let root_component = root_component.clone();
                let child_path = child_path.clone();
                let child_processor = child_processor.lock().unwrap().take().unwrap();
                Box::pin(async move {
                    let component = ctx.component().clone();
                    *root_component.lock().unwrap() = Some(component.clone());
                    // Same steps as the host bindings' `use_mount`.
                    let handle = component
                        .mount_child(&FnCallContext::new(true), child_path)?
                        .use_mount(&ctx, child_processor, DeadlineContext::NONE)
                        .await?;
                    handle.result(Some(&ctx)).await?;
                    Ok(TestData(b"root".to_vec()))
                })
            }))
        };

        let (handle, _) = app
            .update(
                root_processor,
                AppUpdateOptions::default(),
                Arc::new(()),
                None,
            )
            .unwrap();
        handle.result().await.unwrap();

        let root = root_component
            .lock()
            .unwrap()
            .take()
            .expect("root processor ran");
        let child_ctx = retained_child_ctx
            .lock()
            .unwrap()
            .take()
            .expect("child processor ran");
        let child = child_ctx.component();
        assert_eq!(child.stable_path(), &child_path);
        // The retained context keeps the child's identity registered (a
        // re-mount would share it)...
        assert!(root.inner.active_children.lock().contains_key(&child_path));
        // ...but nothing is active, immediately and without polling.
        assert!(!child.is_active());
        assert!(!root.is_active());
    }

    /// A processor body that counts its runs and then holds the build for
    /// `hold`, long enough for a concurrent same-key run to miss the memo
    /// fast-path and queue on the permit.
    fn counting_body(body_runs: Arc<AtomicUsize>, hold: Duration) -> ProcessHook {
        Arc::new(move |_ctx| {
            let body_runs = body_runs.clone();
            Box::pin(async move {
                body_runs.fetch_add(1, Ordering::SeqCst);
                tokio::time::sleep(hold).await;
                Ok(TestData(b"ret".to_vec()))
            })
        })
    }

    /// Start two updates of `app` back to back β€” the second before the first
    /// has stored its memo β€” with memoizable root processors sharing `body`.
    /// Returns both updates' results in start order.
    async fn update_twice_concurrently(
        app: &App<TestProfile>,
        name: &str,
        body: ProcessHook,
    ) -> [crate::prelude::Result<TestData>; 2] {
        let memo_fp = Fingerprint::from(&name).unwrap();
        let processor = || {
            TestProcessor::new(name, memo_fp, Arc::new(AtomicBool::new(false)), false)
                .with_reusable_memo_states()
                .with_on_process(body.clone())
        };
        let (first, _) = app
            .update(processor(), AppUpdateOptions::default(), Arc::new(()), None)
            .unwrap();
        let (second, _) = app
            .update(processor(), AppUpdateOptions::default(), Arc::new(()), None)
            .unwrap();
        [first.result().await, second.result().await]
    }

    /// Two runs of one component with the same memo key that both start before
    /// either has stored a memo execute the body once: the run that loses the
    /// race for the build permit finds the winner's memo under the permit and
    /// reuses it β€” same result, no second execution.
    #[tokio::test]
    async fn concurrent_same_key_runs_execute_body_once() {
        let (app, _dir) = test_app("memo_piggyback").await;
        let body_runs = Arc::new(AtomicUsize::new(0));
        let body = counting_body(body_runs.clone(), Duration::from_millis(100));
        let [first, second] = update_twice_concurrently(&app, "memo_piggyback", body).await;
        assert_eq!(first.unwrap(), TestData(b"ret".to_vec()));
        assert_eq!(second.unwrap(), TestData(b"ret".to_vec()));
        assert_eq!(body_runs.load(Ordering::SeqCst), 1);
    }

    /// The re-check under the permit is for a memo stored since the fast path
    /// looked, and a root that has run before holds a memo the fast path saw.
    /// Two concurrent reruns of such a root whose stored memo is stale (its
    /// key changed) still execute the body once: the loser finds the winner's
    /// memo new under the permit and reuses it.
    #[tokio::test]
    async fn concurrent_same_key_reruns_of_a_root_with_a_stale_memo_execute_body_once() {
        let (app, _dir) = test_app("memo_piggyback_rerun").await;
        let (first, _) = app
            .update(
                TestProcessor::new(
                    "root",
                    Fingerprint::from(&"memo_piggyback_rerun/v1").unwrap(),
                    Arc::new(AtomicBool::new(false)),
                    false,
                )
                .with_reusable_memo_states(),
                AppUpdateOptions::default(),
                Arc::new(()),
                None,
            )
            .unwrap();
        first.result().await.unwrap();

        let body_runs = Arc::new(AtomicUsize::new(0));
        let body = counting_body(body_runs.clone(), Duration::from_millis(100));
        let [first, second] =
            update_twice_concurrently(&app, "memo_piggyback_rerun/v2", body).await;
        assert_eq!(first.unwrap(), TestData(b"ret".to_vec()));
        assert_eq!(second.unwrap(), TestData(b"ret".to_vec()));
        assert_eq!(body_runs.load(Ordering::SeqCst), 1);
    }

    /// The re-check under the permit consults the memo store, not only the
    /// key marker: a run that fails stores no memo, so the run queued behind
    /// it executes the body itself instead of reusing a stale result.
    #[tokio::test]
    async fn queued_run_executes_after_a_failed_same_key_run() {
        let (app, _dir) = test_app("memo_after_failure").await;
        let body_runs = Arc::new(AtomicUsize::new(0));
        let body: ProcessHook = {
            let body_runs = body_runs.clone();
            Arc::new(move |_ctx| {
                let body_runs = body_runs.clone();
                Box::pin(async move {
                    let run = body_runs.fetch_add(1, Ordering::SeqCst);
                    tokio::time::sleep(Duration::from_millis(100)).await;
                    if run == 0 {
                        return Err(cocoindex_utils::internal_error!("first run fails"));
                    }
                    Ok(TestData(b"ret".to_vec()))
                })
            })
        };
        let results = update_twice_concurrently(&app, "memo_after_failure", body).await;
        assert_eq!(body_runs.load(Ordering::SeqCst), 2);
        let (failed, succeeded): (Vec<_>, Vec<_>) =
            results.into_iter().partition(|result| result.is_err());
        assert_eq!(failed.len(), 1, "exactly the first run to execute fails");
        assert_eq!(
            succeeded.into_iter().next().unwrap().unwrap(),
            TestData(b"ret".to_vec())
        );
    }

    /// A rerun of the app's root whose memo misses probes the memo once. The
    /// root component object lives as long as the app, so its last stored
    /// memo carries the rerun's key; the re-check under the permit is for a
    /// memo stored since the fast path looked, not for the one the fast path
    /// already probed β€” a second probe would run every validator again to
    /// the same verdict.
    #[tokio::test]
    async fn a_root_rerun_whose_memo_misses_probes_once() {
        let (app, _dir) = test_app("root_rerun_probes_once").await;
        let validations = Arc::new(AtomicUsize::new(0));
        let body_runs = Arc::new(AtomicUsize::new(0));
        let memo_fp = Fingerprint::from(&"root_rerun_probes_once").unwrap();
        let run = |states_reusable: bool| {
            let processor =
                TestProcessor::new("root", memo_fp, Arc::new(AtomicBool::new(false)), false)
                    .with_validation_counter(validations.clone())
                    .with_on_process(counting_body(body_runs.clone(), Duration::ZERO));
            let processor = if states_reusable {
                processor.with_reusable_memo_states()
            } else {
                processor
            };
            let (handle, _) = app
                .update(processor, AppUpdateOptions::default(), Arc::new(()), None)
                .unwrap();
            async move { handle.result().await.unwrap() }
        };
        let counts = || {
            (
                validations.load(Ordering::SeqCst),
                body_runs.load(Ordering::SeqCst),
            )
        };

        // Fresh: no memo to probe; the body runs and its states are collected.
        run(true).await;
        assert_eq!(counts(), (0, 1));
        // Unchanged: one probe, which hits.
        run(true).await;
        assert_eq!(counts(), (1, 1));
        // The stored states no longer validate: one probe, which misses, then
        // the body.
        run(false).await;
        assert_eq!(counts(), (2, 2));
        // Unchanged again: one probe, which hits.
        run(true).await;
        assert_eq!(counts(), (3, 2));
    }

    /// Run one update whose root runs the same memoizable child component
    /// twice concurrently β€” the second run started before the first has
    /// stored its memo β€” with child processors sharing `body`. A path can be
    /// mounted only once per parent, so the second run gets a build context
    /// built directly. Returns both results in start order.
    async fn run_same_child_twice_in_one_update(
        app: &App<TestProfile>,
        name: &str,
        full_reprocess: bool,
        body: ProcessHook,
    ) -> [crate::prelude::Result<TestData>; 2] {
        let child_path = StablePath::root().concat_part(StableKey::Str(Arc::from("child")));
        let child_memo_fp = Fingerprint::from(&format!("{name}/child")).unwrap();
        let child_processor = || {
            TestProcessor::new(
                "child",
                child_memo_fp,
                Arc::new(AtomicBool::new(false)),
                false,
            )
            .with_reusable_memo_states()
            .with_on_process(body.clone())
        };
        let child_processors = Mutex::new(Some((child_processor(), child_processor())));
        let results: Arc<Mutex<Option<[crate::prelude::Result<TestData>; 2]>>> = Default::default();
        let root_processor = {
            let results = results.clone();
            TestProcessor::new(
                "root",
                Fingerprint::from(&format!("{name}/root")).unwrap(),
                Arc::new(AtomicBool::new(false)),
                false,
            )
            .with_on_process(Arc::new(move |ctx| {
                let (first, second) = child_processors.lock().unwrap().take().unwrap();
                let child_path = child_path.clone();
                let results = results.clone();
                Box::pin(async move {
                    let child = ctx
                        .component()
                        .mount_child(&FnCallContext::new(true), child_path)?;
                    let first = child
                        .clone()
                        .use_mount(&ctx, first, DeadlineContext::NONE)
                        .await?;
                    let second_ctx = ComponentProcessorContext::new(
                        child.clone(),
                        Some(ctx.clone()),
                        ctx.processing_stats().clone(),
                        ctx.host_ctx().clone(),
                        ComponentProcessingAction::new_build(
                            ctx.target_states_providers()?,
                            ctx.full_reprocess(),
                            ctx.live(),
                            None,
                            None,
                            None,
                        ),
                    );
                    let second = child
                        .run(
                            second,
                            second_ctx,
                            DeadlineContext::NONE,
                            DeadlineContext::NONE,
                        )
                        .await?;
                    let first = first.result(Some(&ctx)).await;
                    let second = second.result(Some(&ctx)).await;
                    *results.lock().unwrap() = Some([first, second]);
                    Ok(TestData(b"root".to_vec()))
                })
            }))
        };
        let (handle, _) = app
            .update(
                root_processor,
                AppUpdateOptions {
                    full_reprocess,
                    ..AppUpdateOptions::default()
                },
                Arc::new(()),
                None,
            )
            .unwrap();
        handle.result().await.unwrap();
        results.lock().unwrap().take().expect("root processor ran")
    }

    /// `full_reprocess` ignores memos from previous runs, not this operation's
    /// own executions: two concurrent runs of one component in one
    /// `full_reprocess` update execute the body once, the second reusing the
    /// memo the first stored β€” the re-check under the permit sees that this
    /// operation stored it.
    #[tokio::test]
    async fn concurrent_same_key_runs_execute_body_once_under_full_reprocess() {
        let (app, _dir) = test_app("memo_piggyback_full_reprocess").await;
        let body_runs = Arc::new(AtomicUsize::new(0));
        let body = counting_body(body_runs.clone(), Duration::from_millis(100));
        let [first, second] =
            run_same_child_twice_in_one_update(&app, "memo_piggyback_full_reprocess", true, body)
                .await;
        assert_eq!(first.unwrap(), TestData(b"ret".to_vec()));
        assert_eq!(second.unwrap(), TestData(b"ret".to_vec()));
        assert_eq!(body_runs.load(Ordering::SeqCst), 1);
    }

    /// A memo stored by a previous operation is a cache: a later
    /// `full_reprocess` update executes the body again even though the
    /// component's last stored memo carries its key.
    #[tokio::test]
    async fn full_reprocess_reexecutes_a_memo_stored_by_a_previous_operation() {
        let (app, _dir) = test_app("memo_full_reprocess_generation").await;
        let body_runs = Arc::new(AtomicUsize::new(0));
        let body = counting_body(body_runs.clone(), Duration::ZERO);
        let memo_fp = Fingerprint::from(&"memo_full_reprocess_generation").unwrap();
        let processor = || {
            TestProcessor::new(
                "memo_full_reprocess_generation",
                memo_fp,
                Arc::new(AtomicBool::new(false)),
                false,
            )
            .with_reusable_memo_states()
            .with_on_process(body.clone())
        };
        for full_reprocess in [false, true] {
            let (handle, _) = app
                .update(
                    processor(),
                    AppUpdateOptions {
                        full_reprocess,
                        ..AppUpdateOptions::default()
                    },
                    Arc::new(()),
                    None,
                )
                .unwrap();
            assert_eq!(handle.result().await.unwrap(), TestData(b"ret".to_vec()));
        }
        assert_eq!(
            body_runs.load(Ordering::SeqCst),
            2,
            "the full_reprocess update must not reuse the previous update's memo"
        );
    }

    /// A root in the `mount_target` shape: a child component declares one
    /// container target state, routed to `container_sink`, and the root then
    /// declares `num_rows` target states under the container's child provider.
    fn container_root(
        container_sink: TargetActionSinkKeeper<TestProfile>,
        num_rows: i64,
    ) -> TestProcessor {
        container_root_with(container_sink, num_rows, None)
    }

    /// [`container_root`] that also registers a root provider `also` and
    /// declares one target state through it, after the rows.
    fn container_root_with(
        container_sink: TargetActionSinkKeeper<TestProfile>,
        num_rows: i64,
        also: Option<(&'static str, TargetActionSinkKeeper<TestProfile>)>,
    ) -> TestProcessor {
        let new_processor = |name: &str| {
            TestProcessor::new(
                name,
                Fingerprint::from(&format!("container_root/{name}")).unwrap(),
                Arc::new(AtomicBool::new(false)),
                false,
            )
        };
        let table_processor = Mutex::new(Some({
            let child_provider: Arc<Mutex<Option<TargetStateProvider<TestProfile>>>> =
                Default::default();
            let processor = new_processor("table").with_on_process(Arc::new({
                let child_provider = child_provider.clone();
                move |ctx| {
                    let child_provider = child_provider.clone();
                    let container_sink = container_sink.clone();
                    Box::pin(async move {
                        let tables = register_root_target_state_provider(
                            &ctx,
                            "tables".to_string(),
                            CountingHandler {
                                reconcile_calls: Arc::new(AtomicUsize::new(0)),
                                sink: container_sink,
                                reject: false,
                                change_only: false,
                                plans_deletes: false,
                            },
                        )?;
                        *child_provider.lock().unwrap() = Some(declare_target_state_with_child(
                            &ctx,
                            &FnCallContext::default(),
                            tables,
                            StableKey::Str(Arc::from("table")),
                            (),
                        )?);
                        Ok(TestData(b"table".to_vec()))
                    })
                }
            }));
            (processor, child_provider)
        }));
        new_processor("root").with_on_process(Arc::new(move |ctx| {
            let (table_processor, child_provider) = table_processor.lock().unwrap().take().unwrap();
            let also = also.clone();
            Box::pin(async move {
                let table = ctx.component().mount_child(
                    &FnCallContext::new(true),
                    key_path(ctx.component(), "table"),
                )?;
                table
                    .use_mount(&ctx, table_processor, DeadlineContext::NONE)
                    .await?
                    .result(Some(&ctx))
                    .await?;
                let rows = child_provider.lock().unwrap().take().unwrap();
                for i in 0..num_rows {
                    declare_target_state(
                        &ctx,
                        &FnCallContext::default(),
                        rows.clone(),
                        StableKey::Int(i),
                        (),
                    )?;
                }
                if let Some((name, sink)) = also.clone() {
                    let provider = register_root_target_state_provider(
                        &ctx,
                        name.to_string(),
                        CountingHandler {
                            reconcile_calls: Default::default(),
                            sink,
                            reject: false,
                            change_only: false,
                            plans_deletes: false,
                        },
                    )?;
                    declare_target_state(
                        &ctx,
                        &FnCallContext::default(),
                        provider,
                        StableKey::Int(0),
                        (),
                    )?;
                }
                Ok(TestData(b"ret".to_vec()))
            })
        }))
    }

    /// Every key and value of the app's state store.
    async fn app_store_contents(app: &App<TestProfile>) -> Vec<(Vec<u8>, Vec<u8>)> {
        let app_store = app.app_ctx().persisting_app_store();
        let read = app_store.read_txn().await.unwrap();
        app_store
            .db()
            .raw()
            .iter(read.committed())
            .unwrap()
            .map(|entry| {
                let (key, value) = entry.unwrap();
                (key.to_vec(), value.to_vec())
            })
            .collect()
    }

    /// Preview readies a container's child provider from its sink's child
    /// handler factory, without applying the container's action, so the
    /// target states declared under it are previewed too β€” and writes nothing,
    /// not even the id of the container's new child provider generation.
    #[tokio::test]
    async fn preview_collects_actions_under_a_child_provider() {
        const NUM_ROWS: i64 = 3;
        let (app, _dir) = test_app("preview_child_provider").await;
        let (container_sink, container_apply_calls, child_reconcile_calls) =
            NoopSink::container(ChildHandling::Factory);
        let container_sink = TargetActionSinkKeeper::new(container_sink);

        let contents_before = app_store_contents(&app).await;
        let collector = PreviewActionCollector::<TestProfile>::default();
        let (handle, _) = app
            .update(
                container_root(container_sink.clone(), NUM_ROWS),
                AppUpdateOptions::default(),
                Arc::new(()),
                Some(collector.clone()),
            )
            .unwrap();
        handle.result().await.unwrap();
        assert_eq!(
            collector.lock().unwrap().len(),
            1 + NUM_ROWS as usize,
            "the container's action and one per row"
        );
        assert_eq!(
            child_reconcile_calls.load(Ordering::SeqCst),
            NUM_ROWS as usize
        );
        assert_eq!(
            container_apply_calls.load(Ordering::SeqCst),
            0,
            "preview must not apply the container's action"
        );
        assert!(
            app_store_contents(&app).await == contents_before,
            "preview must not write to the state store"
        );

        // A real update afterwards applies it, with the rows reconciled
        // against the handlers from the same factory.
        let (handle, _) = app
            .update(
                container_root(container_sink.clone(), NUM_ROWS),
                AppUpdateOptions::default(),
                Arc::new(()),
                None,
            )
            .unwrap();
        handle.result().await.unwrap();
        assert_eq!(container_apply_calls.load(Ordering::SeqCst), 1);
        assert_eq!(
            child_reconcile_calls.load(Ordering::SeqCst),
            2 * NUM_ROWS as usize
        );

        // The container action is still listed: arbitrary tracking-record
        // equality does not prove that an action has no external effect.
        let collector = PreviewActionCollector::<TestProfile>::default();
        let (handle, _) = app
            .update(
                container_root(container_sink, NUM_ROWS),
                AppUpdateOptions::default(),
                Arc::new(()),
                Some(collector.clone()),
            )
            .unwrap();
        handle.result().await.unwrap();
        assert_eq!(collector.lock().unwrap().len(), 1 + NUM_ROWS as usize);
        assert_eq!(container_apply_calls.load(Ordering::SeqCst), 1);
    }

    /// A root that registers a root provider routed to `sink` and, with
    /// `with_kid`, mounts a child `kid` declaring `NUM_KID_ROWS` target states
    /// through it, which the handler deletes once the child is gone.
    fn root_with_kid(sink: TargetActionSinkKeeper<TestProfile>, with_kid: bool) -> TestProcessor {
        const NUM_KID_ROWS: i64 = 2;
        let new_processor = |name: &str| {
            TestProcessor::new(
                name,
                Fingerprint::from(&format!("root_with_kid/{name}")).unwrap(),
                Arc::new(AtomicBool::new(false)),
                false,
            )
            .without_memo()
        };
        let kid = new_processor("kid");
        let kid = Mutex::new(Some(kid));
        new_processor("root").with_on_process(Arc::new(move |ctx| {
            let sink = sink.clone();
            let kid = kid.lock().unwrap().take();
            Box::pin(async move {
                let rows = register_root_target_state_provider(
                    &ctx,
                    "rows".to_string(),
                    CountingHandler {
                        reconcile_calls: Default::default(),
                        sink,
                        reject: false,
                        change_only: true,
                        plans_deletes: true,
                    },
                )?;
                if with_kid {
                    let kid = kid.unwrap().with_on_process(Arc::new(move |ctx| {
                        let rows = rows.clone();
                        Box::pin(async move {
                            for i in 0..NUM_KID_ROWS {
                                declare_target_state(
                                    &ctx,
                                    &FnCallContext::default(),
                                    rows.clone(),
                                    StableKey::Int(i),
                                    (),
                                )?;
                            }
                            Ok(TestData(b"kid".to_vec()))
                        })
                    }));
                    ctx.component()
                        .mount_child(&FnCallContext::new(true), key_path(ctx.component(), "kid"))?
                        .use_mount(&ctx, kid, DeadlineContext::NONE)
                        .await?
                        .result(Some(&ctx))
                        .await?;
                }
                Ok(TestData(b"ret".to_vec()))
            })
        }))
    }

    /// A preview plans the deletion of the target states of a child component
    /// that the run no longer mounts, applies none of it and writes nothing;
    /// the update after it applies the deletion.
    #[tokio::test]
    async fn preview_plans_the_deletes_of_a_child_no_longer_mounted() {
        let (app, _dir) = test_app("preview_gone_child").await;
        let apply_calls = Arc::new(AtomicUsize::new(0));
        let sink = TargetActionSinkKeeper::new(NoopSink {
            apply_calls: apply_calls.clone(),
            ..Default::default()
        });
        let update = |with_kid: bool, collector: Option<PreviewActionCollector<TestProfile>>| {
            let (handle, _) = app
                .update(
                    root_with_kid(sink.clone(), with_kid),
                    AppUpdateOptions::default(),
                    Arc::new(()),
                    collector,
                )
                .unwrap();
            handle.result()
        };
        update(true, None).await.unwrap();
        assert_eq!(apply_calls.load(Ordering::SeqCst), 1);

        let contents_before = app_store_contents(&app).await;
        for _ in 0..2 {
            let collector = PreviewActionCollector::<TestProfile>::default();
            update(false, Some(collector.clone())).await.unwrap();
            assert_eq!(
                collector.lock().unwrap().len(),
                2,
                "one deletion per target state of the gone child"
            );
            assert_eq!(
                apply_calls.load(Ordering::SeqCst),
                1,
                "preview applies nothing"
            );
            assert!(
                app_store_contents(&app).await == contents_before,
                "preview must not write to the state store"
            );
        }

        update(false, None).await.unwrap();
        assert_eq!(apply_calls.load(Ordering::SeqCst), 2);
        let collector = PreviewActionCollector::<TestProfile>::default();
        update(false, Some(collector.clone())).await.unwrap();
        assert!(
            collector.lock().unwrap().is_empty(),
            "nothing left to delete"
        );
    }

    /// A preview that runs a live component writes nothing: not the marker
    /// the component commits (which it still reads back), not the existence
    /// rows and tombstone of the children it updates and deletes, and not
    /// what its builds would commit.
    #[tokio::test]
    async fn preview_through_live_component_writes_nothing() {
        let (app, _dir) = test_app("preview_live_component").await;
        let contents_before = app_store_contents(&app).await;
        let collector = PreviewActionCollector::<TestProfile>::default();
        let ctx = Component::new(app.app_ctx().clone(), StablePath::root(), None)
            .new_processor_context_for_build(
                None,
                ProcessingStats::new(),
                false,
                false,
                Some(collector),
                Arc::new(()),
                None,
                None,
            )
            .unwrap();
        let live_path = StablePath::root().concat_part(StableKey::Str(Arc::from("live")));
        let MountLiveResult { controller, .. } =
            mount_live_prepare(&ctx, &FnCallContext::default(), live_path.clone(), false)
                .unwrap()
                .unwrap()
                .complete()
                .await
                .unwrap();
        let processor = |name: &str, body_started: &Arc<AtomicBool>| {
            TestProcessor::new(
                name,
                Fingerprint::from(&name).unwrap(),
                body_started.clone(),
                false,
            )
            .with_reusable_memo_states()
        };

        let first_body_started = Arc::new(AtomicBool::new(false));
        controller
            .update_full(processor("live", &first_body_started), None)
            .await
            .unwrap();
        assert!(first_body_started.load(Ordering::SeqCst));
        // The runs of one preview share its handle: the memo the first run
        // stored is the second run's hit.
        let second_body_started = Arc::new(AtomicBool::new(false));
        controller
            .update_full(processor("live", &second_body_started), None)
            .await
            .unwrap();
        assert!(
            !second_body_started.load(Ordering::SeqCst),
            "the second run must reuse the memo the first run stored in the preview"
        );
        let marker = StableKey::Str(Arc::from("bootstrapped"));
        controller
            .write_committed_state(&marker, b"yes".to_vec())
            .await
            .unwrap();
        assert_eq!(
            controller.read_committed_state(&marker).await.unwrap(),
            Some(b"yes".to_vec()),
            "the preview reads its own committed state back"
        );
        let child_path = live_path.concat_part(StableKey::Str(Arc::from("child")));
        controller
            .update(
                child_path.clone(),
                processor("child", &Arc::new(AtomicBool::new(false))),
                None,
            )
            .await
            .unwrap()
            .ready()
            .await
            .unwrap();
        controller
            .delete(child_path, None)
            .await
            .unwrap()
            .ready()
            .await
            .unwrap();

        assert!(
            app_store_contents(&app).await == contents_before,
            "preview must not write to the state store"
        );
    }

    /// Within one preview, a component declaring a target state that another
    /// component of the run declared earlier plans to take it over, as an
    /// update would: the earlier component committed into the run's handle,
    /// so its tracking record is not left staged for the later one to wait on
    /// until it gives up.
    #[tokio::test]
    async fn preview_takes_over_a_target_state_declared_earlier_in_the_run() {
        let (app, _dir) = test_app("preview_takeover").await;
        let contents_before = app_store_contents(&app).await;
        let collector = PreviewActionCollector::<TestProfile>::default();
        let root = Component::new(app.app_ctx().clone(), StablePath::root(), None)
            .new_processor_context_for_build(
                None,
                ProcessingStats::new(),
                false,
                false,
                Some(collector.clone()),
                Arc::new(()),
                None,
                None,
            )
            .unwrap();
        let provider = register_root_target_state_provider(
            &root,
            "preview_takeover".to_string(),
            CountingHandler {
                reconcile_calls: Arc::new(AtomicUsize::new(0)),
                sink: TargetActionSinkKeeper::new(NoopSink::default()),
                reject: false,
                change_only: false,
                plans_deletes: false,
            },
        )
        .unwrap();
        let processor = TestProcessor::new(
            "preview_takeover",
            Fingerprint::from(&"preview_takeover").unwrap(),
            Arc::new(AtomicBool::new(false)),
            false,
        );

        for name in ["a", "b"] {
            let child = root
                .component()
                .get_child(StablePath::root().concat_part(StableKey::Str(Arc::from(name))));
            let ctx = child
                .new_processor_context_for_build(
                    Some(&root),
                    ProcessingStats::new(),
                    false,
                    false,
                    Some(collector.clone()),
                    Arc::new(()),
                    None,
                    None,
                )
                .unwrap();
            declare_target_state(
                &ctx,
                &FnCallContext::default(),
                provider.clone(),
                StableKey::Int(0),
                (),
            )
            .unwrap();
            tokio::time::timeout(
                Duration::from_secs(10),
                submit(&ctx, Some(&processor), |_| {}),
            )
            .await
            .expect("the preview's submit must not hang")
            .unwrap();
        }

        assert_eq!(
            collector.lock().unwrap().len(),
            2,
            "both components plan an action for the target state"
        );
        assert!(
            app_store_contents(&app).await == contents_before,
            "preview must not write to the state store"
        );
    }

    /// A preview's stored memo is found only by that preview's runs, and does
    /// not displace the persisted memo an update queued on the permit
    /// re-checks.
    #[tokio::test]
    async fn a_previews_stored_memo_does_not_hide_the_persisted_one() {
        let (app, _dir) = test_app("stored_memo_scopes").await;
        let store = app.app_ctx().persisting_app_store();
        let preview = store.discarding_writes();
        let fp = |name: &str| Fingerprint::from(&name).unwrap();
        let memo = |name: &str| super::StoredMemo {
            operation_generation: 0,
            memo_fp: fp(name),
        };
        let mut memos = super::LastStoredMemos::default();
        memos.record(store.write_scope(), memo("update"));
        memos.record(preview.write_scope(), memo("preview"));
        let found = |reader: &crate::state_store::AppStore| {
            memos.readable_by(reader).map(|memo| memo.memo_fp)
        };
        assert_eq!(found(store), Some(fp("update")));
        assert_eq!(found(&preview), Some(fp("preview")));
        assert_eq!(found(&store.discarding_writes()), Some(fp("update")));
    }

    /// A preview that finds the stored memo invalid (here: a changed memo key)
    /// re-runs the component but leaves the memo in place, as everything else
    /// it reads: it writes nothing.
    #[tokio::test]
    async fn preview_leaves_an_invalidated_memo_in_place() {
        let (app, _dir) = test_app("preview_memo_invalidation").await;
        let processor = |key: &str| {
            TestProcessor::new(
                "root",
                Fingerprint::from(&key).unwrap(),
                Arc::new(AtomicBool::new(false)),
                false,
            )
        };
        let (handle, _) = app
            .update(
                processor("v1"),
                AppUpdateOptions::default(),
                Arc::new(()),
                None,
            )
            .unwrap();
        handle.result().await.unwrap();

        let contents_before = app_store_contents(&app).await;
        let (handle, _) = app
            .update(
                processor("v2"),
                AppUpdateOptions::default(),
                Arc::new(()),
                Some(PreviewActionCollector::<TestProfile>::default()),
            )
            .unwrap();
        handle.result().await.unwrap();
        assert!(
            app_store_contents(&app).await == contents_before,
            "preview must not delete or store memos"
        );
    }

    /// After a real update, a preview that meets a memo hit whose reusable
    /// states moved leaves the stored memo states in place: it writes nothing.
    #[tokio::test]
    async fn preview_after_an_update_writes_nothing() {
        let (app, _dir) = test_app("preview_after_update").await;
        // The root re-runs every time (a new memo key per run) and mounts a
        // memoized child whose memo hit reports moved states.
        let root = |run: &str| {
            TestProcessor::new(
                "root",
                Fingerprint::from(&format!("preview_after_update/{run}")).unwrap(),
                Arc::new(AtomicBool::new(false)),
                false,
            )
            .with_on_process(Arc::new(move |ctx| {
                Box::pin(async move {
                    let child_path =
                        StablePath::root().concat_part(StableKey::Str(Arc::from("child")));
                    let child = ctx
                        .component()
                        .mount_child(&FnCallContext::new(true), child_path)?;
                    let child_processor = TestProcessor::new(
                        "child",
                        Fingerprint::from(&"preview_after_update/child").unwrap(),
                        Arc::new(AtomicBool::new(false)),
                        false,
                    )
                    .with_reusable_changed_memo_states();
                    child
                        .use_mount(&ctx, child_processor, DeadlineContext::NONE)
                        .await?;
                    Ok(TestData(b"ret".to_vec()))
                })
            }))
        };
        let run = |run: &'static str, preview: bool| {
            let app = &app;
            async move {
                let (handle, _) = app
                    .update(
                        root(run),
                        AppUpdateOptions::default(),
                        Arc::new(()),
                        preview.then(PreviewActionCollector::<TestProfile>::default),
                    )
                    .unwrap();
                handle.result().await.unwrap();
            }
        };

        run("v1", false).await;
        let contents_before = app_store_contents(&app).await;
        run("v2", true).await;
        assert!(
            app_store_contents(&app).await == contents_before,
            "preview must not rewrite memo states"
        );
    }

    /// `drop_app` reverts the target states of a root provider that a run
    /// registered at run time (in its build state, not in the environment's
    /// registry): the handler sees a deletion for each of them, and its sink
    /// applies it.
    #[tokio::test]
    async fn drop_app_reverts_a_root_provider_registered_at_run_time() {
        let (app, _dir) = test_app("drop_run_time_provider").await;
        let apply_calls = Arc::new(AtomicUsize::new(0));
        let reconcile_calls = Arc::new(AtomicUsize::new(0));
        let root = {
            let (apply_calls, reconcile_calls) = (apply_calls.clone(), reconcile_calls.clone());
            TestProcessor::new(
                "root",
                Fingerprint::from(&"drop_run_time_provider").unwrap(),
                Arc::new(AtomicBool::new(false)),
                false,
            )
            .without_memo()
            .with_on_process(Arc::new(move |ctx| {
                let sink = TargetActionSinkKeeper::new(NoopSink {
                    apply_calls: apply_calls.clone(),
                    children: None,
                    failing: None,
                    recording: None,
                });
                let reconcile_calls = reconcile_calls.clone();
                Box::pin(async move {
                    let provider = register_root_target_state_provider(
                        &ctx,
                        "target".to_string(),
                        CountingHandler {
                            reconcile_calls,
                            sink,
                            reject: false,
                            change_only: true,
                            plans_deletes: false,
                        },
                    )?;
                    for key in [0, 1] {
                        declare_target_state(
                            &ctx,
                            &FnCallContext::default(),
                            provider.clone(),
                            StableKey::Int(key),
                            (),
                        )?;
                    }
                    Ok(TestData(b"ret".to_vec()))
                })
            }))
        };
        let (handle, _) = app
            .update(root, AppUpdateOptions::default(), Arc::new(()), None)
            .unwrap();
        handle.result().await.unwrap();
        assert_eq!(apply_calls.load(Ordering::SeqCst), 1);
        assert_eq!(reconcile_calls.load(Ordering::SeqCst), 2);

        app.drop_app(Arc::new(())).unwrap().result().await.unwrap();
        assert_eq!(
            reconcile_calls.load(Ordering::SeqCst),
            4,
            "drop reconciles both target states of the run-time provider away"
        );
        assert_eq!(
            apply_calls.load(Ordering::SeqCst),
            2,
            "drop applies the deletions through the provider's sink"
        );
    }

    /// A re-run of an unmemoized component that declares the same target
    /// states, which its handler finds unchanged, writes nothing: neither its
    /// precommit nor its commit has a page to write, so no write txn commits
    /// and the store keeps every byte. A changed declaration still writes,
    /// and the run after it is again write-free.
    #[tokio::test]
    async fn an_unchanged_rerun_commits_no_write_txn() {
        let (app, _dir) = test_app("unchanged_rerun").await;
        let apply_calls = Arc::new(AtomicUsize::new(0));
        let root = |keys: Vec<i64>| {
            let apply_calls = apply_calls.clone();
            TestProcessor::new(
                "root",
                Fingerprint::from(&"unchanged_rerun").unwrap(),
                Arc::new(AtomicBool::new(false)),
                false,
            )
            .without_memo()
            .with_on_process(Arc::new(move |ctx| {
                let keys = keys.clone();
                let sink = TargetActionSinkKeeper::new(NoopSink {
                    apply_calls: apply_calls.clone(),
                    children: None,
                    failing: None,
                    recording: None,
                });
                Box::pin(async move {
                    let provider = register_root_target_state_provider(
                        &ctx,
                        "target".to_string(),
                        CountingHandler {
                            reconcile_calls: Arc::new(AtomicUsize::new(0)),
                            sink,
                            reject: false,
                            change_only: true,
                            plans_deletes: false,
                        },
                    )?;
                    for key in keys {
                        declare_target_state(
                            &ctx,
                            &FnCallContext::default(),
                            provider.clone(),
                            StableKey::Int(key),
                            (),
                        )?;
                    }
                    Ok(TestData(b"ret".to_vec()))
                })
            }))
        };
        let run = |keys: Vec<i64>, full_reprocess: bool| {
            let options = AppUpdateOptions {
                full_reprocess,
                ..AppUpdateOptions::default()
            };
            let (handle, _) = app.update(root(keys), options, Arc::new(()), None).unwrap();
            async move { handle.result().await.unwrap() }
        };
        let last_txn_id = || {
            app.app_ctx()
                .persisting_app_store()
                .env()
                .info()
                .last_txn_id
        };

        run(vec![0, 1], false).await;
        assert_eq!(apply_calls.load(Ordering::SeqCst), 1);
        let (txn_before, contents_before) = (last_txn_id(), app_store_contents(&app).await);
        run(vec![0, 1], false).await;
        assert_eq!(apply_calls.load(Ordering::SeqCst), 1, "nothing to apply");
        assert_eq!(
            last_txn_id(),
            txn_before,
            "an unchanged re-run commits no write txn"
        );
        assert!(app_store_contents(&app).await == contents_before);

        // A dropped declaration applies its deletion and commits.
        run(vec![0], false).await;
        assert_eq!(apply_calls.load(Ordering::SeqCst), 2);
        assert_ne!(last_txn_id(), txn_before);
        let (txn_dropped, contents_dropped) = (last_txn_id(), app_store_contents(&app).await);
        assert!(contents_dropped != contents_before);
        run(vec![0], false).await;
        assert_eq!(last_txn_id(), txn_dropped);
        assert!(app_store_contents(&app).await == contents_dropped);

        // Declaring it again applies its creation and commits.
        let applied = apply_calls.load(Ordering::SeqCst);
        run(vec![0, 1], false).await;
        assert_eq!(apply_calls.load(Ordering::SeqCst), applied + 1);
        assert_ne!(last_txn_id(), txn_dropped);

        // `full_reprocess` re-applies every target state, and the next
        // ordinary run is write-free again.
        run(vec![0, 1], true).await;
        assert_eq!(apply_calls.load(Ordering::SeqCst), applied + 2);
        let txn_reprocessed = last_txn_id();
        run(vec![0, 1], false).await;
        assert_eq!(apply_calls.load(Ordering::SeqCst), applied + 2);
        assert_eq!(last_txn_id(), txn_reprocessed);
    }

    /// A deprecated slot-fulfilling sink still works for a real update, but
    /// fails a preview with an error naming the unsupported case.
    #[tokio::test]
    async fn legacy_slot_sink_applies_but_fails_preview() {
        let (app, _dir) = test_app("preview_child_provider_legacy").await;
        let (container_sink, container_apply_calls, child_reconcile_calls) =
            NoopSink::container(ChildHandling::LegacySlots);
        let container_sink = TargetActionSinkKeeper::new(container_sink);

        let (handle, _) = app
            .update(
                container_root(container_sink.clone(), 1),
                AppUpdateOptions::default(),
                Arc::new(()),
                Some(PreviewActionCollector::<TestProfile>::default()),
            )
            .unwrap();
        let Err(err) = handle.result().await else {
            panic!("preview must fail when the sink cannot preview child target states");
        };
        assert!(
            err.to_string()
                .contains("does not support preview of child target states"),
            "unexpected error: {err}"
        );

        let (handle, _) = app
            .update(
                container_root(container_sink, 1),
                AppUpdateOptions::default(),
                Arc::new(()),
                None,
            )
            .unwrap();
        handle.result().await.unwrap();
        assert_eq!(container_apply_calls.load(Ordering::SeqCst), 1);
        assert_eq!(child_reconcile_calls.load(Ordering::SeqCst), 1);
    }

    /// A target state declared with a child under a sink that builds no child
    /// handlers fails its component before the sink is called.
    #[tokio::test]
    async fn child_declaration_under_a_leaf_sink_fails_before_apply() {
        let (app, _dir) = test_app("child_under_leaf_sink").await;
        let leaf_sink = NoopSink::default();
        let apply_calls = leaf_sink.apply_calls.clone();
        let (handle, _) = app
            .update(
                container_root(TargetActionSinkKeeper::new(leaf_sink), 1),
                AppUpdateOptions::default(),
                Arc::new(()),
                None,
            )
            .unwrap();
        let Err(err) = handle.result().await else {
            panic!("a child declared under a leaf sink must fail");
        };
        assert!(
            err.to_string().contains("builds no child handlers"),
            "unexpected error: {err}"
        );
        assert_eq!(apply_calls.load(Ordering::SeqCst), 0);
    }

    /// Precommits that share a write batch fail independently, even across
    /// apps sharing the environment: a target handler rejecting one
    /// component's target state fails that component's submit alone.
    #[tokio::test]
    async fn rejected_target_state_fails_only_its_own_components_submit() {
        let (accepting_app, _dir) = test_app("accepting_app").await;
        let env = accepting_app.app_ctx().env().clone();
        let rejecting_app = App::new("rejecting_app", env.clone(), None).await.unwrap();

        let batch = hold_write_batch(env.storage()).await;

        // Each app's root component declares one target state, through a
        // handler that accepts it or rejects it.
        let root_ctx = |app: &App<TestProfile>, reject: bool| {
            let ctx = Component::new(app.app_ctx().clone(), StablePath::root(), None)
                .new_processor_context_for_build(
                    None,
                    ProcessingStats::new(),
                    false,
                    false,
                    None,
                    Arc::new(()),
                    None,
                    None,
                )
                .unwrap();
            let reconcile_calls = Arc::new(AtomicUsize::new(0));
            let provider = register_root_target_state_provider(
                &ctx,
                "target".to_string(),
                CountingHandler {
                    reconcile_calls: reconcile_calls.clone(),
                    sink: TargetActionSinkKeeper::new(NoopSink::default()),
                    reject,
                    change_only: false,
                    plans_deletes: false,
                },
            )
            .unwrap();
            declare_target_state(
                &ctx,
                &FnCallContext::default(),
                provider,
                StableKey::Int(0),
                (),
            )
            .unwrap();
            (ctx, reconcile_calls)
        };
        let (accepting_ctx, accepting_reconcile_calls) = root_ctx(&accepting_app, false);
        let (rejecting_ctx, _) = root_ctx(&rejecting_app, true);
        let processor = TestProcessor::new(
            "root",
            Fingerprint::from(&"rejected_target_state").unwrap(),
            Arc::new(AtomicBool::new(false)),
            false,
        );

        // Polling each submit once runs it up to queuing its precommit: the
        // accepting one first, so the rejection aborts a txn it ran in.
        let mut accepting = std::pin::pin!(submit(&accepting_ctx, Some(&processor), |_| {}));
        assert!(futures::poll!(accepting.as_mut()).is_pending());
        let mut rejecting = std::pin::pin!(submit(&rejecting_ctx, Some(&processor), |_| {}));
        assert!(futures::poll!(rejecting.as_mut()).is_pending());

        batch.release().await;
        let Err(err) = rejecting.await else {
            panic!("the rejecting component's submit must fail");
        };
        assert!(
            err.to_string().contains("rejected"),
            "unexpected error: {err}"
        );
        accepting
            .await
            .expect("the accepting component's submit must not fail with the rejecting one");
        assert_eq!(
            accepting_reconcile_calls.load(Ordering::SeqCst),
            2,
            "the accepting precommit runs again to commit without the rejected one"
        );
    }

    /// A root whose memo key is `run`: it mounts each of `children`, each of
    /// which records its path in `ran` when its body runs. A child's stored memo
    /// stays reusable, so that only a miss runs it.
    fn mounting_root(
        run: &str,
        children: &'static [&'static str],
        ran: &Arc<Mutex<Vec<String>>>,
    ) -> TestProcessor {
        let ran = ran.clone();
        TestProcessor::new(
            "root",
            Fingerprint::from(&run).unwrap(),
            Arc::new(AtomicBool::new(false)),
            false,
        )
        .with_on_process(Arc::new(move |ctx| {
            let ran = ran.clone();
            Box::pin(async move {
                for child in children {
                    let ran = ran.clone();
                    let processor = TestProcessor::new(
                        child,
                        Fingerprint::from(child).unwrap(),
                        Arc::new(AtomicBool::new(false)),
                        false,
                    )
                    .with_reusable_memo_states()
                    .with_on_process(Arc::new(move |ctx| {
                        ran.lock().unwrap().push(ctx.stable_path().to_string());
                        Box::pin(async { Ok(TestData(b"child".to_vec())) })
                    }));
                    ctx.component()
                        .mount_child(&FnCallContext::new(true), key_path(ctx.component(), child))?
                        .mount(&ctx, processor, None)
                        .await?;
                }
                Ok(TestData(b"root".to_vec()))
            })
        }))
    }

    async fn run_update(app: &App<TestProfile>, root: TestProcessor, options: AppUpdateOptions) {
        let (handle, _) = app.update(root, options, Arc::new(()), None).unwrap();
        handle.result().await.unwrap();
    }

    fn select(key: &str) -> Option<ComponentSelector> {
        Some(ComponentSelector::new([
            StablePath::root().concat_part(StableKey::Str(Arc::from(key)))
        ]))
    }

    /// Not creating the tombstone in the first place: the child's row, tracking
    /// record and memo stay byte for byte, whether the root skipped its mount
    /// ("a", still mounted) or no longer mounts it ("b").
    #[tokio::test]
    async fn an_unselected_component_is_not_run_and_keeps_what_the_store_holds_for_it() {
        let (app, _dir) = test_app("selector_unselected").await;
        let ran = Arc::new(Mutex::new(Vec::new()));
        run_update(
            &app,
            mounting_root("full", &["a", "b", "c"], &ran),
            AppUpdateOptions::default(),
        )
        .await;
        assert_eq!(ran.lock().unwrap().len(), 3);
        ran.lock().unwrap().clear();

        let app_store = app.app_ctx().persisting_app_store();
        let path = |key: &str| StablePath::root().concat_part(StableKey::Str(Arc::from(key)));
        let stored = |key: &'static str| {
            let app_store = app_store.clone();
            let path = path(key);
            async move {
                (
                    app_store.read_tracking_info(&path).await.unwrap(),
                    app_store.read_component_memo(&path).await.unwrap(),
                )
            }
        };
        let (a_before, b_before) = (stored("a").await, stored("b").await);
        assert!(a_before.0.is_some() && a_before.1.is_some());
        assert!(b_before.0.is_some() && b_before.1.is_some());

        // A full reprocess, so that a child the selector lets through would run.
        run_update(
            &app,
            mounting_root("selective", &["a", "c"], &ran),
            AppUpdateOptions {
                full_reprocess: true,
                component_selector: select("c"),
                ..AppUpdateOptions::default()
            },
        )
        .await;
        assert_eq!(*ran.lock().unwrap(), vec![path("c").to_string()]);

        assert_eq!(stored("a").await, a_before);
        assert_eq!(stored("b").await, b_before);
        let key = StableKey::Str(Arc::from("b"));
        assert_eq!(
            app_store
                .read_path_node_type(StablePath::root().as_ref(), &key)
                .await
                .unwrap(),
            Some(StablePathNodeType::Component)
        );
        assert!(
            app_store
                .list_tombstones(&StablePath::root())
                .await
                .unwrap()
                .is_empty()
        );

        // A run the selector does not limit sees "b" gone.
        run_update(
            &app,
            mounting_root("full again", &["a", "c"], &ran),
            AppUpdateOptions::default(),
        )
        .await;
        assert_eq!(
            app_store
                .read_path_node_type(StablePath::root().as_ref(), &key)
                .await
                .unwrap(),
            None
        );
    }

    /// A memo says the subtree is up to date, which a run that left out a child
    /// cannot say. It stores none, and retires the one it ran over: a later
    /// update must run the component to reach that child.
    #[tokio::test]
    async fn a_run_that_left_out_a_child_stores_no_memo_and_drops_the_stored_one() {
        let (app, _dir) = test_app("selector_memo").await;
        let ran = Arc::new(Mutex::new(Vec::new()));
        let app_store = app.app_ctx().persisting_app_store().clone();
        let root_memo = || {
            let app_store = app_store.clone();
            async move {
                app_store
                    .read_component_memo(&StablePath::root())
                    .await
                    .unwrap()
            }
        };

        run_update(
            &app,
            mounting_root("same key", &["a", "b"], &ran),
            AppUpdateOptions::default(),
        )
        .await;
        assert!(root_memo().await.is_some());

        run_update(
            &app,
            mounting_root("same key", &["a", "b"], &ran),
            AppUpdateOptions {
                full_reprocess: true,
                component_selector: select("a"),
                ..AppUpdateOptions::default()
            },
        )
        .await;
        assert!(root_memo().await.is_none());

        // Nothing left out, though under a selector: the run is complete.
        let key_path_of =
            |key: &str| StablePath::root().concat_part(StableKey::Str(Arc::from(key)));
        run_update(
            &app,
            mounting_root("same key", &["a", "b"], &ran),
            AppUpdateOptions {
                full_reprocess: true,
                component_selector: Some(ComponentSelector::new([
                    key_path_of("a"),
                    key_path_of("b"),
                ])),
                ..AppUpdateOptions::default()
            },
        )
        .await;
        assert!(root_memo().await.is_some());

        // "b" is on disk, no longer mounted, and not selected: it is left out.
        run_update(
            &app,
            mounting_root("same key", &["a"], &ran),
            AppUpdateOptions {
                full_reprocess: true,
                component_selector: select("a"),
                ..AppUpdateOptions::default()
            },
        )
        .await;
        assert!(root_memo().await.is_none());

        // Selecting the root is no limit: the run is an ordinary one.
        run_update(
            &app,
            mounting_root("same key", &["a", "b"], &ran),
            AppUpdateOptions {
                component_selector: Some(ComponentSelector::new([StablePath::root()])),
                ..AppUpdateOptions::default()
            },
        )
        .await;
        assert!(root_memo().await.is_some());
    }

    #[tokio::test]
    async fn an_unselected_live_component_does_not_mount() {
        let (app, _dir) = test_app("selector_live").await;
        let contents_before = app_store_contents(&app).await;
        let ctx = Component::new(app.app_ctx().clone(), StablePath::root(), None)
            .new_processor_context_for_build(
                None,
                ProcessingStats::new(),
                false,
                false,
                None,
                Arc::new(()),
                None,
                select("selected"),
            )
            .unwrap();
        let live_path = |key: &str| key_path(ctx.component(), key);
        assert!(
            mount_live_prepare(
                &ctx,
                &FnCallContext::default(),
                live_path("unselected"),
                false
            )
            .unwrap()
            .is_none()
        );
        assert!(app_store_contents(&app).await == contents_before);
        assert!(
            mount_live_prepare(
                &ctx,
                &FnCallContext::default(),
                live_path("selected"),
                false
            )
            .unwrap()
            .is_some()
        );
    }

    /// The root mounts `m` while `mount` is set; `m` declares nothing and
    /// mounts `m/l`, which declares one target state through a handler that
    /// plans its delete, applied by `sink`.
    fn nested_root(sink: TargetActionSinkKeeper<TestProfile>, mount: bool) -> TestProcessor {
        fn new_processor(name: &str) -> TestProcessor {
            TestProcessor::new(
                name,
                Fingerprint::from(&format!("nested_root/{name}")).unwrap(),
                Arc::new(AtomicBool::new(false)),
                false,
            )
        }
        type ProviderSlot = Arc<Mutex<Option<TargetStateProvider<TestProfile>>>>;
        let provider: ProviderSlot = Default::default();
        let leaf = {
            let provider = provider.clone();
            new_processor("leaf").with_on_process(Arc::new(move |ctx| {
                let provider = provider.lock().unwrap().clone().unwrap();
                Box::pin(async move {
                    declare_target_state(
                        &ctx,
                        &FnCallContext::default(),
                        provider,
                        StableKey::Int(0),
                        (),
                    )?;
                    Ok(TestData(b"leaf".to_vec()))
                })
            }))
        };
        let leaf = Mutex::new(Some(leaf));
        let mid = new_processor("mid").with_on_process(Arc::new(move |ctx| {
            let leaf = leaf.lock().unwrap().take().unwrap();
            Box::pin(async move {
                let child = ctx
                    .component()
                    .mount_child(&FnCallContext::new(true), key_path(ctx.component(), "l"))?;
                child
                    .use_mount(&ctx, leaf, DeadlineContext::NONE)
                    .await?
                    .result(Some(&ctx))
                    .await?;
                Ok(TestData(b"mid".to_vec()))
            })
        }));
        let mid = Mutex::new(Some(mid));
        new_processor("root").with_on_process(Arc::new(move |ctx| {
            let mid = mid.lock().unwrap().take().unwrap();
            let provider = provider.clone();
            let sink = sink.clone();
            Box::pin(async move {
                *provider.lock().unwrap() = Some(register_root_target_state_provider(
                    &ctx,
                    "target".to_string(),
                    CountingHandler {
                        reconcile_calls: Arc::new(AtomicUsize::new(0)),
                        sink,
                        reject: false,
                        plans_deletes: true,
                        change_only: false,
                    },
                )?);
                if mount {
                    let child = ctx
                        .component()
                        .mount_child(&FnCallContext::new(true), key_path(ctx.component(), "m"))?;
                    child
                        .use_mount(&ctx, mid, DeadlineContext::NONE)
                        .await?
                        .result(Some(&ctx))
                        .await?;
                }
                Ok(TestData(b"ret".to_vec()))
            })
        }))
    }

    /// A child delete that fails under a deleted parent keeps the parent's
    /// tombstone too, so the next update deletes the parent again, and with
    /// it the child. Were the parent's tombstone cleaned, the child's, keyed
    /// under the gone parent, would never be swept again.
    #[tokio::test]
    async fn a_failed_delete_under_a_deleted_parent_is_retried() {
        let (app, _dir) = test_app("failed_delete_under_deleted_parent").await;
        let failing = Arc::new(AtomicBool::new(false));
        let sink = NoopSink {
            failing: Some(failing.clone()),
            ..Default::default()
        };
        let apply_calls = sink.apply_calls.clone();
        let sink = TargetActionSinkKeeper::new(sink);
        let update = |mount: bool| {
            let (handle, _) = app
                .update(
                    nested_root(sink.clone(), mount),
                    AppUpdateOptions::default(),
                    Arc::new(()),
                    None,
                )
                .unwrap();
            handle.result()
        };
        let app_store = app.app_ctx().persisting_app_store();
        let m = StablePath::root().concat_part(StableKey::Str(Arc::from("m")));
        let l = StablePath::root().concat_part(StableKey::Str(Arc::from("l")));

        update(true).await.unwrap();
        assert_eq!(apply_calls.load(Ordering::SeqCst), 1, "the upsert");

        // Unmount `m`; the delete of `m/l`'s target state fails. With no
        // handler installed, the update still succeeds.
        failing.store(true, Ordering::SeqCst);
        update(false).await.unwrap();
        failing.store(false, Ordering::SeqCst);
        assert_eq!(apply_calls.load(Ordering::SeqCst), 2, "the failed delete");
        assert_eq!(app_store.list_tombstones(&m).await.unwrap(), vec![l]);
        assert_eq!(
            app_store
                .list_tombstones(&StablePath::root())
                .await
                .unwrap(),
            vec![m.clone()],
            "`m` keeps its tombstone while its child's delete is owed"
        );

        update(false).await.unwrap();
        assert_eq!(apply_calls.load(Ordering::SeqCst), 3, "the retried delete");
        assert!(app_store.list_tombstones(&m).await.unwrap().is_empty());
        assert!(
            app_store
                .list_tombstones(&StablePath::root())
                .await
                .unwrap()
                .is_empty()
        );

        update(false).await.unwrap();
        assert_eq!(
            apply_calls.load(Ordering::SeqCst),
            3,
            "nothing left to delete"
        );
    }

    /// A root processor that registers a run-time root provider per entry of
    /// `sinks`, in their order, and declares one target state through each.
    fn declaring_root(
        test: &str,
        sinks: Vec<(&'static str, TargetActionSinkKeeper<TestProfile>)>,
    ) -> TestProcessor {
        TestProcessor::new(
            "root",
            Fingerprint::from(&test).unwrap(),
            Arc::new(AtomicBool::new(false)),
            false,
        )
        .without_memo()
        .with_on_process(Arc::new(move |ctx| {
            let sinks = sinks.clone();
            Box::pin(async move {
                for (name, sink) in sinks {
                    let provider = register_root_target_state_provider(
                        &ctx,
                        name.to_string(),
                        CountingHandler {
                            reconcile_calls: Default::default(),
                            sink,
                            reject: false,
                            change_only: false,
                            plans_deletes: true,
                        },
                    )?;
                    declare_target_state(
                        &ctx,
                        &FnCallContext::default(),
                        provider,
                        StableKey::Int(0),
                        (),
                    )?;
                }
                Ok(TestData(b"ret".to_vec()))
            })
        }))
    }

    /// Sinks of providers at one depth apply in the order of the providers'
    /// keys, whatever order the run declared through them, on every run.
    #[tokio::test]
    async fn sinks_of_providers_at_one_depth_apply_in_provider_key_order() {
        let (app, _dir) = test_app("sink_order").await;
        let applied = Arc::new(Mutex::new(Vec::new()));
        let sink = |name: &str| {
            TargetActionSinkKeeper::new(NoopSink {
                recording: Some(Recording {
                    applied: applied.clone(),
                    name: name.to_string(),
                }),
                ..Default::default()
            })
        };
        let sinks = vec![("c", sink("c")), ("a", sink("a")), ("b", sink("b"))];
        for run in 0..8 {
            applied.lock().unwrap().clear();
            let (handle, _) = app
                .update(
                    declaring_root("sink_order", sinks.clone()),
                    AppUpdateOptions::default(),
                    Arc::new(()),
                    None,
                )
                .unwrap();
            handle.result().await.unwrap();
            assert_eq!(*applied.lock().unwrap(), ["a", "b", "c"], "run {run}");
        }
    }

    /// Sinks of shallower providers apply first, whatever their keys: the
    /// container's provider is keyed `tables` and the other root provider `z`,
    /// which sorts after it, yet the rows (depth 1, under `tables`) apply
    /// last. The key chain alone would put the rows before `z`.
    #[tokio::test]
    async fn sinks_of_shallower_providers_apply_first_whatever_their_keys() {
        let (app, _dir) = test_app("sink_depth_order").await;
        let applied = Arc::new(Mutex::new(Vec::new()));
        let recording = |name: &str| Recording {
            applied: applied.clone(),
            name: name.to_string(),
        };
        let (mut container, _, _) = NoopSink::container(ChildHandling::Factory);
        container.recording = Some(recording("a"));
        let container_sink = TargetActionSinkKeeper::new(container);
        let root_sink = TargetActionSinkKeeper::new(NoopSink {
            recording: Some(recording("z")),
            ..Default::default()
        });
        for run in 0..8 {
            applied.lock().unwrap().clear();
            let root =
                container_root_with(container_sink.clone(), 2, Some(("z", root_sink.clone())));
            let (handle, _) = app
                .update(root, AppUpdateOptions::default(), Arc::new(()), None)
                .unwrap();
            handle.result().await.unwrap();
            assert_eq!(
                *applied.lock().unwrap(),
                ["a", "z", "a/rows"],
                "run {run}: containers before rows, keys within a depth"
            );
        }
    }

    /// A failed sink's error names the target states it was applying: the
    /// connector's own error says what failed, not where.
    #[tokio::test]
    async fn a_failed_sink_names_the_target_states_it_was_applying() {
        let (app, _dir) = test_app("failing_sink").await;
        let sink = TargetActionSinkKeeper::new(NoopSink {
            failing: Some(Arc::new(AtomicBool::new(true))),
            ..Default::default()
        });
        let (handle, _) = app
            .update(
                declaring_root("failing_sink", vec![("orders", sink)]),
                AppUpdateOptions::default(),
                Arc::new(()),
                None,
            )
            .unwrap();
        let message = handle
            .result()
            .await
            .expect_err("the sink fails")
            .to_string();
        assert!(
            message.contains("failed to apply changes to target states under @orders"),
            "{message}"
        );
        assert!(message.contains("injected sink failure"), "{message}");
    }
}