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(py): Ctrl+C stops update_blocking and drop_blocking (#2840)
Jiangzhoub0b976e72eda
diff --git a/docs/src/content/docs/programming_guide/live_mode.mdx b/docs/src/content/docs/programming_guide/live_mode.mdxindex e7906e6d..de505df2 100644--- a/docs/src/content/docs/programming_guide/live_mode.mdx+++ b/docs/src/content/docs/programming_guide/live_mode.mdx@@ -82,6 +82,8 @@ cocoindex update -L<Lang only="python">+Ctrl+C stops a live update run by `cocoindex update -L` or `app.update_blocking(live=True)`; the latter then raises `KeyboardInterrupt`.+The `live` flag propagates top-down through the component tree β both `coco.mount()` and `coco.use_mount()` inherit `live` from the parent, so children are live when the app is live.Without `live=True` on the app, the app runs in catch-up mode β everything completes after the initial scan, even if a source supports live watching.diff --git a/python/cocoindex/_internal/app.py b/python/cocoindex/_internal/app.pyindex 5b864841..87da1d66 100644--- a/python/cocoindex/_internal/app.py+++ b/python/cocoindex/_internal/app.py@@ -380,6 +380,8 @@ class App(Generic[P, R]):"""Update the app synchronously (run the app once to process all pending changes).+ Ctrl+C stops the update and raises ``KeyboardInterrupt``.+Args:report_to_stdout: If truthy, periodically report processing stats tostdout. Pass a ``timedelta`` to set the refresh interval; ``True``@@ -451,6 +453,10 @@ class App(Generic[P, R]):writing to them and leaves their contents as-is. See the connector's docs.- Clear the app's internal state database+ A drop is not stopped partway: Ctrl+C raises ``KeyboardInterrupt`` once it+ finishes. A second Ctrl+C raises at once, and the drop goes on in the+ background.+Args:report_to_stdout: If truthy, periodically report processing stats tostdout. Pass a ``timedelta`` to set the refresh interval; ``True``diff --git a/python/tests/core/test_blocking_update_interrupt.py b/python/tests/core/test_blocking_update_interrupt.pynew file mode 100644index 00000000..edc7e9e0--- /dev/null+++ b/python/tests/core/test_blocking_update_interrupt.py@@ -0,0 +1,239 @@+"""Ctrl+C while a script is blocked in `App.update_blocking()` or+`App.drop_blocking()`.++While the main thread waits on the engine, it runs no Python code: CPython's+SIGINT handler only records the signal, and the `KeyboardInterrupt` it raises+waits for the main thread to run Python again. A live update never returns, so+the blocking wait has to run the pending signal handlers itself, stop the+operation, and raise what the handler raised.++The tests send SIGINT to a fresh interpreter, since what they check is how the+process ends.+"""++from __future__ import annotations++import asyncio+import contextlib+import pathlib+import queue+import signal+import subprocess+import sys+import threading+from collections.abc import Collection, Iterator+from typing import IO, Any++import pytest++import cocoindex as coco+from cocoindex.connectors import localfs++from tests import common++pytestmark = [+ pytest.mark.skipif(+ sys.platform == "win32",+ reason="sends SIGINT to a child process; Windows has CTRL_C_EVENT for a "+ "console process group instead",+ ),+ # Starting a fresh interpreter and its first update takes a few seconds.+ pytest.mark.timeout(120),+]++_PYTHON_DIR = pathlib.Path(__file__).resolve().parents[2]+_PROCESSED = "processed "+_DELETING = "deleting"+_LINE_TIMEOUT_SECS = 30+_EXIT_TIMEOUT_SECS = 10++# Runs one of the `_child_*` functions below. The child raises+# `KeyboardInterrupt` on SIGINT even if it inherited SIGINT ignored, as a+# process a shell starts in the background does.+_CHILD = """\+import signal, sys+signal.signal(signal.SIGINT, signal.default_int_handler)+from tests.core import test_blocking_update_interrupt as tests+getattr(tests, sys.argv[1])(*sys.argv[2:])+"""+++class _ChildOutput:+ """The child's output lines, read on a thread as they come, so the child+ never blocks on a full pipe."""++ def __init__(self, stream: IO[str]) -> None:+ self.lines: list[str] = []+ self._pending: queue.Queue[str | None] = queue.Queue()+ threading.Thread(target=self._read, args=(stream,), daemon=True).start()++ def _read(self, stream: IO[str]) -> None:+ for line in stream:+ self._pending.put(line)+ self._pending.put(None)++ def wait_for(self, expected: str) -> None:+ while True:+ try:+ line = self._pending.get(timeout=_LINE_TIMEOUT_SECS)+ except queue.Empty:+ raise AssertionError(+ f"no {expected!r} line from the child:\n{self.text()}"+ ) from None+ if line is None:+ raise AssertionError(+ f"the child ended before printing {expected!r}:\n{self.text()}"+ )+ self.lines.append(line)+ if line.rstrip("\n") == expected:+ return++ def read_to_end(self) -> str:+ while (line := self._pending.get(timeout=_LINE_TIMEOUT_SECS)) is not None:+ self.lines.append(line)+ return self.text()++ def text(self) -> str:+ return "".join(self.lines)+++def _child(+ child_fn: str, *args: str+) -> Iterator[tuple[subprocess.Popen[str], _ChildOutput]]:+ child = subprocess.Popen(+ [sys.executable, "-c", _CHILD, child_fn, *args],+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ text=True,+ cwd=_PYTHON_DIR,+ )+ try:+ assert child.stdout is not None+ yield child, _ChildOutput(child.stdout)+ finally:+ child.kill()+ child.wait()+++def _wait_for_exit(child: subprocess.Popen[str], output: _ChildOutput) -> str:+ try:+ child.wait(timeout=_EXIT_TIMEOUT_SECS)+ except subprocess.TimeoutExpired:+ raise AssertionError(+ f"the child kept running after SIGINT:\n{output.text()}"+ ) from None+ return output.read_to_end()+++def _assert_ended_by_keyboard_interrupt(+ child: subprocess.Popen[str], text: str, call: str+) -> None:+ assert f"{call} raised KeyboardInterrupt" in text, text+ # Uncaught, the `KeyboardInterrupt` ends the process the way SIGINT does,+ # and nothing is left half-stopped to complain at exit.+ assert child.returncode == -signal.SIGINT, text+ assert "Exception ignored" not in text, text+ assert "Task was destroyed but it is pending" not in text, text+++def test_ctrl_c_stops_a_blocking_live_update(tmp_path: pathlib.Path) -> None:+ source_dir = tmp_path / "source"+ source_dir.mkdir()+ (source_dir / "a.txt").write_text("a")++ with _child("_child_live_update", str(source_dir)) as (child, output):+ output.wait_for(_PROCESSED + "a.txt")+ # A file processed after the initial pass shows that the update has+ # reached its live phase, the one that never returns.+ (source_dir / "b.txt").write_text("b")+ output.wait_for(_PROCESSED + "b.txt")++ child.send_signal(signal.SIGINT)+ text = _wait_for_exit(child, output)++ _assert_ended_by_keyboard_interrupt(child, text, "update_blocking")+++def test_a_second_ctrl_c_stops_waiting_for_a_drop() -> None:+ """A drop has nothing to cancel: the first Ctrl+C waits for it to finish,+ and a second one stops waiting."""+ with _child("_child_drop") as (child, output):+ output.wait_for(_DELETING)++ child.send_signal(signal.SIGINT)+ with pytest.raises(subprocess.TimeoutExpired):+ child.wait(timeout=1)++ child.send_signal(signal.SIGINT)+ text = _wait_for_exit(child, output)++ _assert_ended_by_keyboard_interrupt(child, text, "drop_blocking")+++def _child_live_update(source_dir: str) -> None:+ """Block in a live update until interrupted."""+ env = common.create_test_env(__file__)++ @coco.fn+ async def process_file(file: localfs.File) -> None:+ print(_PROCESSED + file.file_path.path.name, flush=True)++ @coco.fn+ async def app_main() -> None:+ files = localfs.walk_dir(pathlib.Path(source_dir), live=True)+ await coco.mount_each(process_file, files.items())++ app = coco.App(coco.AppConfig(name="live_update", environment=env), app_main)+ try:+ app.update_blocking(live=True)+ except KeyboardInterrupt:+ print("update_blocking raised KeyboardInterrupt", flush=True)+ raise+++class _DeleteNeverEnds(coco.TargetHandler[Any, Any, None]):+ """Applies upserts, and blocks forever on a delete."""++ def __init__(self) -> None:+ self._sink = coco.TargetActionSink.from_async_fn(self._apply)++ async def _apply(+ self, context_provider: coco.ContextProvider, actions: Collection[Any], /+ ) -> None:+ if any(coco.is_non_existence(action) for action in actions):+ print(_DELETING, flush=True)+ await asyncio.Event().wait()++ def reconcile(+ self,+ key: coco.StableKey,+ desired_state: Any | coco.NonExistenceType,+ prev_possible_records: Collection[Any],+ prev_may_be_missing: bool,+ ) -> coco.TargetReconcileOutput[Any, Any] | None:+ if coco.is_non_existence(desired_state) and not prev_possible_records:+ return None+ return coco.TargetReconcileOutput(+ action=desired_state, sink=self._sink, tracking_record=desired_state+ )+++def _child_drop() -> None:+ """Block in a drop that never ends until interrupted twice."""+ env = common.create_test_env(__file__)+ provider = coco.register_root_target_states_provider(+ "test_blocking_update_interrupt/delete_never_ends", _DeleteNeverEnds()+ )++ @coco.fn+ async def app_main() -> None:+ coco.declare_target_state(provider.target_state("key", "value"))++ app = coco.App(coco.AppConfig(name="drop", environment=env), app_main)+ app.update_blocking()+ try:+ app.drop_blocking()+ except KeyboardInterrupt:+ print("drop_blocking raised KeyboardInterrupt", flush=True)+ raisediff --git a/python/tests/core/test_update_handle.py b/python/tests/core/test_update_handle.pyindex 834d3930..da83a412 100644--- a/python/tests/core/test_update_handle.py+++ b/python/tests/core/test_update_handle.py@@ -1,4 +1,5 @@import asyncio+import threadingimport pytest@@ -147,3 +148,40 @@ async def test_show_progress_with_watch() -> None:assert len(snapshots) >= 1assert snapshots[-1].status == coco.UpdateStatus.READY+++async def test_show_progress_runs_after_a_cancelled_one() -> None:+ """A progress display dropped before it ends, its awaiter cancelled, lets+ the next one run."""+ running = threading.Event()++ async def _main_until_cancelled() -> None:+ running.set()+ await asyncio.Event().wait()++ blocked = coco.App(+ coco.AppConfig(name="test_show_progress_cancelled", environment=coco_env),+ _main_until_cancelled,+ )+ showing = asyncio.create_task(coco.show_progress(blocked.update()))+ for _ in range(1000):+ if running.is_set():+ break+ await asyncio.sleep(0.01)+ else:+ raise AssertionError("the update did not start")+ showing.cancel()+ with pytest.raises(asyncio.CancelledError):+ await showing++ try:+ app = coco.App(+ coco.AppConfig(name="test_show_progress_next", environment=coco_env),+ _trivial_fn,+ "next",+ )+ assert await coco.show_progress(app.update()) == "next"+ finally:+ # Stop the update whose display was cancelled: it runs on without it.+ await blocked.drop()diff --git a/rust/core/src/engine/progress_display.rs b/rust/core/src/engine/progress_display.rsindex cd3aa0d1..09369011 100644--- a/rust/core/src/engine/progress_display.rs+++ b/rust/core/src/engine/progress_display.rs@@ -20,9 +20,30 @@ const DEFAULT_TTY_REFRESH_INTERVAL: Duration = Duration::from_secs(1);/// e.g. a CI log): each block adds lines that stay, so print them rarely.const DEFAULT_PLAIN_REFRESH_INTERVAL: Duration = Duration::from_secs(10);-/// Global flag ensuring only one show_progress runs at a time.+/// Global flag ensuring only one show_progress runs at a time; held through+/// a [`ProgressActiveClaim`].static PROGRESS_ACTIVE: AtomicBool = AtomicBool::new(false);+/// A running `show_progress`'s hold on [`PROGRESS_ACTIVE`], released on drop:+/// a display dropped before it ends (its awaiter cancelled, or a blocking wait+/// given up on a second Ctrl+C) lets the next one run.+struct ProgressActiveClaim;++impl ProgressActiveClaim {+ fn acquire() -> Option<Self> {+ PROGRESS_ACTIVE+ .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)+ .ok()+ .map(|_| Self)+ }+}++impl Drop for ProgressActiveClaim {+ fn drop(&mut self) {+ PROGRESS_ACTIVE.store(false, Ordering::SeqCst);+ }+}+/// A stats group drawn as a section of the in-place region, while a root/// display runs on a terminal.#[cfg(unix)]@@ -929,8 +950,8 @@ fn write_to_fd(fd: i32, buf: &[u8]) {}/// Internal RAII guard for PTY fd cleanup.-/// Restores original fds, ends the stats groups' sections and clears the global-/// flag on drop, so a cancelled display leaves no region behind for later groups.+/// Restores original fds and ends the stats groups' sections on drop, so a+/// cancelled display leaves no region behind for later groups.#[cfg(unix)]struct PtyGuard {saved_stdout: i32,@@ -949,7 +970,6 @@ impl Drop for PtyGuard {if let Ok(mut groups) = GROUP_SECTIONS.lock() {*groups = None;}- PROGRESS_ACTIVE.store(false, Ordering::SeqCst);}}@@ -962,13 +982,8 @@ pub async fn show_progress<T: Send + 'static>(handle: AppOpHandle<T>,options: ProgressDisplayOptions,) -> Result<T> {- // Check exclusive access- if PROGRESS_ACTIVE- .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)- .is_err()- {- return Err(internal_error!("Another show_progress is already running"));- }+ let _claim = ProgressActiveClaim::acquire()+ .ok_or_else(|| internal_error!("Another show_progress is already running"))?;let live = handle.live;let start_time = Instant::now();@@ -1188,7 +1203,6 @@ async fn show_progress_plain<T: Send + 'static>(start_time: Instant,) -> Result<T> {render_plain(handle.stats(), None, live, &options, start_time).await;- PROGRESS_ACTIVE.store(false, Ordering::SeqCst);handle.result().await}diff --git a/rust/py/src/app.rs b/rust/py/src/app.rsindex 168f49ba..79e6f8cc 100644--- a/rust/py/src/app.rs+++ b/rust/py/src/app.rs@@ -14,7 +14,8 @@ use tokio::sync::watch;use crate::{component::PyComponentProcessor, deadline::PyDeadlineContext, environment::PyEnvironment,- stable_path::PyStablePath, target_state_codec::PyTargetAction, value::PyStoredValue,+ runtime::block_on_interruptibly, stable_path::PyStablePath, target_state_codec::PyTargetAction,+ value::PyStoredValue,};fn snapshot_to_py<'py>(@@ -334,8 +335,10 @@ impl PyApp {} else {None};- py.detach(|| {- get_runtime().block_on(async move {+ let app_to_stop = app.clone();+ block_on_interruptibly(+ py,+ async move {let (handle, preview_collector) = app.update(root_processor, options, host_ctx, preview_collector).context("failed to start app update")@@ -360,8 +363,11 @@ impl PyApp {let ret: PyStoredValue = handle.result().await.into_py_result()?;Python::attach(|py| Ok(Py::new(py, ret)?.into_any()))}- })- })+ },+ // Stop the app's operations: this update, and the live components+ // it mounted, which would otherwise run on.+ move || app_to_stop.app_ctx().cancellation_token().cancel(),+ )}pub fn drop_async(&self, host_ctx: Py<PyAny>) -> PyResult<PyDropHandle> {@@ -384,8 +390,9 @@ impl PyApp {) -> PyResult<()> {let app = self.0.clone();let host_ctx = Arc::new(host_ctx);- py.detach(|| {- get_runtime().block_on(async move {+ block_on_interruptibly(+ py,+ async move {let handle = app.drop_app(host_ctx).context("failed to start app drop")@@ -400,8 +407,11 @@ impl PyApp {} else {handle.result().await.into_py_result()}- })- })+ },+ // A drop has no cancellation to request: its deletes observe no+ // cancellation token. A Ctrl+C lets it finish before raising.+ || {},+ )}}diff --git a/rust/py/src/runtime.rs b/rust/py/src/runtime.rsindex 0e622552..dc4b47d2 100644--- a/rust/py/src/runtime.rs+++ b/rust/py/src/runtime.rs@@ -1,6 +1,8 @@use std::{hash::{Hash, Hasher},+ pin::Pin,sync::{Arc, OnceLock},+ time::Duration,};use crate::prelude::*;@@ -91,6 +93,59 @@ pub fn shutdown_tokio_runtime(py: Python<'_>) {py.detach(shutdown_runtime);}+/// How often [`block_on_interruptibly`] wakes to run Python's signal handlers.+const SIGNAL_CHECK_INTERVAL: Duration = Duration::from_millis(100);++/// Block on `work` on the engine runtime with the GIL released, as a blocking+/// entry point (`App.update_blocking`, `App.drop_blocking`) does, and stay+/// responsive to Ctrl+C while waiting.+///+/// CPython only records a signal when it arrives; its Python handler (the one+/// raising `KeyboardInterrupt` for SIGINT) runs once the main thread runs+/// Python code again, which a wait on work that never ends (a live update)+/// never does. So the wait wakes every [`SIGNAL_CHECK_INTERVAL`] to run the+/// pending handlers (`check_signals`, which does nothing off the main thread).+/// When a handler raises, `stop` is called to cancel the work, and the wait+/// goes on while the work winds down, so a progress display ends with its+/// final line; then the handler's exception is raised in place of the work's+/// result. A handler raising again before that (a second Ctrl+C) ends the wait+/// at once with its exception, leaving the work to finish on the runtime.+pub fn block_on_interruptibly<T: Send>(+ py: Python<'_>,+ work: impl Future<Output = PyResult<T>> + Send,+ stop: impl FnOnce(),+) -> PyResult<T> {+ let mut work = std::pin::pin!(work);+ let interrupt = loop {+ if let Some(result) = wait_a_while(py, work.as_mut()) {+ return result;+ }+ if let Err(err) = py.check_signals() {+ break err;+ }+ };+ stop();+ loop {+ if wait_a_while(py, work.as_mut()).is_some() {+ return Err(interrupt);+ }+ py.check_signals()?;+ }+}++/// Poll `work` with the GIL released for up to [`SIGNAL_CHECK_INTERVAL`];+/// `None` if it has not finished by then.+fn wait_a_while<F>(py: Python<'_>, work: Pin<&mut F>) -> Option<F::Output>+where+ F: Future + Send,+ F::Output: Send,+{+ py.detach(|| {+ get_runtime()+ .block_on(async { tokio::time::timeout(SIGNAL_CHECK_INTERVAL, work).await.ok() })+ })+}+/// Cancel the global cancellation token, causing all in-flight operations to/// exit promptly. Safe to call from signal handlers.#[pyfunction]