Skip to content

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

68.4 KB
Raw Blame
from __future__ import annotations

import asyncio
import threading
import traceback
from collections.abc import AsyncIterator, Awaitable, Callable
from typing import Any

import pytest

import cocoindex as coco

from tests import common
from tests.common.target_states import AtMost, GlobalDictTarget, DictDataWithPrev

coco_env = common.create_test_env(__file__)

_source_data: dict[str, int] = {}


# ============================================================================
# Rejection tests
# ============================================================================


class _MinimalLiveComponent:
    async def process(self) -> None:
        pass

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        pass


def test_live_component_rejected_in_use_mount() -> None:
    async def _main() -> None:
        await coco.use_mount(coco.component_subpath("x"), _MinimalLiveComponent)

    app = coco.App(
        coco.AppConfig(name="test_rejected_use_mount", environment=coco_env),
        _main,
    )
    with pytest.raises(TypeError, match="cannot be used with use_mount"):
        app.update_blocking()


# ============================================================================
# Basic lifecycle tests
# ============================================================================


def _declare_source_entries() -> None:
    for key, value in _source_data.items():
        coco.declare_target_state(GlobalDictTarget.target_state(key, value))


class _BasicLiveComponent:
    """LiveComponent that processes _source_data into GlobalDictTarget."""

    async def process(self) -> None:
        _declare_source_entries()

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        await operator.update_full()
        await operator.mark_ready()


def test_live_component_basic_full_update() -> None:
    GlobalDictTarget.store.clear()
    _source_data.clear()

    _source_data["a"] = 1
    _source_data["b"] = 2

    async def _main() -> None:
        await coco.mount(coco.component_subpath("live"), _BasicLiveComponent)

    app = coco.App(
        coco.AppConfig(name="test_live_basic_full_update", environment=coco_env),
        _main,
    )
    app.update_blocking(live=True)

    assert GlobalDictTarget.store.data == {
        "a": DictDataWithPrev(data=1, prev=[], prev_may_be_missing=True),
        "b": DictDataWithPrev(data=2, prev=[], prev_may_be_missing=True),
    }


class _CatchUpLiveComponent:
    """LiveComponent that loops forever after mark_ready (tests catch-up termination)."""

    async def process(self) -> None:
        _declare_source_entries()

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        await operator.update_full()
        await operator.mark_ready()
        # In catch-up mode, mark_ready should terminate process_live.
        # This infinite loop should never execute.
        while True:
            await asyncio.sleep(1)


def test_live_component_catch_up_mode() -> None:
    GlobalDictTarget.store.clear()
    _source_data.clear()

    _source_data["x"] = 10

    async def _main() -> None:
        await coco.mount(coco.component_subpath("live"), _CatchUpLiveComponent)

    app = coco.App(
        coco.AppConfig(name="test_live_catch_up_mode", environment=coco_env),
        _main,
    )
    # Catch-up mode (default): should complete without hanging
    app.update_blocking()

    assert GlobalDictTarget.store.data == {
        "x": DictDataWithPrev(data=10, prev=[], prev_may_be_missing=True),
    }


class _AutoReadyLiveComponent:
    """LiveComponent where process_live returns without calling mark_ready."""

    async def process(self) -> None:
        _declare_source_entries()

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        await operator.update_full()
        # Deliberately NOT calling mark_ready β€” ensure_mark_ready should auto-call it


def test_live_component_mark_ready_auto_on_return() -> None:
    GlobalDictTarget.store.clear()
    _source_data.clear()

    _source_data["auto"] = 42

    async def _main() -> None:
        await coco.mount(coco.component_subpath("live"), _AutoReadyLiveComponent)

    app = coco.App(
        coco.AppConfig(name="test_live_mark_ready_auto", environment=coco_env),
        _main,
    )
    app.update_blocking(live=True)

    assert GlobalDictTarget.store.data == {
        "auto": DictDataWithPrev(data=42, prev=[], prev_may_be_missing=True),
    }


# ============================================================================
# read_committed_state / write_committed_state (the Live keyspace)
# ============================================================================


_committed_reads: list[Any] = []


class _BootstrapStateLiveComponent:
    """Commits a marker via ``operator.write_committed_state`` (the ``Live``
    keyspace) and reads it back via ``operator.read_committed_state`` at the
    top of ``process_live`` β€” the bootstrap-detection pattern: a later run
    observes what the prior run committed, before its own ``update_full``
    runs.
    """

    async def process(self) -> None:
        _declare_source_entries()

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        # Read BEFORE update_full so we observe the PRIOR run's commit, not
        # anything from this run.
        _committed_reads.append(await operator.read_committed_state("marker"))
        await operator.update_full()
        # Persist the bootstrap marker for the next run to read back. Lives
        # in the Live keyspace, separate from any `coco.use_state` in
        # `process()`.
        await operator.write_committed_state("marker", 100)
        await operator.mark_ready()


def test_read_committed_state_across_runs() -> None:
    GlobalDictTarget.store.clear()
    _source_data.clear()
    _committed_reads.clear()
    _source_data["k"] = 1

    async def _main() -> None:
        await coco.mount(coco.component_subpath("live"), _BootstrapStateLiveComponent)

    app = coco.App(
        coco.AppConfig(name="test_read_committed_state", environment=coco_env),
        _main,
    )

    # Run 1: nothing committed yet -> None; commits marker=100 via the Live path.
    app.update_blocking()
    # Run 2: reads back the value committed by run 1.
    app.update_blocking()

    assert _committed_reads == [None, 100]


_iso_boot_reads: list[Any] = []


class _LiveBootSurvivesRegularPrune:
    """Regression for the ``StateKind`` split (PR #2078): a live component's
    ``process()`` runs a *Regular* ``coco.use_state`` flush whose
    set-reduction prunes every prefetched key it does not redeclare. The
    live machinery's *Live* committed state, written via
    ``operator.write_committed_state``, must be exempt from that prune.

    The read happens AFTER ``update_full()`` (i.e. after ``process()``'s
    Regular flush has run) so that, pre-fix β€” when both kinds shared one
    ``UserState`` prefix β€” the flush would have pruned the ``"boot"`` key it
    never redeclared, and the assertion below would see ``None``.
    """

    async def process(self) -> None:
        # A Regular use_state key, declared every run. Its presence makes the
        # set-reduction flush active; pre-fix the Live "boot" key shared this
        # keyspace and would be pruned because `process()` never redeclares it.
        coco.use_state("reg", 0)
        _declare_source_entries()

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        # Commit the Live bootstrap key once (run 1).
        if await operator.read_committed_state("boot") is None:
            await operator.write_committed_state("boot", "ready")
        # Run process(), which flushes the Regular keyspace with prune...
        await operator.update_full()
        # ...then confirm the Live key still survives that flush.
        _iso_boot_reads.append(await operator.read_committed_state("boot"))
        await operator.mark_ready()


def test_live_state_survives_regular_use_state_prune() -> None:
    GlobalDictTarget.store.clear()
    _source_data.clear()
    _iso_boot_reads.clear()
    _source_data["k"] = 1

    async def _main() -> None:
        await coco.mount(coco.component_subpath("live"), _LiveBootSurvivesRegularPrune)

    app = coco.App(
        coco.AppConfig(name="test_live_state_survives_prune", environment=coco_env),
        _main,
    )

    # Run 1 commits "boot"; run 2's process() runs a Regular flush that must
    # not touch the Live "boot" key. Both runs read it back as "ready".
    app.update_blocking()
    app.update_blocking()

    assert _iso_boot_reads == ["ready", "ready"]


# ============================================================================
# Incremental operations
# ============================================================================


def _declare_item(key: str, value: int) -> None:
    coco.declare_target_state(GlobalDictTarget.target_state(key, value))


