Incremental engine for long horizon agents π Star if you like it!
Rust agentic-data-frameworkaiai-agentschange-data-capturecodebase-intelligencecontext-engineeringdata-engineeringdata-indexingdata-processingetlhelp-wantedindexingknowledge-graphllmlong-horizon-agentpythonragreal-timerustsemantic-search
fix(cli): make "cocoindex update" exit 1 on failures nobody handled (#2661)
ε°ε‘ε‘ε
bd0fa96f008a
diff --git a/docs/src/content/docs/advanced_topics/exception_handlers.mdx b/docs/src/content/docs/advanced_topics/exception_handlers.mdxindex 5fae42fc..68300045 100644--- a/docs/src/content/docs/advanced_topics/exception_handlers.mdx+++ b/docs/src/content/docs/advanced_topics/exception_handlers.mdx@@ -29,6 +29,7 @@ For a quick overview of failure isolation and the two-phase model, see [What hap| `await LiveComponentOperator.update_full()` | reaches *ready state* of the full cycle | **No by default** β same shape as `handle.ready()` || `await coco.use_mount(...)` | the inner component's *value* is produced | **Yes** β component success is on the critical path || `await app.drop()` (and `cocoindex drop`) | GC succeeds at *every* level | **Yes**, at any depth β leaking target state would otherwise go silent |+| `cocoindex update` | every component of the run has finished, failed or not | **Exit status, not an exception**: exits 1 only when a failure nobody handled happened β a handler that returns normally keeps the exit status at 0 |</Lang>diff --git a/docs/src/content/docs/cli.mdx b/docs/src/content/docs/cli.mdxindex d1779e6d..ca72c952 100644--- a/docs/src/content/docs/cli.mdx+++ b/docs/src/content/docs/cli.mdx@@ -278,6 +278,9 @@ cocoindex show [OPTIONS] [APP_TARGET] [STABLE_PATH]Run an app in catch-up mode. With --live, run in live mode.+Exits with status 1 if a component failure goes unhandled: no exception+handler is registered for it, or every handler re-raised. Not with --live.+`APP_TARGET`: `path/to/app.py`, `module`, `path/to/app.py:app_name`, or`module:app_name`.diff --git a/python/cocoindex/_internal/app.py b/python/cocoindex/_internal/app.pyindex 6ed8ec7f..5b864841 100644--- a/python/cocoindex/_internal/app.py+++ b/python/cocoindex/_internal/app.py@@ -91,6 +91,14 @@ class UpdateHandle(Generic[R]):return Nonereturn self._snapshot_from_handle(self._core_handle).stats+ def _unhandled_failures(self) -> int:+ """Number of component failures nobody took ownership of: no+ exception handler was registered for them, or every handler+ re-raised. Returns 0 if not yet started."""+ if self._core_handle is None:+ return 0+ return self._core_handle.unhandled_failures()+async def watch(self) -> AsyncIterator[UpdateSnapshot[R]]:"""Async iterator that yields progress snapshots.diff --git a/python/cocoindex/_internal/component_ctx.py b/python/cocoindex/_internal/component_ctx.pyindex 78202386..4700ff7a 100644--- a/python/cocoindex/_internal/component_ctx.py+++ b/python/cocoindex/_internal/component_ctx.py@@ -191,22 +191,25 @@ class ComponentContext:if node is None:# No handlers registered β log directly without building# the ExceptionContext metadata at all. Don't propagate.+ self._core_processor_ctx.record_unhandled_failure()+ # The path and processor are the mounted component's; a failed+ # delete of one of its descendants is reported here as well.+ path = readable_path(stable_path)+ label = f"{path} ({processor_name})" if processor_name else path+ message = "%s failed: %s: %s"+ args = (label, type(exc).__name__, exc)mode = display_mode()- if mode is not None:- # A progress display lists only the first few failures of- # the stats it draws, so this log is the complete record.- # On a terminal a traceback per failure would push the- # display off screen; in scrolling output it costs nothing.- path = readable_path(str(stable_path))- message = "%s failed: %s: %s"- args = (path, type(exc).__name__, exc)- if mode is DisplayMode.TERMINAL:- _failure_logger.error(message, *args)- _failure_logger.debug("traceback of %s", path, exc_info=exc)- else:- _failure_logger.error(message, *args, exc_info=exc)+ # A progress display lists only the first few failures of+ # the stats it draws, so this log is the complete record.+ # On a terminal a traceback per failure would push the+ # display off screen; in scrolling output it costs nothing.+ if mode is DisplayMode.TERMINAL:+ _failure_logger.error(message, *args)+ _failure_logger.debug("traceback of %s", path, exc_info=exc)+ elif mode is not None:+ _failure_logger.error(message, *args, exc_info=exc)else:- _logger.error("component build failed: %s", exc, exc_info=exc)+ _logger.error(message, *args, exc_info=exc)returnenv_name = self._env.name@@ -242,6 +245,7 @@ class ComponentContext:# raise β Rust's on_error catches it and the spawned task# returns Err, so `handle.ready()` raises. Handlers thus# control propagation: return (swallow) vs raise (propagate).+ self._core_processor_ctx.record_unhandled_failure()raise current_excreturn _rundiff --git a/python/cocoindex/_internal/core.pyi b/python/cocoindex/_internal/core.pyiindex aba86e31..daa6f2a8 100644--- a/python/cocoindex/_internal/core.pyi+++ b/python/cocoindex/_internal/core.pyi@@ -120,6 +120,7 @@ class ComponentProcessorContext:refresh_interval_secs: float | None = None,) -> tuple[ComponentProcessorContext, StatsGroupHandle]: ...def end_stats_group(self) -> None: ...+ def record_unhandled_failure(self) -> None: ...def use_state(self, key: StableKey, initial_value: Any) -> StoredValue: ...def update_user_state(self, key: StableKey, value: Any) -> StoredValue: ...@@ -310,6 +311,7 @@ def iter_target_states_by_name(# --- UpdateHandle ---class UpdateHandle:def stats_snapshot(self) -> tuple[int, bool, dict[str, dict[str, int]]]: ...+ def unhandled_failures(self) -> int: ...def changed(self) -> Coroutine[Any, Any, int]: ...def result(self) -> Coroutine[Any, Any, StoredValue]: ...def take_preview_actions(self) -> list[Any]: ...diff --git a/python/cocoindex/cli.py b/python/cocoindex/cli.pyindex fe123ac4..9022e0d4 100644--- a/python/cocoindex/cli.py+++ b/python/cocoindex/cli.py@@ -15,7 +15,7 @@ from .user_app_loader import load_user_app, Error as UserAppLoaderErrorimport asyncioimport cocoindex as coco-from cocoindex._internal.app import App+from cocoindex._internal.app import App, UpdateHandlefrom cocoindex._internal import banner as _bannerfrom cocoindex._internal.update_stats import DisplayMode, display_modefrom cocoindex._internal import core as _core@@ -1099,6 +1099,20 @@ async def _stop_all_environments() -> None:await env.stop()+def _fail_on_unhandled_failures(handle: UpdateHandle[Any], verb: str) -> None:+ """Exit 1 when a component failure nobody took ownership of happened.++ A failure is unhandled when no exception handler was registered for it,+ or every handler in the chain re-raised. `--quiet` keeps the message:+ Click prints it to stderr.+ """+ failures = handle._unhandled_failures()+ if failures:+ raise click.ClickException(+ f"{verb} finished with {failures} unhandled component failure(s)."+ )++@cli.command()@click.argument("app_target", type=str)@click.option(@@ -1177,6 +1191,9 @@ def update("""Run an app in catch-up mode. With --live, run in live mode.+ Exits with status 1 if a component failure goes unhandled: no exception+ handler is registered for it, or every handler re-raised. Not with --live.+`APP_TARGET`: `path/to/app.py`, `module`, `path/to/app.py:app_name`, or `module:app_name`."""if preview and reset:@@ -1215,7 +1232,14 @@ def update(for action in actions:click.echo(f" {action!r}")else:- _say_done("ok", "Nothing to change", took)+ # A preview with failed components is missing their+ # changes, so "Nothing to change" would overstate it:+ # no green mark for an incomplete preview.+ mark: Literal["ok", "info"] = (+ "info" if handle._unhandled_failures() else "ok"+ )+ _say_done(mark, "Nothing to change", took)+ _fail_on_unhandled_failures(handle, "Preview")return# --reset: drop existing state first (equivalent to `cocoindex drop ...`)@@ -1241,6 +1265,11 @@ def update(await show_progress(handle)else:await handle.result()+ # Surface unhandled component failures in the exit status so+ # schedulers (cron, CI) can detect a failed run. Live mode is+ # excluded: cumulative failures do not describe current health.+ if not live:+ _fail_on_unhandled_failures(handle, "Update")finally:await _stop_all_environments()diff --git a/python/tests/cli/catching_parent_app.py b/python/tests/cli/catching_parent_app.pynew file mode 100644index 00000000..ada04edd--- /dev/null+++ b/python/tests/cli/catching_parent_app.py@@ -0,0 +1,28 @@+"""Test module with an app whose parent catches a use_mount failure."""++from __future__ import annotations++import pathlib++import cocoindex as coco++_HERE = pathlib.Path(__file__).resolve().parent+DB_PATH = _HERE / "cocoindex_catching_parent.db"++env = coco.Environment(coco.Settings.from_env(db_path=DB_PATH))+++async def boom(i: int) -> None:+ raise ValueError(f"item {i} is poison")+++async def app_main() -> None:+ try:+ await coco.use_mount(coco.component_subpath("boom"), boom, 0)+ except ValueError:+ pass+++app = coco.App(coco.AppConfig(name="CatchingParentApp", environment=env), app_main)diff --git a/python/tests/cli/failing_app.py b/python/tests/cli/failing_app.pynew file mode 100644index 00000000..3b7a6452--- /dev/null+++ b/python/tests/cli/failing_app.py@@ -0,0 +1,26 @@+"""Test module with an app whose background components always fail."""++from __future__ import annotations++import pathlib++import cocoindex as coco++_HERE = pathlib.Path(__file__).resolve().parent+DB_PATH = _HERE / "cocoindex_failing.db"++env = coco.Environment(coco.Settings.from_env(db_path=DB_PATH))+++async def boom(i: int) -> None:+ raise ValueError(f"item {i} is poison")+++async def app_main() -> None:+ for i in range(3):+ await coco.mount(coco.component_subpath("boom", str(i)), boom, i)+++app = coco.App(coco.AppConfig(name="FailingApp", environment=env), app_main)diff --git a/python/tests/cli/failing_group_app.py b/python/tests/cli/failing_group_app.pynew file mode 100644index 00000000..4c184c52--- /dev/null+++ b/python/tests/cli/failing_group_app.py@@ -0,0 +1,27 @@+"""Test module with an app whose background components fail inside a stats group."""++from __future__ import annotations++import pathlib++import cocoindex as coco++_HERE = pathlib.Path(__file__).resolve().parent+DB_PATH = _HERE / "cocoindex_failing_group.db"++env = coco.Environment(coco.Settings.from_env(db_path=DB_PATH))+++async def boom(i: int) -> None:+ raise ValueError(f"item {i} is poison")+++async def app_main() -> None:+ with coco.stats_group("grp"):+ for i in range(3):+ await coco.mount(coco.component_subpath("boom", str(i)), boom, i)+++app = coco.App(coco.AppConfig(name="FailingGroupApp", environment=env), app_main)diff --git a/python/tests/cli/handler_app.py b/python/tests/cli/handler_app.pynew file mode 100644index 00000000..6fd7e22a--- /dev/null+++ b/python/tests/cli/handler_app.py@@ -0,0 +1,47 @@+"""Test module with apps whose failing components run under an exception handler."""++from __future__ import annotations++import pathlib++import cocoindex as coco++_HERE = pathlib.Path(__file__).resolve().parent+DB_PATH = _HERE / "cocoindex_handler.db"++env = coco.Environment(coco.Settings.from_env(db_path=DB_PATH))+++async def boom(i: int) -> None:+ raise ValueError(f"item {i} is poison")+++def _swallow(exc: BaseException, ctx: object) -> None:+ """Return normally: take ownership of the failure."""+++def _reraise(exc: BaseException, ctx: object) -> None:+ raise exc+++async def swallowing_main() -> None:+ async with coco.exception_handler(_swallow):+ for i in range(3):+ await coco.mount(coco.component_subpath("boom", str(i)), boom, i)+++async def reraising_main() -> None:+ async with coco.exception_handler(_reraise):+ for i in range(3):+ await coco.mount(coco.component_subpath("boom", str(i)), boom, i)+++swallowing_app = coco.App(+ coco.AppConfig(name="SwallowingHandlerApp", environment=env), swallowing_main+)+reraising_app = coco.App(+ coco.AppConfig(name="ReraisingHandlerApp", environment=env), reraising_main+)diff --git a/python/tests/cli/test_cli.py b/python/tests/cli/test_cli.pyindex fdba66cf..021f4715 100644--- a/python/tests/cli/test_cli.py+++ b/python/tests/cli/test_cli.py@@ -1158,3 +1158,62 @@ class TestShowTargetStatesTypedKeys:)self._assert_typed_keys_rendered(result.stdout)+++# =============================================================================+# Update exit status: failures nobody handled+# =============================================================================+++class TestUpdateExitStatus:+ """The exit status of `update` counts only unhandled component failures:+ no exception handler was registered, or every handler re-raised."""++ def test_unhandled_failures_exit_1(self) -> None:+ """Background components failing with no handler exit 1."""+ result = run_cli("update", "./failing_app.py", check=False)++ assert result.returncode == 1+ assert "unhandled component failure(s)" in result.stderr++ def test_failures_inside_stats_group_exit_1(self) -> None:+ """A failure inside a stats group lands on the run's count too."""+ result = run_cli("update", "./failing_group_app.py", check=False)++ assert result.returncode == 1+ assert "unhandled component failure(s)" in result.stderr++ def test_swallowing_handler_exits_0(self) -> None:+ """A handler that returns normally has taken ownership: exit 0."""+ run_cli("update", "./handler_app.py:SwallowingHandlerApp")++ def test_reraising_handler_exits_1(self) -> None:+ """A handler that re-raises leaves the failure unhandled: exit 1."""+ result = run_cli("update", "./handler_app.py:ReraisingHandlerApp", check=False)++ assert result.returncode == 1+ assert "unhandled component failure(s)" in result.stderr++ def test_reraising_handler_quiet_stderr_line_only(self) -> None:+ """#2429: with -q, the stderr line is the only output."""+ result = run_cli(+ "update", "-q", "./handler_app.py:ReraisingHandlerApp", check=False+ )++ assert result.returncode == 1+ assert result.stdout == ""+ assert "Update finished with 3 unhandled component failure(s)." in result.stderr++ def test_catching_parent_exits_0(self) -> None:+ """A parent that catches a use_mount failure owns it: exit 0."""+ run_cli("update", "./catching_parent_app.py")++ def test_preview_with_failures_exit_1(self) -> None:+ """A preview with failed components is missing their changes: exit 1,+ and "Nothing to change" doesn't get the green mark."""+ result = run_cli("update", "--preview", "./failing_app.py", check=False)++ assert result.returncode == 1+ assert "Nothing to change" in result.stdout+ assert "β Nothing to change" not in result.stdout+ assert "unhandled component failure(s)" in result.stderrdiff --git a/python/tests/cli/test_terminal_output.py b/python/tests/cli/test_terminal_output.pyindex a315992e..5a58a77f 100644--- a/python/tests/cli/test_terminal_output.py+++ b/python/tests/cli/test_terminal_output.py@@ -21,7 +21,9 @@ pytestmark = pytest.mark.skipif(_APP = Path(__file__).resolve().parent / "terminal_output_app.py"-def _run(args: list[str], tmp_path: Path, **extra_env: str) -> bytes:+def _run(+ args: list[str], tmp_path: Path, *, expected_exit: int = 0, **extra_env: str+) -> bytes:"""Run `args` with a pseudo-terminal as stdout and stderr, and return whatthe terminal received."""env = {@@ -57,7 +59,7 @@ def _run(args: list[str], tmp_path: Path, **extra_env: str) -> bytes:breakoutput += chunkos.close(master)- assert process.wait() == 0, output.decode(errors="replace")+ assert process.wait() == expected_exit, output.decode(errors="replace")return bytes(output)@@ -84,6 +86,7 @@ def test_debug_logs_keep_their_time_and_logger_name(tmp_path: Path) -> None:output = _run(["cocoindex", "update", f"{_APP}:Failures"],tmp_path,+ expected_exit=1,COCOINDEX_LOG_LEVEL="DEBUG",)assert b" ERROR cocoindex: " in outputdiff --git a/rust/core/src/engine/component.rs b/rust/core/src/engine/component.rsindex e8bb6cc1..10436289 100644--- a/rust/core/src/engine/component.rs+++ b/rust/core/src/engine/component.rs@@ -1255,6 +1255,7 @@ impl<Prof: EngineProfile> Component<Prof> {}} else {error!("component build failed at {}:\n{err:?}", self.stable_path());+ context.processing_stats().record_unhandled_failure();Ok(())};(ComponentRunOutcome::exception(), task_result)@@ -1328,6 +1329,7 @@ impl<Prof: EngineProfile> Component<Prof> {"component delete failed at {}:\n{err:?}",self.stable_path());+ context.processing_stats().record_unhandled_failure();Ok(())};(ComponentRunOutcome::exception(), task_result)diff --git a/rust/core/src/engine/stats.rs b/rust/core/src/engine/stats.rsindex 4c6f8006..29c1e738 100644--- a/rust/core/src/engine/stats.rs+++ b/rust/core/src/engine/stats.rs@@ -1,4 +1,5 @@use crate::prelude::*;+use std::sync::atomic::{AtomicU64, Ordering};use tokio::sync::watch;/// Sentinel version sent on the watch channel when processing is fully terminated@@ -82,6 +83,12 @@ pub struct VersionedProcessingStats {/// What the stats groups under this scope count, at any depth. Their rows/// stay out of this scope's report, but its final status covers them.pub in_groups: ProcessingStatsGroup,+ /// Failures nobody took ownership of: no exception handler was registered,+ /// or every handler re-raised. Unlike `num_errors`, which the engine bumps+ /// for every failed component, this is what the exit status of+ /// `cocoindex update` counts. The count lives on a counter shared by the+ /// whole chain, so every scope's snapshot reports the run's total.+ pub unhandled_failures: u64,}/// Thread-safe container for processing stats with version tracking and change notification.@@ -96,6 +103,9 @@ pub struct ProcessingStats {terminated_rx: watch::Receiver<bool>,/// The enclosing stats, for a stats group.parent: Option<Arc<ProcessingStats>>,+ /// Unhandled failures of the whole run, shared by every stats in the+ /// chain: a group's failure lands on the same counter the root reads.+ unhandled_failures: Arc<AtomicU64>,}impl Default for ProcessingStats {@@ -115,13 +125,16 @@ impl ProcessingStats {terminated_tx,terminated_rx,parent: None,+ unhandled_failures: Arc::new(AtomicU64::new(0)),}}- /// The stats of a group opened under `parent`.+ /// The stats of a group opened under `parent`, sharing the parent's+ /// unhandled-failure counter.pub(crate) fn new_in(parent: &ProcessingStats) -> Self {Self {parent: Some(Arc::new(parent.clone())),+ unhandled_failures: parent.unhandled_failures.clone(),..Self::new()}}@@ -160,9 +173,20 @@ impl ProcessingStats {}}+ /// Count a failure that no exception handler took ownership of: either no+ /// handler was registered, or every handler in the chain re-raised. The+ /// counter is shared by the whole chain, so a failure inside a stats group+ /// lands on the run's count without walking to the root. Does not bump the+ /// version: the CLI reads it once, after the update finished.+ pub fn record_unhandled_failure(&self) {+ self.unhandled_failures.fetch_add(1, Ordering::Relaxed);+ }+/// Returns an atomic snapshot of (version, stats).pub fn snapshot(&self) -> VersionedProcessingStats {- self.inner.lock().unwrap().clone()+ let mut snapshot = self.inner.lock().unwrap().clone();+ snapshot.unhandled_failures = self.unhandled_failures.load(Ordering::Relaxed);+ snapshot}/// Signal that the root processing component is ready (initial processing caught up).@@ -236,6 +260,28 @@ mod tests {assert_eq!(root.snapshot().version, 0, "its own rows did not change");}+ #[test]+ fn test_unhandled_failure_count_is_shared_by_the_chain() {+ let root = ProcessingStats::new();+ let group = ProcessingStats::new_in(&root);++ group.record_unhandled_failure();+ group.record_unhandled_failure();+ root.record_unhandled_failure();++ assert_eq!(root.snapshot().unhandled_failures, 3);+ assert_eq!(+ group.snapshot().unhandled_failures,+ 3,+ "every scope reports the run's total"+ );+ assert_eq!(+ root.snapshot().version,+ 0,+ "counting a failure does not bump the version"+ );+ }+#[test]fn test_version_increments_on_update() {let stats = ProcessingStats::new();diff --git a/rust/py/src/app.rs b/rust/py/src/app.rsindex 1526087b..168f49ba 100644--- a/rust/py/src/app.rs+++ b/rust/py/src/app.rs@@ -83,6 +83,14 @@ impl PyUpdateHandle {Ok((snapshot.version, snapshot.ready, dict))}+ /// Number of component failures nobody took ownership of: no exception+ /// handler was registered for them, or every handler re-raised. Unlike+ /// the per-processor error counts, this covers stats groups (the counter+ /// is shared by the whole chain) and excludes handled failures.+ pub fn unhandled_failures(&self) -> u64 {+ self.stats.snapshot().unhandled_failures+ }+/// Awaits a version change notification. Returns the new version./// Returns u64::MAX when the task terminates.///diff --git a/rust/py/src/context.rs b/rust/py/src/context.rsindex ccbc1e36..09724ae0 100644--- a/rust/py/src/context.rs+++ b/rust/py/src/context.rs@@ -64,6 +64,14 @@ impl PyComponentProcessorContext {self.0.end_stats_group();}+ /// Count a component failure that no exception handler took ownership of+ /// (no handler registered, or every handler re-raised). Recorded on the+ /// root of the stats chain, so failures inside a stats group are covered+ /// too; drives the exit status of `cocoindex update`.+ fn record_unhandled_failure(&self) {+ self.0.processing_stats().record_unhandled_failure();+ }+/// Collect eager initial memo states for the change-detection context fingerprints/// observed so far on this component (from `logic_deps`). Returns a/// `dict[Fingerprint, list[Any]]` directly β fingerprints with no