class _IncrementalUpdateLiveComponent:
    """LiveComponent that does a full update then an incremental update."""

    async def process(self) -> None:
        _declare_source_entries()

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        await operator.update_full()
        # Incremental: add a new item not in _source_data
        handle = await operator.update(
            coco.component_subpath("new_item"), _declare_item, "new_key", 99
        )
        await handle.ready()
        # mark_ready called AFTER incremental operations so update_blocking waits
        await operator.mark_ready()


# Slice F: nested LiveCompClass via operator.update
class _InnerLiveComponent:
    """Inner live component mounted via operator.update(LiveCompClass)."""

    async def process(self) -> None:
        coco.declare_target_state(GlobalDictTarget.target_state("inner_marker", 7))

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        await operator.update_full()
        await operator.mark_ready()


class _OuterLiveComponentWithInner:
    """Outer live component that mounts an inner live component via operator.update.

    Exercises Slice F: the LiveCompClass branch in `operator.update()` should
    install the inner controller under the outer's `update_full_lock`, spawn
    the inner's `process_live`, and wait for the inner's `mark_ready`.
    """

    async def process(self) -> None:
        coco.declare_target_state(GlobalDictTarget.target_state("outer_marker", 1))

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        await operator.update_full()
        # Mount a nested live component at "inner" subpath.
        handle = await operator.update(
            coco.component_subpath("inner"), _InnerLiveComponent
        )
        await handle.ready()
        await operator.mark_ready()


def test_in_process_live_blocks_coco_mount() -> None:
    """Polish 2: `coco.mount(...)` inside `process_live` raises RuntimeError.

    Verifies the `_in_process_live` ContextVar enforcement directly:
    when the var is `True` (as it is inside `process_live`), the entry
    points `coco.mount` / `coco.mount_each` / `coco.use_mount` must
    raise a `RuntimeError` mentioning `process_live`.

    The integration shape β€” that the var is actually set to `True` for
    `process_live`'s body β€” is covered by the positive-case test
    (`test_process_inside_live_can_call_coco_mount`): if the var weren't
    set, calls inside `process()` would only succeed because the var was
    already `False`, not because of the symmetric reset, which means
    `process_live`'s body would also see `False`. The fact that the
    positive case passes after the symmetric reset takes effect
    (combined with the var defaulting to `False`) is the load-bearing
    end-to-end signal that the True/False machinery works.
    """
    from cocoindex._internal.live_component import (
        _in_process_live,
        check_not_in_process_live,
    )

    # Default: not in process_live β†’ no raise.
    assert _in_process_live.get() is False
    check_not_in_process_live("coco.mount")  # should not raise

    # Simulate inside process_live: var set to True β†’ must raise.
    prev = _in_process_live.get()
    _in_process_live.set(True)
    try:
        with pytest.raises(RuntimeError, match="not allowed inside process_live"):
            check_not_in_process_live("coco.mount")
        with pytest.raises(RuntimeError, match="not allowed inside process_live"):
            check_not_in_process_live("coco.mount_each")
        with pytest.raises(RuntimeError, match="not allowed inside process_live"):
            check_not_in_process_live("coco.use_mount")
    finally:
        _in_process_live.set(prev)


class _LiveComponentInnerCallsCocoMount:
    """Polish 2 positive test: process() inside live can call coco.mount safely."""

    async def process(self) -> None:
        # This MUST NOT raise β€” process() is a separate context; the
        # symmetric reset in update_full sets _in_process_live=False
        # before the new Task captures Context for process()'s body.
        await coco.mount(coco.component_subpath("ok"), _declare_item, "marker", 99)

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        await operator.update_full()
        await operator.mark_ready()


def test_process_inside_live_can_call_coco_mount() -> None:
    """Polish 2: `coco.mount(...)` from inside `process()` of a live component
    must work β€” `update_full`'s inline `_in_process_live = False` reset
    takes effect for the asyncio Task that runs `process()`.

    This is the load-bearing positive case (design.md integration test #3):
    if the symmetric reset breaks, every `process()` of a live component
    would falsely raise here.
    """
    GlobalDictTarget.store.clear()

    async def _main() -> None:
        await coco.mount(
            coco.component_subpath("inner_ok"), _LiveComponentInnerCallsCocoMount
        )

    app = coco.App(
        coco.AppConfig(
            name="test_process_inside_live_can_call_coco_mount",
            environment=coco_env,
        ),
        _main,
    )
    app.update_blocking()
    # The inner mount declared the marker.
    assert "marker" in GlobalDictTarget.store.data


def test_live_component_operator_update_with_live_class() -> None:
    """operator.update(LiveCompClass) installs and runs a nested live component.

    Verifies Slice F: the cancellable update_full_lock acquisition, fresh
    parent_ctx construction, mount_live_prepare + complete sequence, and
    inner controller startup all wire up correctly. Both outer and inner
    target states should be declared.
    """
    GlobalDictTarget.store.clear()
    _source_data.clear()

    async def _main() -> None:
        await coco.mount(coco.component_subpath("outer"), _OuterLiveComponentWithInner)

    app = coco.App(
        coco.AppConfig(name="test_operator_update_live_class", environment=coco_env),
        _main,
    )
    app.update_blocking()

    # Both outer's process() and inner's process() (via inner's update_full
    # invoked from inner's process_live) should have declared their markers.
    assert "outer_marker" in GlobalDictTarget.store.data
    assert GlobalDictTarget.store.data["outer_marker"].data == 1
    assert "inner_marker" in GlobalDictTarget.store.data
    assert GlobalDictTarget.store.data["inner_marker"].data == 7


def test_live_component_incremental_update() -> None:
    GlobalDictTarget.store.clear()
    _source_data.clear()

    _source_data["a"] = 1
    _source_data["b"] = 2

    async def _main() -> None:
        await coco.mount(
            coco.component_subpath("live"), _IncrementalUpdateLiveComponent
        )

    app = coco.App(
        coco.AppConfig(name="test_live_incremental_update", environment=coco_env),
        _main,
    )
    app.update_blocking(live=True)

    assert "a" in GlobalDictTarget.store.data
    assert "b" in GlobalDictTarget.store.data
    assert "new_key" in GlobalDictTarget.store.data
    assert GlobalDictTarget.store.data["new_key"].data == 99


# ----------------------------------------------------------------------------
# `update()` before any `update_full()`
#
# A live component has no Build of its own at mount time, so its existence
# row is written at mount (`MountLivePending::complete`). Without it, the
# first `update()` child's eager upsert fills the live component's path in
# as a Directory, and the parent's commit β€” seeing Directory -> Component β€”
# tombstones every child mounted so far.
# ----------------------------------------------------------------------------


def _stored() -> dict[str, int]:
    return {k: v.data for k, v in GlobalDictTarget.store.data.items()}


class _UpdateOnlyLiveComponent:
    """LiveComponent that only ever calls `update()`, never `update_full()`.

    The shape of a watch-only feed (e.g. a message-queue source).
    """

    async def process(self) -> None:
        pass

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        for key, value in _source_data.items():
            handle = await operator.update(
                coco.component_subpath(key), _declare_item, key, value
            )
            await handle.ready()
        await operator.mark_ready()


def test_live_component_update_before_any_update_full_keeps_children() -> None:
    GlobalDictTarget.store.clear()
    _source_data.clear()

    async def _main() -> None:
        await coco.mount(coco.component_subpath("live"), _UpdateOnlyLiveComponent)

    app = coco.App(
        coco.AppConfig(name="test_live_update_only_first_run", environment=coco_env),
        _main,
    )

    # Run 1 (live mode): children added by `update()` before any `update_full()`
    # survive the parent's first commit, and are never deleted along the way.
    _source_data.update(a=1, b=2)
    GlobalDictTarget.store.metrics.clear()
    app.update_blocking(live=True)
    assert _stored() == {"a": 1, "b": 2}
    assert GlobalDictTarget.store.metrics.collect() == {"sink": AtMost(2), "upsert": 2}

    # Run 2 (one-shot): only `c` is sent. Without a full scan nothing is
    # reconciled away, so the earlier children stay.
    _source_data.clear()
    _source_data.update(c=3)
    GlobalDictTarget.store.metrics.clear()
    app.update_blocking()
    assert _stored() == {"a": 1, "b": 2, "c": 3}
    assert GlobalDictTarget.store.metrics.collect() == {"sink": AtMost(1), "upsert": 1}


def test_live_component_update_only_unmounted_on_next_run_is_gcd() -> None:
    """The row written at mount is what makes the live component discoverable
    to its parent's reconciliation: when a later run no longer mounts it, the
    children it added with `update()` are cleaned up along with it."""
    GlobalDictTarget.store.clear()
    _source_data.clear()
    mount_live = True

    async def _main() -> None:
        if mount_live:
            await coco.mount(coco.component_subpath("live"), _UpdateOnlyLiveComponent)

    app = coco.App(
        coco.AppConfig(name="test_live_update_only_gc", environment=coco_env),
        _main,
    )
    _source_data.update(a=1, b=2)
    app.update_blocking(live=True)
    assert _stored() == {"a": 1, "b": 2}

    mount_live = False
    GlobalDictTarget.store.metrics.clear()
    app.update_blocking()
    assert _stored() == {}
    assert GlobalDictTarget.store.metrics.collect() == {"sink": AtMost(2), "delete": 2}


async def _parent_of_update_only_live() -> None:
    """Non-live parent that mounts the live component below a Directory
    segment, i.e. at `/parent/src/live`."""
    await coco.mount(coco.component_subpath("src", "live"), _UpdateOnlyLiveComponent)


def test_live_component_update_only_under_nonroot_parent_and_directory() -> None:
    """The mount-time write covers the ancestor chain too: `src` as a
    Directory under the (non-root) parent, then `live` as a Component."""
    GlobalDictTarget.store.clear()
    _source_data.clear()
    _source_data.update(a=1, b=2)

    async def _main() -> None:
        await coco.mount(coco.component_subpath("parent"), _parent_of_update_only_live)

    app = coco.App(
        coco.AppConfig(name="test_live_update_only_nested_path", environment=coco_env),
        _main,
    )
    GlobalDictTarget.store.metrics.clear()
    app.update_blocking(live=True)
    assert _stored() == {"a": 1, "b": 2}
    assert GlobalDictTarget.store.metrics.collect() == {"sink": AtMost(2), "upsert": 2}


class _OuterUpdateOnlyWithInnerLive:
    """Outer live component that never calls `update_full()` and mounts an
    update-only inner live component via `operator.update(LiveCompClass)`."""

    async def process(self) -> None:
        pass

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        handle = await operator.update(
            coco.component_subpath("inner"), _UpdateOnlyLiveComponent
        )
        await handle.ready()
        await operator.mark_ready()


def test_live_component_nested_update_only_live_keeps_children() -> None:
    GlobalDictTarget.store.clear()
    _source_data.clear()
    _source_data.update(a=1, b=2)

    async def _main() -> None:
        await coco.mount(coco.component_subpath("outer"), _OuterUpdateOnlyWithInnerLive)

    app = coco.App(
        coco.AppConfig(name="test_live_nested_update_only", environment=coco_env),
        _main,
    )
    GlobalDictTarget.store.metrics.clear()
    app.update_blocking(live=True)
    assert _stored() == {"a": 1, "b": 2}
    assert GlobalDictTarget.store.metrics.collect() == {"sink": AtMost(2), "upsert": 2}


def test_live_component_update_only_preview_plans_without_applying() -> None:
    """A preview of an update-only live component plans its children's
    upserts, applies nothing, and leaves no state behind for the real run."""
    GlobalDictTarget.store.clear()
    _source_data.clear()
    _source_data.update(a=1, b=2)

    async def _main() -> None:
        await coco.mount(coco.component_subpath("live"), _UpdateOnlyLiveComponent)

    app = coco.App(
        coco.AppConfig(name="test_live_update_only_preview", environment=coco_env),
        _main,
    )
    GlobalDictTarget.store.metrics.clear()
    actions = app.update_blocking(preview=True)
    assert isinstance(actions, list)
    assert len(actions) == 2
    assert GlobalDictTarget.store.data == {}
    assert GlobalDictTarget.store.metrics.collect() == {}

    app.update_blocking()
    assert _stored() == {"a": 1, "b": 2}
    assert GlobalDictTarget.store.metrics.collect() == {"sink": AtMost(2), "upsert": 2}


class _WatchOnlyFeed:
    """A `LiveMapFeed` with `watch()` only: the message-queue source shape."""

    async def watch(
        self, subscriber: coco.LiveMapSubscriber[coco.StableKey, tuple[str, int]]
    ) -> None:
        for key, value in _source_data.items():
            handle = await subscriber.update(key, (key, value))
            await handle.ready()
        await subscriber.mark_ready()


def _declare_feed_item(item: tuple[str, int]) -> None:
    coco.declare_target_state(GlobalDictTarget.target_state(item[0], item[1]))


def test_mount_each_watch_only_feed_keeps_items_across_runs() -> None:
    GlobalDictTarget.store.clear()
    _source_data.clear()
    _source_data.update(a=1, b=2)

    async def _main() -> None:
        await coco.mount_each(_declare_feed_item, _WatchOnlyFeed())

    app = coco.App(
        coco.AppConfig(name="test_mount_each_watch_only_feed", environment=coco_env),
        _main,
    )
    GlobalDictTarget.store.metrics.clear()
    app.update_blocking(live=True)
    assert _stored() == {"a": 1, "b": 2}
    assert GlobalDictTarget.store.metrics.collect() == {"sink": AtMost(2), "upsert": 2}

    # Restart: the feed only delivers `c`. There is no scan to reconcile
    # against, so the items from the first run stay.
    _source_data.clear()
    _source_data.update(c=3)
    GlobalDictTarget.store.metrics.clear()
    app.update_blocking(live=True)
    assert _stored() == {"a": 1, "b": 2, "c": 3}
    assert GlobalDictTarget.store.metrics.collect() == {"sink": AtMost(1), "upsert": 1}


class _IncrementalDeleteDirectLiveComponent:
    """LiveComponent that tests direct deletion via operator.delete().

    process() mounts child components for each key in _source_data.
    process_live() does a full update, then directly deletes one child.
    """

    async def process(self) -> None:
        for key, value in _source_data.items():
            await coco.mount(coco.component_subpath(key), _declare_item, key, value)

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        await operator.update_full()
        # Directly delete the child that was mounted by process() for key "b"
        handle = await operator.delete(coco.component_subpath("b"))
        await handle.ready()
        await operator.mark_ready()


def test_live_component_incremental_delete_direct() -> None:
    """operator.delete() removes a child originally created by update_full()."""
    GlobalDictTarget.store.clear()
    _source_data.clear()

    _source_data["a"] = 1
    _source_data["b"] = 2

    async def _main() -> None:
        await coco.mount(
            coco.component_subpath("live"), _IncrementalDeleteDirectLiveComponent
        )

    app = coco.App(
        coco.AppConfig(
            name="test_live_incremental_delete_direct", environment=coco_env
        ),
        _main,
    )
    app.update_blocking(live=True)

    # "a" should remain, "b" should be deleted
    assert "a" in GlobalDictTarget.store.data
    assert "b" not in GlobalDictTarget.store.data


class _CreateThenDeleteAtOnceLiveComponent:
    """Issues an update and a delete of the same new child without awaiting
    the update first, for many children."""

    async def process(self) -> None:
        pass

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        await operator.update_full()
        handles = []
        for i in range(50):
            key = f"tmp{i}"
            handles.append(
                await operator.update(
                    coco.component_subpath(key), _declare_item, key, i
                )
            )
            handles.append(await operator.delete(coco.component_subpath(key)))
        for handle in handles:
            await handle.ready()
        await operator.mark_ready()


def test_live_component_delete_right_after_update_leaves_nothing() -> None:
    """A delete issued while the same child's update is already running wins:
    the update's target state does not survive it."""
    GlobalDictTarget.store.clear()

    async def _main() -> None:
        await coco.mount(
            coco.component_subpath("live"), _CreateThenDeleteAtOnceLiveComponent
        )

    app = coco.App(
        coco.AppConfig(
            name="test_live_delete_right_after_update", environment=coco_env
        ),
        _main,
    )
    app.update_blocking(live=True)

    survivors = [k for k in GlobalDictTarget.store.data if str(k).startswith("tmp")]
    assert survivors == []


class _DeleteOnRequestLiveComponent:
    """Mounts a child per source key; deletes child "b" through
    operator.delete() when `delete_b` is set."""

    delete_b = False

    async def process(self) -> None:
        for key, value in _source_data.items():
            await coco.mount(coco.component_subpath(key), _declare_item, key, value)

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        await operator.update_full()
        if _DeleteOnRequestLiveComponent.delete_b:
            handle = await operator.delete(coco.component_subpath("b"))
            await handle.ready()
        await operator.mark_ready()


def test_live_component_delete_in_preview_applies_nothing() -> None:
    """In a preview, operator.delete() plans the deletion of the child's target
    states, but neither deletes the child nor leaves a tombstone: the next real
    update keeps the child."""
    GlobalDictTarget.store.clear()
    _source_data.clear()
    _DeleteOnRequestLiveComponent.delete_b = False

    _source_data["a"] = 1
    _source_data["b"] = 2

    async def _main() -> None:
        await coco.mount(coco.component_subpath("live"), _DeleteOnRequestLiveComponent)

    app = coco.App(
        coco.AppConfig(
            name="test_live_component_delete_in_preview", environment=coco_env
        ),
        _main,
    )
    app.update_blocking()
    assert set(GlobalDictTarget.store.data) == {"a", "b"}
    GlobalDictTarget.store.metrics.clear()

    _DeleteOnRequestLiveComponent.delete_b = True
    try:
        actions = app.update_blocking(preview=True)
    finally:
        _DeleteOnRequestLiveComponent.delete_b = False
    # Planned, not applied.
    assert actions is not None
    assert [(key, coco.is_non_existence(value)) for key, value in actions] == [
        ("b", True)
    ]
    assert set(GlobalDictTarget.store.data) == {"a", "b"}
    assert GlobalDictTarget.store.metrics.collect() == {}

    # Nothing is written: a tombstone left by the preview would have `b`
    # re-upserted here.
    app.update_blocking()
    assert set(GlobalDictTarget.store.data) == {"a", "b"}
    assert GlobalDictTarget.store.metrics.collect() == {}


class _CommittedStateLiveComponent:
    """Records the committed value it reads, then commits a new one."""

    seen: list[Any] = []

    async def process(self) -> None:
        pass

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        _CommittedStateLiveComponent.seen.append(
            await operator.read_committed_state("marker")
        )
        await operator.write_committed_state("marker", "done")
        # Read back within the run: also in a preview, which persists nothing.
        _CommittedStateLiveComponent.seen.append(
            await operator.read_committed_state("marker")
        )
        await operator.update_full()
        await operator.mark_ready()


def test_live_component_preview_commits_no_state() -> None:
    """write_committed_state() in a preview is not persisted, so the next real
    run does not skip work the preview never did; within the preview, a later
    read sees it, as in a real run."""
    _CommittedStateLiveComponent.seen = []

    async def _main() -> None:
        await coco.mount(coco.component_subpath("live"), _CommittedStateLiveComponent)

    app = coco.App(
        coco.AppConfig(
            name="test_live_component_preview_commits_no_state",
            environment=coco_env,
        ),
        _main,
    )
    app.update_blocking(live=True, preview=True)
    app.update_blocking(live=True)
    app.update_blocking(live=True)
    assert _CommittedStateLiveComponent.seen == [
        None,
        "done",  # preview: read back in the run, not persisted
        None,
        "done",  # first real run
        "done",
        "done",  # persisted
    ]


class _IncrementalDeleteNoStaleComponent:
    """LiveComponent for testing that incremental delete doesn't leave stale tombstones.

    First run: process() mounts "a" and "b", process_live() deletes "b".
    Second run: process() mounts only "a", process_live() does nothing extra.
    The second run should NOT produce an "<unknown>" deletion for "b".
    """

    async def process(self) -> None:
        for key, value in _source_data.items():
            await coco.mount(coco.component_subpath(key), _declare_item, key, value)

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        await operator.update_full()
        # Delete "b" only if it's in the current source data
        if "b" in _source_data:
            handle = await operator.delete(coco.component_subpath("b"))
            await handle.ready()
        await operator.mark_ready()


@pytest.mark.asyncio
async def test_live_component_incremental_delete_no_stale_tombstone() -> None:
    """After incremental delete, a second run should not produce '<unknown>' deletions."""
    GlobalDictTarget.store.clear()
    _source_data.clear()

    _source_data["a"] = 1
    _source_data["b"] = 2

    async def _main() -> None:
        await coco.mount(
            coco.component_subpath("live"), _IncrementalDeleteNoStaleComponent
        )

    app = coco.App(
        coco.AppConfig(name="test_live_incr_delete_no_stale", environment=coco_env),
        _main,
    )

    # First run: deletes "b" incrementally
    app.update_blocking(live=True)
    assert "a" in GlobalDictTarget.store.data
    assert "b" not in GlobalDictTarget.store.data

    # Second run: "b" no longer in source, should be a clean run
    _source_data.pop("b", None)
    handle = app.update(live=True)
    await handle.result()
    stats = handle.stats()
    assert stats is not None

    # There should be no "<unknown>" component in the stats
    assert "<unknown>" not in stats.by_component, (
        f"Stale tombstone caused '<unknown>' deletion: {stats.by_component}"
    )


class _IncrementalDeleteViaGCLiveComponent:
    """LiveComponent that tests deletion via update_full GC.

    The update_full GC mechanism is the primary way children get cleaned up:
    any children mounted by the previous update_full but NOT mounted by the
    current update_full are garbage collected.
    """

    async def process(self) -> None:
        _declare_source_entries()

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        # First full update: adds "a" and "b" from _source_data
        await operator.update_full()
        # Incrementally add "extra"
        handle = await operator.update(
            coco.component_subpath("extra"), _declare_item, "extra_key", 42
        )
        await handle.ready()
        # Second full update: process() still only declares "a" and "b".
        # The incremental "extra" child was not mounted by process(), so it
        # gets GC'd by the second update_full.
        await operator.update_full()
        # mark_ready auto-called on return


def test_live_component_incremental_delete() -> None:
    GlobalDictTarget.store.clear()
    _source_data.clear()

    _source_data["a"] = 1
    _source_data["b"] = 2

    async def _main() -> None:
        await coco.mount(
            coco.component_subpath("live"), _IncrementalDeleteViaGCLiveComponent
        )

    app = coco.App(
        coco.AppConfig(name="test_live_incremental_delete", environment=coco_env),
        _main,
    )
    app.update_blocking(live=True)

    # a and b should remain from both full updates
    assert "a" in GlobalDictTarget.store.data
    assert "b" in GlobalDictTarget.store.data
    # extra_key should have been GC'd by the second update_full
    assert "extra_key" not in GlobalDictTarget.store.data


# State for GC test β€” controlled by a flag to change behavior between update_full calls
_gc_phase: int = 0


def _declare_gc_entries() -> None:
    """Declares entries based on _gc_phase:
    Phase 0: A, B, C
    Phase 1+: A, B only
    """
    if _gc_phase == 0:
        coco.declare_target_state(GlobalDictTarget.target_state("gc_a", 1))
        coco.declare_target_state(GlobalDictTarget.target_state("gc_b", 2))
        coco.declare_target_state(GlobalDictTarget.target_state("gc_c", 3))
    else:
        coco.declare_target_state(GlobalDictTarget.target_state("gc_a", 1))
        coco.declare_target_state(GlobalDictTarget.target_state("gc_b", 2))


class _GCLiveComponent:
    """LiveComponent that tests GC via two update_full calls."""

    async def process(self) -> None:
        _declare_gc_entries()

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        global _gc_phase
        # First full update: A, B, C
        _gc_phase = 0
        await operator.update_full()

        # Incremental add D
        handle = await operator.update(
            coco.component_subpath("d_item"), _declare_item, "gc_d", 4
        )
        await handle.ready()

        # Second full update: only A, B (C removed from process, D was incremental)
        _gc_phase = 1
        await operator.update_full()
        # mark_ready auto-called on return


def test_live_component_update_full_gc() -> None:
    GlobalDictTarget.store.clear()
    _source_data.clear()

    async def _main() -> None:
        await coco.mount(coco.component_subpath("live"), _GCLiveComponent)

    app = coco.App(
        coco.AppConfig(name="test_live_update_full_gc", environment=coco_env),
        _main,
    )
    app.update_blocking(live=True)

    # After second update_full: only A and B should exist. C and D should be GC'd.
    assert "gc_a" in GlobalDictTarget.store.data
    assert "gc_b" in GlobalDictTarget.store.data
    assert "gc_c" not in GlobalDictTarget.store.data
    assert "gc_d" not in GlobalDictTarget.store.data


# ============================================================================
# LiveComponentOperator.report_exception
# ============================================================================


class _LiveThatReports:
    """Live component that calls operator.report_exception once after mark_ready."""

    def __init__(self, exc: BaseException) -> None:
        self._exc = exc

    async def process(self) -> None:
        coco.declare_target_state(GlobalDictTarget.target_state("marker", 1))

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        await operator.update_full()
        await operator.mark_ready()
        await operator.report_exception(self._exc)


def _raise_for_trace_test() -> None:
    raise ValueError("traceful boom")


class _LiveThatReportsCaught:
    """Raises and catches a ValueError, then reports it β€” exc.__traceback__ is real."""

    async def process(self) -> None:
        coco.declare_target_state(GlobalDictTarget.target_state("marker", 1))

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        await operator.update_full()
        await operator.mark_ready()
        try:
            _raise_for_trace_test()
        except ValueError as exc:
            await operator.report_exception(exc)


def test_report_exception_routes_to_global_handler() -> None:
    """report_exception walks the parent's exception handler chain."""
    GlobalDictTarget.store.clear()

    seen: list[tuple[str, str, str, str | None, str | None]] = []

    def handler(exc: BaseException, ctx: coco.ExceptionContext) -> None:
        seen.append(
            (
                type(exc).__name__,
                ctx.mount_kind,
                ctx.stable_path,
                ctx.parent_stable_path,
                ctx.processor_name,
            )
        )

    env = common.create_test_env(
        __file__, suffix="report_exc_global", exception_handler=handler
    )

    async def _root() -> None:
        await coco.mount(
            coco.component_subpath("live"),
            _LiveThatReports,
            ValueError("boom from cycle"),
        )

    app = coco.App(
        coco.AppConfig(name="test_report_exc_global", environment=env), _root
    )
    app.update_blocking(live=True)

    assert len(seen) == 1
    exc_name, mount_kind, stable_path, parent_path, processor_name = seen[0]
    # report_exception passes the original exception through unchanged
    assert exc_name == "ValueError"
    assert mount_kind == "process_live"
    # The live component's path includes the "live" subpath component
    assert "live" in stable_path
    # Parent is the root context
    assert parent_path is not None
    assert processor_name == "_LiveThatReports"


def test_report_exception_surfaces_python_traceback() -> None:
    """The handler should see the original exception with its traceback intact."""
    GlobalDictTarget.store.clear()

    seen: list[BaseException] = []

    def handler(exc: BaseException, ctx: coco.ExceptionContext) -> None:
        seen.append(exc)

    env = common.create_test_env(
        __file__, suffix="report_exc_trace", exception_handler=handler
    )

    async def _root() -> None:
        await coco.mount(coco.component_subpath("live"), _LiveThatReportsCaught)

    app = coco.App(coco.AppConfig(name="test_report_exc_trace", environment=env), _root)
    app.update_blocking(live=True)

    assert len(seen) == 1
    exc = seen[0]
    assert isinstance(exc, ValueError)
    assert str(exc) == "traceful boom"
    assert exc.__traceback__ is not None
    formatted = "".join(traceback.format_exception(exc))
    assert "Traceback (most recent call last)" in formatted
    assert "_raise_for_trace_test" in formatted


async def _failing_child(value: int) -> None:
    raise ValueError(f"child failed with value={value}")


async def _child_declare_one(value: int) -> None:
    """Helper for delete-propagation test: declares a single target row."""
    coco.declare_target_state(GlobalDictTarget.target_state("c", value))


class _LiveThatDeletesWithFailingSink:
    """Mount a child, await ready, toggle the sink to fail, then delete.

    ``operator.delete`` is symmetric with ``operator.update`` β€”
    failures route through the parent's exception handler chain.
    Handlers control whether ``handle.ready()`` raises (raise to
    propagate, return to swallow). This test verifies the routing.
    """

    async def process(self) -> None:
        pass

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        await operator.update_full()
        h = await operator.update(coco.component_subpath("c"), _child_declare_one, 1)
        await h.ready()
        await operator.mark_ready()
        GlobalDictTarget.store.sink_exception = True
        try:
            dh = await operator.delete(coco.component_subpath("c"))
            await dh.ready()
        finally:
            GlobalDictTarget.store.sink_exception = False


def test_operator_delete_failure_routes_to_handler() -> None:
    """`operator.delete()` failure β†’ handler chain (mount-style symmetry
    with `operator.update`). Handler that returns normally β†’ swallow."""
    GlobalDictTarget.store.clear()
    GlobalDictTarget.store.sink_exception = False

    seen: list[tuple[str, str, str]] = []

    def handler(exc: BaseException, ctx: coco.ExceptionContext) -> None:
        seen.append((type(exc).__name__, ctx.mount_kind, ctx.stable_path))

    env = common.create_test_env(
        __file__, suffix="delete_route", exception_handler=handler
    )

    async def _root() -> None:
        await coco.mount(
            coco.component_subpath("live"), _LiveThatDeletesWithFailingSink
        )

    app = coco.App(coco.AppConfig(name="test_delete_route", environment=env), _root)
    app.update_blocking(live=True)

    assert len(seen) == 1
    exc_name, mount_kind, stable_path = seen[0]
    assert exc_name == "ValueError"
    assert mount_kind == "process_live"
    assert "c" in stable_path


class _LiveThatDeletesWithRaisingHandler:
    """`operator.delete` with a raising-handler: handle.ready() should raise.

    The raise should propagate via the user's handler chain β†’ Rust
    on_error returns Err β†’ spawned task task_result = Err β†’
    HandleOutcome::Executed(Err) β†’ user's await handle.ready() raises.
    """

    delete_err: BaseException | None = None

    async def process(self) -> None:
        pass

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        type(self).delete_err = None
        await operator.update_full()
        h = await operator.update(coco.component_subpath("c"), _child_declare_one, 1)
        await h.ready()
        await operator.mark_ready()
        GlobalDictTarget.store.sink_exception = True
        try:
            dh = await operator.delete(coco.component_subpath("c"))
            try:
                await dh.ready()
            except Exception as e:
                # Hold the real exception object on a class attribute:
                # exercises the operator-detach guarantee (the framework
                # releases the controller in `_process_live_wrapper`'s
                # finally, so the exception's traceback no longer pins
                # the live component's Arc via `operator`).
                type(self).delete_err = e
        finally:
            GlobalDictTarget.store.sink_exception = False


@pytest.mark.timeout(10, method="thread")
def test_operator_delete_failure_propagates_via_raising_handler() -> None:
    """A handler that raises must propagate the err to handle.ready()."""
    GlobalDictTarget.store.clear()
    GlobalDictTarget.store.sink_exception = False
    _LiveThatDeletesWithRaisingHandler.delete_err = None

    async def raising_handler(exc: BaseException, ctx: coco.ExceptionContext) -> None:
        raise exc

    env = common.create_test_env(
        __file__, suffix="delete_raise", exception_handler=raising_handler
    )

    async def _root() -> None:
        await coco.mount(
            coco.component_subpath("live"), _LiveThatDeletesWithRaisingHandler
        )

    app = coco.App(coco.AppConfig(name="test_delete_raise", environment=env), _root)
    app.update_blocking(live=True)

    err = _LiveThatDeletesWithRaisingHandler.delete_err
    assert err is not None
    assert "injected sink exception" in str(err)


class _LiveThatUpdatesFailingChild:
    """Mount a child via operator.update() that raises; the loop continues."""

    update_err: BaseException | None = None

    async def process(self) -> None:
        coco.declare_target_state(GlobalDictTarget.target_state("marker", 1))

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        type(self).update_err = None
        await operator.update_full()
        await operator.mark_ready()
        handle = await operator.update(
            coco.component_subpath("bad_child"), _failing_child, 42
        )
        try:
            await handle.ready()
        except Exception as e:
            # Hold the real exception (with traceback) on a class
            # attribute to verify the operator-detach guarantee:
            # `_process_live_wrapper`'s finally releases the controller
            # so the retained traceback can't pin the live component.
            type(self).update_err = e


def test_operator_update_child_failure_routes_to_handler() -> None:
    """A child mounted via operator.update() that raises should be routed
    through the parent's exception handler chain with mount_kind='process_live'
    β€” same as update_full() cycle failures, not silently logged via Rust."""
    GlobalDictTarget.store.clear()
    _LiveThatUpdatesFailingChild.update_err = None

    seen: list[tuple[str, str, str]] = []

    def handler(exc: BaseException, ctx: coco.ExceptionContext) -> None:
        seen.append((type(exc).__name__, ctx.mount_kind, ctx.stable_path))

    env = common.create_test_env(
        __file__, suffix="op_update_failure", exception_handler=handler
    )

    async def _root() -> None:
        await coco.mount(coco.component_subpath("live"), _LiveThatUpdatesFailingChild)

    app = coco.App(
        coco.AppConfig(name="test_op_update_failure", environment=env), _root
    )
    app.update_blocking(live=True)

    assert len(seen) == 1
    exc_name, mount_kind, stable_path = seen[0]
    assert exc_name == "ValueError"
    assert mount_kind == "process_live"
    assert "bad_child" in stable_path
    # Swallowing handler β†’ no propagation
    assert _LiveThatUpdatesFailingChild.update_err is None


@pytest.mark.timeout(10, method="thread")
def test_operator_update_child_failure_propagates_via_raising_handler() -> None:
    """operator.update with a RAISING handler: handle.ready() should raise.
    Probe to localize the hang β€” if this also hangs, the issue is in the
    on_error mechanism generally, not delete-specific."""
    GlobalDictTarget.store.clear()
    _LiveThatUpdatesFailingChild.update_err = None

    def raising(exc: BaseException, ctx: coco.ExceptionContext) -> None:
        raise exc

    env = common.create_test_env(
        __file__, suffix="op_update_raise", exception_handler=raising
    )

    async def _root() -> None:
        await coco.mount(coco.component_subpath("live"), _LiveThatUpdatesFailingChild)

    app = coco.App(coco.AppConfig(name="test_op_update_raise", environment=env), _root)
    app.update_blocking(live=True)

    err = _LiveThatUpdatesFailingChild.update_err
    assert err is not None
    assert "child failed with value=42" in str(err)


def test_report_exception_falls_back_to_log_when_no_handler(
    caplog: pytest.LogCaptureFixture,
) -> None:
    """With no handler registered, report_exception logs at ERROR."""
    GlobalDictTarget.store.clear()

    env = common.create_test_env(__file__, suffix="report_exc_no_handler")

    async def _root() -> None:
        await coco.mount(
            coco.component_subpath("live"),
            _LiveThatReports,
            RuntimeError("no handler boom"),
        )

    app = coco.App(
        coco.AppConfig(name="test_report_exc_no_handler", environment=env), _root
    )
    with caplog.at_level("ERROR"):
        app.update_blocking(live=True)

    assert any(
        record.levelname == "ERROR"
        and "no handler boom" in record.getMessage()
        and record.exc_info is not None
        and "no handler boom" in str(record.exc_info[1])
        for record in caplog.records
    )


# ============================================================================
# LiveMapView + mount_each tests
# ============================================================================


class _TestLiveMapView:
    """A simple LiveMapView for testing.

    Yields (key, key) pairs β€” the value is the same as the key string.
    The per-item function receives the value (a str) as first arg.
    """

    def __init__(self, data: dict[str, int]) -> None:
        self._data = data
        self._watch_fn: (
            Callable[[coco.LiveMapSubscriber[str, str]], Awaitable[None]] | None
        ) = None

    def set_watch_fn(
        self,
        fn: Callable[[coco.LiveMapSubscriber[str, str]], Awaitable[None]],
    ) -> None:
        self._watch_fn = fn

    def __aiter__(self) -> AsyncIterator[tuple[str, str]]:
        return self._aiter_impl()

    async def _aiter_impl(self) -> AsyncIterator[tuple[str, str]]:
        for k in self._data:
            yield (k, k)

    async def watch(self, subscriber: coco.LiveMapSubscriber[str, str]) -> None:
        await subscriber.update_all()
        if self._watch_fn is not None:
            await self._watch_fn(subscriber)
        await subscriber.mark_ready()


_live_source: dict[str, int] = {}


def _declare_live_item(key: str) -> None:
    """Per-item function for LiveMapView tests. Looks up value from _live_source."""
    value = _live_source[key]
    coco.declare_target_state(GlobalDictTarget.target_state(key, value))


def test_mount_each_live_items_view_basic() -> None:
    GlobalDictTarget.store.clear()
    _live_source.clear()
    _live_source.update({"a": 1, "b": 2, "c": 3})

    items = _TestLiveMapView(_live_source)

    async def _main() -> None:
        await coco.mount_each(_declare_live_item, items)  # type: ignore[call-overload]

    app = coco.App(
        coco.AppConfig(name="test_live_items_basic", environment=coco_env),
        _main,
    )
    app.update_blocking(live=True)

    assert GlobalDictTarget.store.data == {
        "a": DictDataWithPrev(data=1, prev=[], prev_may_be_missing=True),
        "b": DictDataWithPrev(data=2, prev=[], prev_may_be_missing=True),
        "c": DictDataWithPrev(data=3, prev=[], prev_may_be_missing=True),
    }


def test_mount_each_live_items_view_catch_up_mode() -> None:
    GlobalDictTarget.store.clear()
    _live_source.clear()
    _live_source["x"] = 10

    items = _TestLiveMapView(_live_source)

    async def _main() -> None:
        await coco.mount_each(_declare_live_item, items)  # type: ignore[call-overload]

    app = coco.App(
        coco.AppConfig(name="test_live_items_catch_up", environment=coco_env),
        _main,
    )
    # Catch-up mode: mark_ready terminates watch(), app completes
    app.update_blocking()

    assert GlobalDictTarget.store.data == {
        "x": DictDataWithPrev(data=10, prev=[], prev_may_be_missing=True),
    }


def test_mount_each_live_items_view_incremental_update() -> None:
    GlobalDictTarget.store.clear()
    _live_source.clear()
    _live_source["a"] = 1

    items = _TestLiveMapView(_live_source)

    async def _after_ready(subscriber: coco.LiveMapSubscriber[str, str]) -> None:
        _live_source["new_key"] = 99
        handle = await subscriber.update("new_key", "new_key")
        await handle.ready()

    items.set_watch_fn(_after_ready)

    async def _main() -> None:
        await coco.mount_each(_declare_live_item, items)  # type: ignore[call-overload]

    app = coco.App(
        coco.AppConfig(name="test_live_items_incr_update", environment=coco_env),
        _main,
    )
    app.update_blocking(live=True)

    assert "a" in GlobalDictTarget.store.data
    assert "new_key" in GlobalDictTarget.store.data
    assert GlobalDictTarget.store.data["new_key"].data == 99


def test_mount_each_live_items_view_update_all_rescan() -> None:
    GlobalDictTarget.store.clear()
    _live_source.clear()
    _live_source.update({"a": 1, "b": 2, "c": 3})

    items = _TestLiveMapView(_live_source)

    async def _after_ready(subscriber: coco.LiveMapSubscriber[str, str]) -> None:
        # Mutate backing data, then trigger rescan
        _live_source.clear()
        _live_source.update({"a": 1, "d": 4})
        items._data = _live_source
        await subscriber.update_all()

    items.set_watch_fn(_after_ready)

    async def _main() -> None:
        await coco.mount_each(_declare_live_item, items)  # type: ignore[call-overload]

    app = coco.App(
        coco.AppConfig(name="test_live_items_rescan", environment=coco_env),
        _main,
    )
    app.update_blocking(live=True)

    # After rescan: a and d should exist, b and c should be GC'd
    assert "a" in GlobalDictTarget.store.data
    assert "d" in GlobalDictTarget.store.data
    assert "b" not in GlobalDictTarget.store.data
    assert "c" not in GlobalDictTarget.store.data


def test_mount_each_auto_subpath() -> None:
    GlobalDictTarget.store.clear()
    _live_source.clear()
    _live_source["k1"] = 1

    async def _main() -> None:
        await coco.mount_each(_declare_live_item, [("k1", "k1")])  # type: ignore[call-overload]

    app = coco.App(
        coco.AppConfig(name="test_mount_each_auto_subpath", environment=coco_env),
        _main,
    )
    app.update_blocking()

    assert "k1" in GlobalDictTarget.store.data


# ============================================================================
# mount_each with a LiveComponent class as the per-item processor
# ============================================================================


class _PerItemLiveComponent:
    """A LiveComponent used as the per-item processor in ``mount_each``.

    Receives the item value as its sole constructor argument β€” exactly how a
    plain per-item function receives the item as its first positional argument.
    Each item therefore gets its own live component instance.
    """

    def __init__(self, value: int) -> None:
        self._value = value

    async def process(self) -> None:
        coco.declare_target_state(
            GlobalDictTarget.target_state(f"item{self._value}", self._value)
        )

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        await operator.update_full()
        await operator.mark_ready()


def test_mount_each_live_component_per_item_catch_up() -> None:
    """A LiveComponent class can be the per-item processor for static items.

    Catch-up mode: each per-item live component does one full pass and
    terminates after ``mark_ready``.
    """
    GlobalDictTarget.store.clear()

    async def _main() -> None:
        await coco.mount_each(
            coco.component_subpath("items"),
            _PerItemLiveComponent,
            [("a", 1), ("b", 2)],
        )

    app = coco.App(
        coco.AppConfig(
            name="test_mount_each_live_per_item_catch_up", environment=coco_env
        ),
        _main,
    )
    app.update_blocking()

    assert GlobalDictTarget.store.data == {
        "item1": DictDataWithPrev(data=1, prev=[], prev_may_be_missing=True),
        "item2": DictDataWithPrev(data=2, prev=[], prev_may_be_missing=True),
    }


def test_mount_each_live_component_per_item_live_mode() -> None:
    """Same as above but in live mode.

    All per-item live components return after ``mark_ready``, so the app
    becomes inactive and ``update_blocking(live=True)`` returns. This
    exercises readiness aggregation across the per-item live mounts.
    """
    GlobalDictTarget.store.clear()

    async def _main() -> None:
        handle = await coco.mount_each(
            coco.component_subpath("items"),
            _PerItemLiveComponent,
            [("a", 1), ("b", 2), ("c", 3)],
        )
        await handle.ready()

    app = coco.App(
        coco.AppConfig(
            name="test_mount_each_live_per_item_live_mode", environment=coco_env
        ),
        _main,
    )
    app.update_blocking(live=True)

    assert GlobalDictTarget.store.data == {
        "item1": DictDataWithPrev(data=1, prev=[], prev_may_be_missing=True),
        "item2": DictDataWithPrev(data=2, prev=[], prev_may_be_missing=True),
        "item3": DictDataWithPrev(data=3, prev=[], prev_may_be_missing=True),
    }


_per_item_live_source: list[int] = []


def test_mount_each_live_component_per_item_gc_on_rerun() -> None:
    """A per-item live component is GC'd when its item disappears on re-run.

    Confirms the per-item live mounts participate in the normal child-existence
    reconciliation: dropping an item from the source deletes that item's
    component (and its declared target state) on the next ``update``.
    """
    GlobalDictTarget.store.clear()

    async def _main() -> None:
        handle = await coco.mount_each(
            coco.component_subpath("items"),
            _PerItemLiveComponent,
            [(str(v), v) for v in _per_item_live_source],
        )
        await handle.ready()

    app = coco.App(
        coco.AppConfig(name="test_mount_each_live_per_item_gc", environment=coco_env),
        _main,
    )

    _per_item_live_source[:] = [1, 2]
    app.update_blocking()
    assert set(GlobalDictTarget.store.data) == {"item1", "item2"}

    # Re-run with item 2 removed β†’ its per-item live component is GC'd.
    _per_item_live_source[:] = [1]
    app.update_blocking()
    assert set(GlobalDictTarget.store.data) == {"item1"}


class _PerItemLiveComponentByName:
    """Per-item LiveComponent keyed by a string name (for LiveMapView items).

    ``_TestLiveMapView`` yields ``(key, key)``, so the per-item processor
    receives the key string as its value. The component looks up the real
    value from ``_live_source`` β€” mirroring ``_declare_live_item``.
    """

    def __init__(self, name: str) -> None:
        self._name = name

    async def process(self) -> None:
        coco.declare_target_state(
            GlobalDictTarget.target_state(self._name, _live_source[self._name])
        )

    async def process_live(self, operator: coco.LiveComponentOperator) -> None:
        await operator.update_full()
        await operator.mark_ready()


def test_mount_each_live_items_view_with_live_component() -> None:
    """LiveMapView source + LiveComponent per-item processor (recursive case).

    The internal ``_MountEachLiveComponent`` mounts each item via ``mount()``
    (in ``process()``) / ``operator.update()`` (in ``process_live``); both
    install the per-item LiveComponent as a nested live component under the
    outer's ``update_full_lock``.
    """
    GlobalDictTarget.store.clear()
    _live_source.clear()
    _live_source.update({"a": 1, "b": 2})

    items = _TestLiveMapView(_live_source)

    async def _main() -> None:
        await coco.mount_each(
            coco.component_subpath("items"),
            _PerItemLiveComponentByName,
            items,  # type: ignore[arg-type]
        )

    app = coco.App(
        coco.AppConfig(
            name="test_mount_each_live_items_live_component", environment=coco_env
        ),
        _main,
    )
    app.update_blocking(live=True)

    assert GlobalDictTarget.store.data == {
        "a": DictDataWithPrev(data=1, prev=[], prev_may_be_missing=True),
        "b": DictDataWithPrev(data=2, prev=[], prev_may_be_missing=True),
    }


def test_mount_each_no_name_raises() -> None:
    """Callables without __name__ require an explicit ComponentSubpath."""

    class _NoName:
        def __call__(self, x: Any) -> None:
            pass

    fn = _NoName()  # callable instance without __name__

    async def _main() -> None:
        await coco.mount_each(fn, [("a", 1)])  # type: ignore[arg-type]

    app = coco.App(
        coco.AppConfig(name="test_mount_each_no_name", environment=coco_env),
        _main,
    )
    with pytest.raises(TypeError, match="requires a ComponentSubpath"):
        app.update_blocking()


# ============================================================================
# Cancellation
# ============================================================================


@pytest.mark.asyncio
async def test_live_component_global_cancel_terminates_update() -> None:
    """Global cancellation (Ctrl+C path) must reach a blocked process_live coroutine
    and let App.update() terminate.

    Regression test for the bug where AppContextInner.cancellation_token was an
    independent token rather than a child of GLOBAL_CANCEL, so cancel_all() never
    propagated to LiveComponentState child tokens.
    """
    from cocoindex._internal import core as _core

    started = asyncio.Event()
    cancelled_in_python = asyncio.Event()

    class _BlockingLive:
        async def process(self) -> None:
            pass

        async def process_live(self, operator: coco.LiveComponentOperator) -> None:
            await operator.update_full()
            await operator.mark_ready()
            started.set()
            try:
                await asyncio.Event().wait()  # Block forever.
            except asyncio.CancelledError:
                cancelled_in_python.set()
                raise

    async def _main() -> None:
        await coco.mount(coco.component_subpath("live"), _BlockingLive)

    _core.reset_global_cancellation()
    app = coco.App(
        coco.AppConfig(name="test_live_global_cancel_terminates", environment=coco_env),
        _main,
    )
    handle = app.update(live=True)
    # update() is lazy β€” kick it off by spawning a task that awaits result().
    result_task = asyncio.create_task(handle.result())
    try:
        await asyncio.wait_for(started.wait(), timeout=5.0)

        _core.cancel_all()  # simulates SIGINT handler in cli.py

        # Wait for cancellation to actually reach Python before checking. The
        # update task may return before the inner Python cancellation has
        # finished propagating via CancelOnDropPy.
        await asyncio.wait_for(cancelled_in_python.wait(), timeout=5.0)

        try:
            await asyncio.wait_for(result_task, timeout=5.0)
        except Exception:
            pass
    finally:
        if not result_task.done():
            result_task.cancel()
        _core.reset_global_cancellation()


@pytest.mark.asyncio
async def test_catch_up_update_beside_running_live_update() -> None:
    """A catch-up `app.update()` while the same app's live update runs does
    its work and leaves the live incarnation running: its `process_live` is
    not cancelled, and its operator still applies updates afterwards."""
    GlobalDictTarget.store.clear()
    _source_data.clear()
    _source_data["a"] = 1

    # `process_live` runs on the environment's loop, not the test's: signal
    # across them with thread-safe events, polled.
    started = threading.Event()
    cancelled = threading.Event()
    go = threading.Event()
    applied = threading.Event()

    async def _wait(event: threading.Event) -> None:
        for _ in range(1000):
            if event.is_set():
                return
            await asyncio.sleep(0.01)
        raise AssertionError("timed out")

    class _Live:
        async def process(self) -> None:
            _declare_source_entries()

        async def process_live(self, operator: coco.LiveComponentOperator) -> None:
            await operator.update_full()
            # In catch-up mode `mark_ready` ends `process_live` here.
            await operator.mark_ready()
            started.set()
            try:
                await _wait(go)
                handle = await operator.update(
                    coco.component_subpath("late"), _declare_item, "late", 7
                )
                await handle.ready()
                applied.set()
                await asyncio.Event().wait()
            except asyncio.CancelledError:
                cancelled.set()
                raise

    async def _main() -> None:
        await coco.mount(coco.component_subpath("live"), _Live)

    app = coco.App(
        coco.AppConfig(name="test_catch_up_beside_live", environment=coco_env),
        _main,
    )
    live_task = asyncio.create_task(app.update(live=True).result())
    try:
        await _wait(started)
        _source_data["b"] = 2
        await asyncio.wait_for(app.update().result(), timeout=10.0)
        assert "b" in GlobalDictTarget.store.data
        assert not cancelled.is_set(), "the catch-up update cancelled the live one"

        go.set()
        await _wait(applied)
        assert "late" in GlobalDictTarget.store.data
    finally:
        try:
            await app.drop()
        finally:
            live_task.cancel()
            try:
                await live_task
            except BaseException:
                pass


@pytest.mark.asyncio
async def test_live_update_during_catch_up_is_not_reconciled_away() -> None:
    """A live `operator.update()` that lands while a catch-up update beside
    it works from a source listing taken before the update must survive the
    catch-up's commit: it queues behind the catch-up's `update_full` and is
    applied after it, instead of being applied first and then reconciled
    away."""
    GlobalDictTarget.store.clear()
    _source_data.clear()
    _source_data["a"] = 1

    calls = {"n": 0}
    started = threading.Event()
    catch_up_listed = threading.Event()
    release_catch_up = threading.Event()
    applied = threading.Event()

    async def _wait(event: threading.Event) -> None:
        for _ in range(1000):
            if event.is_set():
                return
            await asyncio.sleep(0.01)
        raise AssertionError("timed out")

    class _Live:
        async def process(self) -> None:
            calls["n"] += 1
            snapshot = dict(_source_data)
            if calls["n"] == 2:  # the catch-up update's process()
                catch_up_listed.set()
                await _wait(release_catch_up)
            for key, value in snapshot.items():
                await coco.mount(coco.component_subpath(key), _declare_item, key, value)

        async def process_live(self, operator: coco.LiveComponentOperator) -> None:
            await operator.update_full()
            await operator.mark_ready()
            if calls["n"] != 1:
                return
            started.set()
            await _wait(catch_up_listed)
            _source_data["x"] = 9
            handle = await operator.update(
                coco.component_subpath("x"), _declare_item, "x", 9
            )
            await handle.ready()
            applied.set()
            await asyncio.Event().wait()

    async def _main() -> None:
        await coco.mount(coco.component_subpath("live"), _Live)

    app = coco.App(
        coco.AppConfig(name="test_live_update_during_catch_up", environment=coco_env),
        _main,
    )
    live_task = asyncio.create_task(app.update(live=True).result())
    try:
        await _wait(started)
        catch_up = asyncio.create_task(app.update().result())
        await _wait(catch_up_listed)
        # Give the live update a moment to reach the engine.
        await asyncio.sleep(0.3)
        release_catch_up.set()
        await asyncio.wait_for(catch_up, timeout=10.0)
        await _wait(applied)
        assert "x" in GlobalDictTarget.store.data
    finally:
        release_catch_up.set()
        try:
            await app.drop()
        finally:
            live_task.cancel()
            try:
                await live_task
            except BaseException:
                pass


# ============================================================================
# LiveStream primitives
# ============================================================================


@pytest.mark.asyncio
async def test_immediate_ready_is_immediate() -> None:
    """_IMMEDIATE_READY.ready() resolves without suspension."""
    from cocoindex._internal.live_component import _IMMEDIATE_READY

    fut = _IMMEDIATE_READY.ready()
    # Should already be done after one await with no scheduling.
    await asyncio.wait_for(fut, timeout=0.1)


def test_live_stream_protocol_runtime_check() -> None:
    """A minimal subscriber satisfies LiveStreamSubscriber.isinstance(...)."""
    from cocoindex._internal.live_component import (
        LiveStreamSubscriber,
        ReadyAwaitable,
    )

    class _Sub:
        async def send(self, message: Any) -> ReadyAwaitable:  # noqa: ARG002
            raise NotImplementedError

        async def mark_ready(self) -> None:
            pass

    assert isinstance(_Sub(), LiveStreamSubscriber)
    assert not isinstance(object(), LiveStreamSubscriber)