Skip to content

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

fix(progress): keep a record of every failure, and report it honestly (#2744)

Jiangzhoua0f3d69e7479
diff --git a/dev/plans/rust-cli.md b/dev/plans/rust-cli.md
index e137d883..bdb073c8 100644
--- a/dev/plans/rust-cli.md
+++ b/dev/plans/rust-cli.md
@@ -96,7 +96,10 @@ exits 1) and build and run an `init` scaffold.
**Framing.** One record per line on the child's stdout: ASCII record separator `U+001E`, then a
JSON object with an `event` tag, then `\n`. The child flushes after every record. Any stdout
text without the separator (or before it on the same line) is user output; the CLI forwards it
-verbatim. Stderr is inherited. Lines whose JSON does not parse are reported as malformed and
+verbatim. Stderr is read line by line and forwarded to the CLI's stderr, the stream the progress
+block draws on, so that the block can make room for it. The child's stderr is then a pipe, not a
+terminal: engine logs have no color under this CLI, libraries that check for a terminal behave as
+under a pipe, and output with no newline waits for one. Lines whose JSON does not parse are reported as malformed and
otherwise ignored.
**Invocation.** `<bin> __coco <ls|update|drop> --protocol 1 [--app NAME] [--live]
@@ -111,7 +114,7 @@ lifespan to one run per command; the CLI does the prompting.
| `hello` | `protocol`, `sdk` | all verbs, first | handshake; the CLI exits 2 on an unknown `protocol` |
| `apps` | `apps: [{name, persisted, registered}]`, `db_path` | `ls` | registered ∪ persisted apps |
| `start` | `app`, `db_path` | `update`, `drop` | the verb begins |
-| `progress` | `version`, `ready`, `by_component: {name: counters}` | `update` | one per engine change; counters are `num_execution_starts`, `num_unchanged`, `num_adds`, `num_deletes`, `num_reprocesses`, `num_errors` |
+| `progress` | `version`, `ready`, `by_component: {name: counters}`, `in_groups: counters` | `update` | one per engine change; counters are `num_execution_starts`, `num_unchanged`, `num_adds`, `num_deletes`, `num_reprocesses`, `num_errors`; `in_groups` (absent means zero) is what stats groups count, for the final status |
| `confirm` | `action: drop\|drop_db_only\|reset`, `app` | `drop`, `update --reset` with `--confirm` | asks for `yes`/`no` on stdin before the destructive step; `reset` only when there is state to drop |
| `preview` | `kind: create\|update\|delete`, `value` (JSON) | `update --preview` | one planned target action |
| `done` | `outcome: completed\|cancelled\|aborted\|nothing_to_drop`, `stats?` (`processed`, `skipped`, `written`, `deleted`, `elapsed: {secs, nanos}`) | terminal | `cancelled` after Ctrl-C; `aborted` after a `no` to `confirm`; `nothing_to_drop` when `drop` found no state; `stats` when an update completed |
diff --git a/docs/src/content/docs/advanced_topics/progress_monitoring.mdx b/docs/src/content/docs/advanced_topics/progress_monitoring.mdx
index 381d9e83..024de071 100644
--- a/docs/src/content/docs/advanced_topics/progress_monitoring.mdx
+++ b/docs/src/content/docs/advanced_topics/progress_monitoring.mdx
@@ -138,8 +138,9 @@ class UpdateSnapshot:
pub struct UpdateStats {
pub by_component: BTreeMap<String, ComponentStats>, // keyed by processor name
pub status: UpdateStatus, // Running | Ready
+ pub in_groups: ComponentStats, // what stats groups under this scope count
}
-// UpdateStats::total() sums every component; run_stats() derives the coarse RunStats.
+// UpdateStats::total() sums every component, not in_groups; run_stats() derives the coarse RunStats.
pub struct ComponentStats {
pub num_execution_starts: u64,
@@ -211,7 +212,9 @@ In Rust a group is a closure, not a block. `stats_group(title, f)` runs `f` with
</Fragment>
</LangTabs>
-With `report_to_stdout=True`, the group's progress is also printed to stdout, labeled by its title, alongside the main `report_to_stdout` display without disrupting it. Pass a `timedelta` instead of `True` to set the group's refresh interval.
+With `report_to_stdout=True`, the group's progress is also printed to stdout, labeled by its title, alongside the main `report_to_stdout` display without disrupting it. Pass a `timedelta` instead of `True` to set the group's refresh interval; while a terminal display runs, the group is a section of that display and redraws with it.
+
+A failure in a group, reported or not, still counts in the final status line of the main display: the run ends in `✗ Done in 2.0s · 3 failed`, even though the group's rows stay out of the main report.
The block yields a `StatsGroupHandle` with the same `stats()` and `watch()` as `UpdateHandle` (a group has no return value, so there's no `result()`):
diff --git a/python/cocoindex/_internal/component_ctx.py b/python/cocoindex/_internal/component_ctx.py
index 2b8ef754..78202386 100644
--- a/python/cocoindex/_internal/component_ctx.py
+++ b/python/cocoindex/_internal/component_ctx.py
@@ -193,19 +193,18 @@ class ComponentContext:
# the ExceptionContext metadata at all. Don't propagate.
mode = display_mode()
if mode is not None:
- # A progress display lists the failures. On a terminal it
- # shows each one, so the log keeps it at DEBUG; in
- # scrolling output one line each says when it happened.
- # The traceback is at DEBUG either way.
+ # 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 = (readable_path(str(stable_path)), type(exc).__name__, exc)
+ args = (path, type(exc).__name__, exc)
if mode is DisplayMode.TERMINAL:
- _failure_logger.debug(message, *args)
- else:
_failure_logger.error(message, *args)
- _failure_logger.debug(
- "traceback of the failure above", exc_info=exc
- )
+ _failure_logger.debug("traceback of %s", path, exc_info=exc)
+ else:
+ _failure_logger.error(message, *args, exc_info=exc)
else:
_logger.error("component build failed: %s", exc, exc_info=exc)
return
@@ -485,9 +484,11 @@ def stats_group(
Entering and exiting the block only bound *member registration* — exit is
non-blocking; the group becomes ready asynchronously once the body has
exited and all members are ready. With ``report_to_stdout`` truthy the group
- is also rendered as plain, title-prefixed log lines (interleaved above the
- progress region when a TTY display is active); pass a ``timedelta`` to set
- the refresh interval.
+ is also reported: as a section of the progress region while a terminal
+ display runs, otherwise as plain, title-prefixed blocks. Pass a ``timedelta``
+ to set the refresh interval of those blocks; a section redraws with its
+ region. Either way a failure in the group counts in the enclosing report's
+ final status.
This is a plain (synchronous) ``with`` block — like ``component_subpath`` —
even though the body typically ``await``s ``mount``/``use_mount``.
diff --git a/python/cocoindex/cli.py b/python/cocoindex/cli.py
index c5a24f25..560fcd8b 100644
--- a/python/cocoindex/cli.py
+++ b/python/cocoindex/cli.py
@@ -76,8 +76,9 @@ def _setup_logging() -> None:
)
# On a terminal, show records like the progress display shows its lines:
# a colored mark and the message. Logs that go to a file or a CI log keep
- # the timestamped format.
- if sys.stderr.isatty() and os.environ.get("TERM") != "dumb":
+ # the timestamped format, and so does DEBUG, which is for diagnosing: there
+ # the time and the logger's name matter.
+ if level != "DEBUG" and sys.stderr.isatty() and os.environ.get("TERM") != "dumb":
color = not os.environ.get("NO_COLOR")
for handler in logging.getLogger().handlers:
handler.setFormatter(_TerminalLogFormatter(color=color))
diff --git a/python/tests/cli/terminal_output_app.py b/python/tests/cli/terminal_output_app.py
new file mode 100644
index 00000000..973224e9
--- /dev/null
+++ b/python/tests/cli/terminal_output_app.py
@@ -0,0 +1,71 @@
+"""Apps for test_terminal_output.py, which runs them in a pseudo-terminal.
+
+Run as a script, this cancels a progress display, then opens a stats group that
+asks to report.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import os
+import pathlib
+
+import cocoindex as coco
+
+env = coco.Environment(
+ coco.Settings.from_env(db_path=pathlib.Path(os.environ["TERMINAL_OUTPUT_DB"]))
+)
+
+
+async def _item(i: int) -> None:
+ await asyncio.sleep(0)
+
+
+async def _fail(i: int) -> None:
+ raise ValueError(f"boom {i}")
+
+
+async def _slow_main() -> None:
+ await asyncio.sleep(0.5)
+
+
+async def _group_main() -> None:
+ with coco.stats_group("LaterGroup", report_to_stdout=True):
+ await coco.mount_each(_item, [("a", 1)])
+
+
+async def _items_main() -> None:
+ await coco.mount_each(_item, [("a", 1)])
+
+
+async def _failures_main() -> None:
+ await coco.mount_each(_fail, [("a", 1)])
+
+
+_items_app = coco.App(coco.AppConfig(name="Items", environment=env), _items_main)
+_failures_app = coco.App(
+ coco.AppConfig(name="Failures", environment=env), _failures_main
+)
+_slow_app = coco.App(coco.AppConfig(name="Slow", environment=env), _slow_main)
+_group_app = coco.App(coco.AppConfig(name="Group", environment=env), _group_main)
+
+
+async def _cancelled_display_then_group() -> None:
+ handle = _slow_app.update()
+ with contextlib.suppress(asyncio.TimeoutError):
+ await asyncio.wait_for(coco.show_progress(handle), timeout=0.1)
+ await asyncio.sleep(1)
+ await _group_app.update()
+ # The group's detached reporter prints its final block.
+ await asyncio.sleep(0.5)
+
+
+if __name__ == "__main__":
+ asyncio.run(_cancelled_display_then_group())
diff --git a/python/tests/cli/test_terminal_output.py b/python/tests/cli/test_terminal_output.py
new file mode 100644
index 00000000..a315992e
--- /dev/null
+++ b/python/tests/cli/test_terminal_output.py
@@ -0,0 +1,90 @@
+"""What a command prints on a real terminal, run in a pseudo-terminal: the code
+paths that check for one do not run under a pipe."""
+
+from __future__ import annotations
+
+import os
+import select
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+if sys.platform != "win32":
+ import pty
+
+pytestmark = pytest.mark.skipif(
+ sys.platform == "win32", reason="pseudo-terminals are Unix-only"
+)
+
+_APP = Path(__file__).resolve().parent / "terminal_output_app.py"
+
+
+def _run(args: list[str], tmp_path: Path, **extra_env: str) -> bytes:
+ """Run `args` with a pseudo-terminal as stdout and stderr, and return what
+ the terminal received."""
+ env = {
+ **os.environ,
+ "TERMINAL_OUTPUT_DB": str(tmp_path / "db"),
+ "TERM": "xterm-256color",
+ **extra_env,
+ }
+ master, slave = pty.openpty()
+ with subprocess.Popen(
+ args,
+ cwd=tmp_path,
+ env=env,
+ stdin=subprocess.DEVNULL,
+ stdout=slave,
+ stderr=slave,
+ ) as process:
+ os.close(slave)
+ output = bytearray()
+ while True:
+ # Poll: a helper that inherited the terminal can keep it open after
+ # the process exits, so end of file may never come.
+ exited = process.poll() is not None
+ if not select.select([master], [], [], 0.1)[0]:
+ if exited:
+ break
+ continue
+ try:
+ chunk = os.read(master, 65536)
+ except OSError: # EIO: every writer closed the terminal.
+ break
+ if not chunk:
+ break
+ output += chunk
+ os.close(master)
+ assert process.wait() == 0, output.decode(errors="replace")
+ return bytes(output)
+
+
+def test_a_cancelled_display_leaves_no_region_for_later_groups(tmp_path: Path) -> None:
+ output = _run([sys.executable, str(_APP)], tmp_path, NO_COLOR="1")
+ assert "✓ LaterGroup · Done in".encode() in output
+
+
+def test_no_color_also_covers_engine_logs(tmp_path: Path) -> None:
+ target = f"{_APP}:Items"
+ _run(["cocoindex", "update", target], tmp_path)
+ output = _run(
+ ["cocoindex", "drop", target, "-f"],
+ tmp_path,
+ NO_COLOR="1",
+ RUST_LOG="cocoindex_core=debug",
+ )
+ logs = [line for line in output.splitlines() if b" DEBUG " in line]
+ assert logs, output
+ assert not any(b"\x1b[" in line for line in logs), logs
+
+
+def test_debug_logs_keep_their_time_and_logger_name(tmp_path: Path) -> None:
+ output = _run(
+ ["cocoindex", "update", f"{_APP}:Failures"],
+ tmp_path,
+ COCOINDEX_LOG_LEVEL="DEBUG",
+ )
+ assert b" ERROR cocoindex: " in output
+ assert b" DEBUG cocoindex: traceback of " in output
diff --git a/python/tests/core/test_failure_log.py b/python/tests/core/test_failure_log.py
new file mode 100644
index 00000000..5b93cce0
--- /dev/null
+++ b/python/tests/core/test_failure_log.py
@@ -0,0 +1,90 @@
+"""How a component failure with no exception handler reaches the log while a
+progress display runs. The log is the complete record: a display lists only the
+first few failures of the stats it draws."""
+
+from __future__ import annotations
+
+import logging
+import sys
+
+import pytest
+
+import cocoindex as coco
+from tests.common import create_test_env
+
+coco_env = create_test_env(__file__)
+
+# More than the engine records for the display (`MAX_RECORDED_FAILURES`).
+_FAILURES = 8
+
+
+async def _fail(i: int) -> None:
+ raise ValueError(f"boom {i}")
+
+
+async def _main_failures() -> None:
+ await coco.mount_each(_fail, [(f"k{i}", i) for i in range(_FAILURES)])
+
+
+async def _main_failure_in_group() -> None:
+ with coco.stats_group("Docs"):
+ await coco.mount_each(_fail, [("k0", 0)])
+
+
+def _failure_records(caplog: pytest.LogCaptureFixture) -> list[logging.LogRecord]:
+ return [
+ r
+ for r in caplog.records
+ if r.name == "cocoindex" and r.levelno == logging.ERROR
+ ]
+
+
+def test_scrolling_output_logs_each_failure_with_its_traceback(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ app = coco.App(
+ coco.AppConfig(name="test_failure_log_plain", environment=coco_env),
+ _main_failures,
+ )
+ with caplog.at_level(logging.DEBUG, logger="cocoindex"):
+ app.update_blocking(report_to_stdout=True)
+ records = _failure_records(caplog)
+ assert len(records) == _FAILURES
+ assert all(r.exc_info for r in records)
+ assert any("ValueError: boom 7" in r.getMessage() for r in records)
+
+
+def test_terminal_logs_each_failure_past_what_the_display_lists(
+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
+ app = coco.App(
+ coco.AppConfig(name="test_failure_log_terminal", environment=coco_env),
+ _main_failures,
+ )
+ with caplog.at_level(logging.DEBUG, logger="cocoindex"):
+ app.update_blocking(report_to_stdout=True)
+ records = _failure_records(caplog)
+ assert len(records) == _FAILURES
+ # A traceback per failure would push the display off screen: it is at DEBUG.
+ assert not any(r.exc_info for r in records)
+ tracebacks = [
+ r for r in caplog.records if r.levelno == logging.DEBUG and r.exc_info
+ ]
+ assert len(tracebacks) == _FAILURES
+
+
+def test_terminal_logs_a_failure_in_a_group_the_display_does_not_draw(
+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
+ app = coco.App(
+ coco.AppConfig(name="test_failure_log_group", environment=coco_env),
+ _main_failure_in_group,
+ )
+ with caplog.at_level(logging.DEBUG, logger="cocoindex"):
+ app.update_blocking(report_to_stdout=True)
+ assert len(_failure_records(caplog)) == 1
diff --git a/python/tests/core/test_stats_group.py b/python/tests/core/test_stats_group.py
index f0ffaf35..9fcb47f4 100644
--- a/python/tests/core/test_stats_group.py
+++ b/python/tests/core/test_stats_group.py
@@ -312,6 +312,44 @@ async def test_stats_group_report_to_stdout_plain(
assert "✓ Indexing · Done in" in out
+async def test_a_group_that_succeeds_keeps_the_final_status_green(
+ capfd: pytest.CaptureFixture[str],
+) -> None:
+ _reset()
+ app = coco.App(
+ coco.AppConfig(name="test_sg_final_status_green", environment=coco_env),
+ _main_report,
+ )
+ await coco.show_progress(app.update())
+ assert "✓ Done in" in capfd.readouterr().out
+
+
+async def _fail_in_group() -> None:
+ raise ValueError("boom")
+
+
+async def _main_group_failure() -> None:
+ with coco.stats_group("Indexing"):
+ await coco.mount(coco.component_subpath("m"), _fail_in_group)
+
+
+async def test_failure_in_a_group_fails_the_final_status(
+ capfd: pytest.CaptureFixture[str],
+) -> None:
+ app = coco.App(
+ coco.AppConfig(name="test_sg_final_status", environment=coco_env),
+ _main_group_failure,
+ )
+ await coco.show_progress(app.update())
+ out = capfd.readouterr().out
+ assert "✗ Done in" in out
+ assert "1 failed" in out
+
+
# --- 11. live member: group readies + splits out, no hang ---
diff --git a/rust/cli/src/child.rs b/rust/cli/src/child.rs
index ac91654e..6a5068ad 100644
--- a/rust/cli/src/child.rs
+++ b/rust/cli/src/child.rs
@@ -3,16 +3,25 @@
use std::io::Write as _;
use std::path::Path;
use std::process::{ExitStatus, Stdio};
+use std::time::Duration;
use cocoindex::cli::protocol::{ConfirmAction, Event, Line, MARKER, PROTOCOL_VERSION, decode_line};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use crate::error::{CliError, CliResult, fail};
-/// What the child wrote on stdout, in order.
+/// How long to wait for the rest of the child's stderr after it exited. A
+/// process it left behind can hold the pipe open, so end of file may never come.
+const STDERR_DRAIN: Duration = Duration::from_millis(200);
+
+/// What the child wrote, in order for each stream.
pub enum Output<'a> {
- /// The user's own output, to forward.
+ /// The user's own stdout output, to forward.
Text(&'a str),
+ /// A line of the child's stderr (engine logs, the user's `eprintln!`), to
+ /// forward. It comes through here so that the progress block, drawn on the
+ /// same stream, can make room for it.
+ ErrorText(&'a str),
/// A protocol record after the handshake (including the terminal one).
Event(Event),
}
@@ -92,6 +101,24 @@ async fn pending_answer(answer: &mut Option<tokio::sync::oneshot::Receiver<bool>
}
}
+/// Forward what a finished read left in `buf`, and return whether the stream is
+/// still open: the end of the stream, or a failed read, ends the forwarding, not
+/// the run. `buf` decides what to forward, not the count: a read that `select!`
+/// cancelled leaves its bytes there, so a last line with no newline can arrive
+/// with a count of 0.
+fn forward_stderr(
+ read: std::io::Result<usize>,
+ buf: &mut Vec<u8>,
+ on_output: &mut impl FnMut(Output<'_>),
+) -> bool {
+ if !buf.is_empty() {
+ let text = String::from_utf8_lossy(buf).into_owned();
+ buf.clear();
+ on_output(Output::ErrorText(text.trim_end_matches(['\n', '\r'])));
+ }
+ matches!(read, Ok(n) if n > 0)
+}
+
/// Run `<exe> __coco <verb> --protocol N <flags>` and feed its output to
/// `on_output`. The first record must be a matching `hello`. A `confirm`
/// record (sent when `flags` has `--confirm`) is answered here: the user is
@@ -127,7 +154,7 @@ pub async fn run(
Stdio::null()
})
.stdout(Stdio::piped())
- .stderr(Stdio::inherit())
+ .stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()
.map_err(fail(&format!("could not run {}", exe.display())))?;
@@ -140,6 +167,14 @@ pub async fn run(
));
};
let mut reader = BufReader::new(stdout);
+ let Some(stderr) = child.stderr.take() else {
+ return Err(CliError::failure(
+ "could not read the target binary's error output",
+ ));
+ };
+ let mut err_reader = BufReader::new(stderr);
+ let mut err_buf = Vec::new();
+ let mut err_open = true;
let mut buf = Vec::new();
let mut greeted = false;
@@ -148,9 +183,13 @@ pub async fn run(
let mut ctrl_c_count = 0u32;
loop {
tokio::select! {
+ read = err_reader.read_until(b'\n', &mut err_buf), if err_open => {
+ err_open = forward_stderr(read, &mut err_buf, &mut on_output);
+ }
read = reader.read_until(b'\n', &mut buf) => {
let n = read.map_err(fail("reading the target binary's output"))?;
- if n == 0 {
+ // A cancelled read can leave a last line here with a count of 0.
+ if n == 0 && buf.is_empty() {
break;
}
let text = String::from_utf8_lossy(&buf).into_owned();
@@ -162,7 +201,9 @@ pub async fn run(
if !text.is_empty() {
on_output(Output::Text(text));
}
- eprintln!("warning: ignoring a malformed protocol line: {raw}");
+ on_output(Output::ErrorText(&format!(
+ "warning: ignoring a malformed protocol line: {raw}"
+ )));
}
Line::Record { text, event } => {
if !text.is_empty() {
@@ -221,7 +262,7 @@ pub async fn run(
ctrl_c_count += 1;
if ctrl_c_count == 1 {
if let Interrupt::Cancel { quiet: false } = interrupt {
- eprintln!("\nStopping...");
+ on_output(Output::ErrorText("\nStopping..."));
}
forward_interrupt(pid);
} else {
@@ -230,10 +271,26 @@ pub async fn run(
}
}
}
- let status = child
- .wait()
- .await
- .map_err(fail("waiting for the target binary"))?;
+ // The child can write to stderr while it shuts down, with stdout closed.
+ let status = loop {
+ tokio::select! {
+ status = child.wait() => {
+ break status.map_err(fail("waiting for the target binary"))?;
+ }
+ read = err_reader.read_until(b'\n', &mut err_buf), if err_open => {
+ err_open = forward_stderr(read, &mut err_buf, &mut on_output);
+ }
+ }
+ };
+ let _ = tokio::time::timeout(STDERR_DRAIN, async {
+ while err_open {
+ let read = err_reader.read_until(b'\n', &mut err_buf).await;
+ err_open = forward_stderr(read, &mut err_buf, &mut on_output);
+ }
+ })
+ .await;
+ // The drain can time out in the middle of a line.
+ forward_stderr(Ok(0), &mut err_buf, &mut on_output);
if let Some(err) = mismatch {
return Err(err);
}
@@ -315,6 +372,23 @@ fn forward_interrupt(pid: Option<u32>) {
mod tests {
use super::*;
+ #[test]
+ fn forward_stderr_keeps_a_last_line_whose_count_was_lost() {
+ let mut forwarded = Vec::new();
+ let mut on_output = |output: Output<'_>| {
+ if let Output::ErrorText(text) = output {
+ forwarded.push(text.to_string());
+ }
+ };
+ let mut buf = b"a line\r\n".to_vec();
+ assert!(forward_stderr(Ok(8), &mut buf, &mut on_output));
+ // A cancelled read left these bytes; the next read finds end of file.
+ buf.extend_from_slice(b"fatal");
+ assert!(!forward_stderr(Ok(0), &mut buf, &mut on_output));
+ assert!(!forward_stderr(Ok(0), &mut buf, &mut on_output));
+ assert_eq!(forwarded, ["a line", "fatal"]);
+ }
+
#[test]
fn confirm_prompts_match_the_python_cli() {
assert_eq!(
diff --git a/rust/cli/src/commands.rs b/rust/cli/src/commands.rs
index b7179a8a..9dd8bd6f 100644
--- a/rust/cli/src/commands.rs
+++ b/rust/cli/src/commands.rs
@@ -26,6 +26,7 @@ async fn query_apps(exe: &Path) -> CliResult<(Vec<AppInfo>, String)> {
let mut found = None;
let outcome = child::run(exe, "ls", &[], Interrupt::Default, |output| match output {
Output::Text(text) => println!("{text}"),
+ Output::ErrorText(text) => eprintln!("{text}"),
Output::Event(Event::Apps { apps, db_path }) => found = Some((apps, db_path)),
Output::Event(_) => {}
})
@@ -308,6 +309,7 @@ pub async fn update(args: UpdateArgs) -> CliResult<()> {
Interrupt::Cancel { quiet },
|output| match output {
Output::Text(text) => renderer.text(text),
+ Output::ErrorText(text) => renderer.error_text(text),
Output::Event(Event::Start { app, db_path }) => {
if !quiet {
renderer.text(&format!(
@@ -319,8 +321,9 @@ pub async fn update(args: UpdateArgs) -> CliResult<()> {
Output::Event(Event::Progress {
ready,
by_component,
+ in_groups,
..
- }) => renderer.progress(ready, by_component),
+ }) => renderer.progress(ready, by_component, in_groups),
Output::Event(Event::Preview { kind, value }) => previews.push((kind, value)),
Output::Event(_) => {}
},
@@ -402,6 +405,7 @@ pub async fn drop_app(args: DropArgs) -> CliResult<()> {
Interrupt::Cancel { quiet },
|output| match output {
Output::Text(text) => println!("{text}"),
+ Output::ErrorText(text) => eprintln!("{text}"),
Output::Event(Event::Start { app, db_path }) => {
if !quiet {
println!(
diff --git a/rust/cli/src/progress.rs b/rust/cli/src/progress.rs
index 8076cd1c..517799ff 100644
--- a/rust/cli/src/progress.rs
+++ b/rust/cli/src/progress.rs
@@ -23,6 +23,7 @@ pub struct Renderer {
started: Instant,
ready_at: Option<Instant>,
components: BTreeMap<String, ComponentStatsWire>,
+ in_groups: ComponentStatsWire,
drawn_lines: usize,
last_draw: Option<Instant>,
spinner: usize,
@@ -48,6 +49,7 @@ impl Renderer {
started: Instant::now(),
ready_at: None,
components: BTreeMap::new(),
+ in_groups: ComponentStatsWire::default(),
drawn_lines: 0,
last_draw: None,
spinner: 0,
@@ -65,12 +67,28 @@ impl Renderer {
self.draw();
}
- pub fn progress(&mut self, ready: bool, components: BTreeMap<String, ComponentStatsWire>) {
+ /// The same for a line of the child's stderr, the stream the block draws on.
+ pub fn error_text(&mut self, text: &str) {
+ self.clear();
+ let mut err = std::io::stderr().lock();
+ let _ = writeln!(err, "{text}");
+ let _ = err.flush();
+ drop(err);
+ self.draw();
+ }
+
+ pub fn progress(
+ &mut self,
+ ready: bool,
+ components: BTreeMap<String, ComponentStatsWire>,
+ in_groups: ComponentStatsWire,
+ ) {
let became_ready = ready && self.ready_at.is_none();
if became_ready {
self.ready_at = Some(Instant::now());
}
self.components = components;
+ self.in_groups = in_groups;
let due = self.last_draw.is_none_or(|t| t.elapsed() >= MIN_REDRAW);
if due || became_ready {
self.clear();
@@ -82,7 +100,9 @@ impl Renderer {
pub fn clear(&mut self) {
if self.drawn_lines > 0 {
let mut err = std::io::stderr().lock();
- let _ = write!(err, "\x1b[{}A\x1b[J", self.drawn_lines);
+ // `\r` first: the terminal's `^C` echo can leave the cursor mid-line,
+ // and clearing from there would keep the start of the status line.
+ let _ = write!(err, "\r\x1b[{}A\x1b[J", self.drawn_lines);
let _ = err.flush();
self.drawn_lines = 0;
}
@@ -96,6 +116,7 @@ impl Renderer {
.map(|(name, stats)| (name.clone(), group(stats)))
.collect(),
ready: self.ready_at.is_some(),
+ in_groups: group(&self.in_groups),
..Default::default()
}
}
diff --git a/rust/cli/tests/e2e.rs b/rust/cli/tests/e2e.rs
index 76a6fd27..50e8352a 100644
--- a/rust/cli/tests/e2e.rs
+++ b/rust/cli/tests/e2e.rs
@@ -528,6 +528,28 @@ fn interrupt_slow_lifespan(verb: &[&str]) {
);
}
+/// A failure inside a stats group reaches the final status, though the group's
+/// rows stay out of the report, and its engine log comes through on stderr.
+#[test]
+fn a_failure_in_a_stats_group_fails_the_final_status() {
+ let sb = Sandbox::new(&[("a.txt", "alpha")]);
+ let output = Command::new(env!("CARGO_BIN_EXE_cocoindex"))
+ .args(["update", &exe_target("FixtureApp")])
+ .current_dir(sb.dir.path())
+ .env("COCOINDEX_DB", sb.path("db"))
+ .env("FIXTURE_SRC", sb.path("src"))
+ .env("FIXTURE_OUT", sb.path("out"))
+ .env("FIXTURE_FAIL_IN_GROUP", "1")
+ .env_remove("RUST_LOG")
+ .output()
+ .unwrap();
+ assert_ok(&output);
+ let text = stdout(&output);
+ assert!(text.contains("✗ Done in"), "{text}");
+ assert!(text.contains("1 failed"), "{text}");
+ assert!(stderr(&output).contains("fixture: boom"));
+}
+
/// The binary's own `main` still runs, and its error (a `Debug`-only type, as
/// a plain `main` allows) becomes exit status 1.
#[test]
diff --git a/rust/cli/tests/fixture_app/src/main.rs b/rust/cli/tests/fixture_app/src/main.rs
index 7e8602c3..f0197ad2 100644
--- a/rust/cli/tests/fixture_app/src/main.rs
+++ b/rust/cli/tests/fixture_app/src/main.rs
@@ -39,6 +39,17 @@ async fn fixture_app(ctx: Ctx) -> Result<()> {
target.declare_file(&ctx, name, text.as_bytes())?;
}
println!("fixture: processed {count}");
+ // `FIXTURE_FAIL_IN_GROUP` fails a background component inside a stats group:
+ // the run itself still succeeds.
+ if std::env::var_os("FIXTURE_FAIL_IN_GROUP").is_some() {
+ ctx.stats_group("Failing", |group_ctx, _handle| async move {
+ group_ctx
+ .mount("boom", |_ctx| async { Err(Error::engine("fixture: boom")) })
+ .await?;
+ Ok::<_, Error>(())
+ })
+ .await?;
+ }
Ok(())
}
diff --git a/rust/core/src/engine/component.rs b/rust/core/src/engine/component.rs
index 1a2a0dd4..919941fb 100644
--- a/rust/core/src/engine/component.rs
+++ b/rust/core/src/engine/component.rs
@@ -494,9 +494,9 @@ pub(crate) struct StatsGroup<Prof: EngineProfile> {
}
impl<Prof: EngineProfile> StatsGroup<Prof> {
- pub(crate) fn new() -> Self {
+ pub(crate) fn new(parent: &ProcessingStats) -> Self {
Self {
- stats: ProcessingStats::new(),
+ stats: ProcessingStats::new_in(parent),
readiness: ComponentBgChildReadiness::default(),
active_members: parking_lot::Mutex::new(Vec::new()),
}
@@ -558,7 +558,7 @@ impl<Prof: EngineProfile> ComponentProcessorContext<Prof> {
report_to_stdout: bool,
refresh_interval_secs: Option<f64>,
) -> (ComponentProcessorContext<Prof>, ProcessingStats) {
- let group = Arc::new(StatsGroup::new());
+ let group = Arc::new(StatsGroup::new(self.processing_stats()));
let group_stats = group.stats().clone();
// The group counts as one pending child of the enclosing readiness, so
@@ -1639,12 +1639,10 @@ impl<Prof: EngineProfile> Component<Prof> {
}
Err(err) => {
if !err.is_cancelled() {
- let message = err.to_string();
- let message = message.lines().find(|l| !l.trim().is_empty());
processing_stats.record_failure(crate::engine::stats::FailureRecord {
processor: final_processor_name.to_string(),
component: self.stable_path().clone(),
- message: message.unwrap_or_default().trim().to_string(),
+ message: crate::engine::stats::failure_message(&err),
});
}
processing_stats.update(final_processor_name, |stats| {
@@ -1875,7 +1873,7 @@ mod tests {
let (app, _dir) = test_app("stats_group_members").await;
let root = Component::new(app.app_ctx().clone(), StablePath::root(), None);
let member = root.get_child(key_path(&root, "member"));
- let group = StatsGroup::<TestProfile>::new();
+ let group = StatsGroup::<TestProfile>::new(&ProcessingStats::new());
let activity = ActivityGuard::new(member.clone());
group.push_member(&member);
diff --git a/rust/core/src/engine/progress_display.rs b/rust/core/src/engine/progress_display.rs
index ce63dd12..cd3aa0d1 100644
--- a/rust/core/src/engine/progress_display.rs
+++ b/rust/core/src/engine/progress_display.rs
@@ -132,7 +132,7 @@ impl Style {
}
/// Colors are on unless `NO_COLOR` is set to a non-empty value (no-color.org).
-fn color_enabled() -> bool {
+pub(crate) fn color_enabled() -> bool {
!matches!(std::env::var_os("NO_COLOR"), Some(v) if !v.is_empty())
}
@@ -141,6 +141,19 @@ fn cells(s: &str) -> usize {
unicode_width::UnicodeWidthStr::width(s)
}
+/// `text` with control characters as spaces. A terminal acts on them: a tab or
+/// a carriage return moves its cursor past the cells counted here, which breaks
+/// the in-place redraw.
+fn printable(text: String) -> String {
+ if text.contains(char::is_control) {
+ text.chars()
+ .map(|c| if c.is_control() { ' ' } else { c })
+ .collect()
+ } else {
+ text
+ }
+}
+
/// One output line, built from segments that each carry their own color, so
/// width is measured on the text alone and a cut never splits an escape.
#[derive(Default, Clone)]
@@ -148,12 +161,12 @@ struct Line(Vec<(String, Option<&'static str>)>);
impl Line {
fn text(mut self, text: impl Into<String>) -> Self {
- self.0.push((text.into(), None));
+ self.0.push((printable(text.into()), None));
self
}
fn styled(mut self, code: &'static str, text: impl Into<String>) -> Self {
- self.0.push((text.into(), Some(code)));
+ self.0.push((printable(text.into()), Some(code)));
self
}
@@ -220,6 +233,25 @@ fn fit_end(text: &str, max: usize) -> String {
out
}
+/// Fit `text` in `max` cells, cutting the start: `…guide/page_a.md`. The end
+/// of a path tells its items apart.
+fn fit_start(text: &str, max: usize) -> String {
+ if cells(text) <= max {
+ return text.to_string();
+ }
+ let mut kept = Vec::new();
+ let mut used = 0;
+ for ch in text.chars().rev() {
+ let w = cells(ch.encode_utf8(&mut [0; 4]));
+ if used + w + 1 > max {
+ break;
+ }
+ used += w;
+ kept.push(ch);
+ }
+ std::iter::once('…').chain(kept.into_iter().rev()).collect()
+}
+
/// `<0.1s`, `12.3s`, `2m 05s`, `1h 02m`.
fn format_duration(d: Duration) -> String {
let secs = d.as_secs_f64();
@@ -450,6 +482,11 @@ struct Totals {
failed: u64,
/// Runs still in flight. On the final block these were cut off.
unfinished: u64,
+ /// What stats groups under this block count: they have their own rows, and
+ /// only the final status adds these. Final blocks have one section, so
+ /// nothing counts twice with a nested group's section.
+ failed_in_groups: u64,
+ unfinished_in_groups: u64,
}
impl Totals {
@@ -458,6 +495,11 @@ impl Totals {
Totals {
failed: groups().map(|g| g.num_errors).sum(),
unfinished: groups().map(|g| g.num_in_progress()).sum(),
+ failed_in_groups: snapshots.iter().map(|s| s.in_groups.num_errors).sum(),
+ unfinished_in_groups: snapshots
+ .iter()
+ .map(|s| s.in_groups.num_in_progress())
+ .sum(),
}
}
}
@@ -476,8 +518,11 @@ struct BlockSpec<'a> {
/// The status line that heads a block: one mark (the block's only spinner
/// while running), what is happening, and details in gray parentheses.
///
-/// A one-shot run that ends with runs in flight was stopped (Ctrl+C), not
-/// done.
+/// A run that ends with runs in flight was cut off (Ctrl+C), so it gets no
+/// success mark. A one-shot run then says `Stopped`, not `Done`.
+///
+/// Failures inside stats groups have their own rows, but they count here: the
+/// status of the block's run covers them.
fn status_line(spec: &BlockSpec<'_>, ready: bool, totals: Totals, style: &Style) -> Line {
let elapsed = format_duration(spec.start_time.elapsed());
let ready_in = spec
@@ -501,10 +546,12 @@ fn status_line(spec: &BlockSpec<'_>, ready: bool, totals: Totals, style: &Style)
};
if spec.finished {
- let interrupted = !spec.live && totals.unfinished > 0;
+ let failed = totals.failed + totals.failed_in_groups;
+ let unfinished = totals.unfinished + totals.unfinished_in_groups;
+ let interrupted = unfinished > 0;
let mark = if interrupted {
Line::default().styled(YELLOW, "!")
- } else if totals.failed > 0 {
+ } else if failed > 0 {
Line::default().styled(RED, "✗")
} else {
Line::default().styled(GREEN, "✓")
@@ -515,18 +562,17 @@ fn status_line(spec: &BlockSpec<'_>, ready: bool, totals: Totals, style: &Style)
"Done in"
};
let mut line = say(mark, &format!("{verb} {elapsed}"));
- if totals.failed > 0 {
+ if failed > 0 {
line = line
.styled(GRAY, " · ")
- .styled(RED, format!("{} failed", totals.failed));
+ .styled(RED, format!("{failed} failed"));
}
- if totals.unfinished > 0 {
+ if unfinished > 0 {
line = line.styled(GRAY, " · ").styled(
YELLOW,
format!(
- "{} {} unfinished",
- totals.unfinished,
- plural(totals.unfinished, "run", "runs")
+ "{unfinished} {} unfinished",
+ plural(unfinished, "run", "runs")
),
);
}
@@ -602,7 +648,11 @@ fn block_lines(
.map(|f| cells(&readable_path(&f.component)))
.max()
.unwrap_or(0)
- .min(MAX_NAME_CELLS);
+ .min(if style.width.is_some() {
+ MAX_NAME_CELLS
+ } else {
+ usize::MAX
+ });
for (name, group) in &section.snapshot.stats {
lines.push(component_line(
indent,
@@ -618,7 +668,7 @@ fn block_lines(
break;
}
listed += 1;
- let path = fit_end(&readable_path(&failure.component), path_cells);
+ let path = fit_start(&readable_path(&failure.component), path_cells);
let pad = " ".repeat(path_cells.saturating_sub(cells(&path)) + 2);
lines.push(
Line::default()
@@ -879,7 +929,8 @@ fn write_to_fd(fd: i32, buf: &[u8]) {
}
/// Internal RAII guard for PTY fd cleanup.
-/// Restores original fds and clears the global flag on drop.
+/// 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.
#[cfg(unix)]
struct PtyGuard {
saved_stdout: i32,
@@ -895,6 +946,9 @@ impl Drop for PtyGuard {
nix::libc::close(self.saved_stdout);
nix::libc::close(self.saved_stderr);
}
+ if let Ok(mut groups) = GROUP_SECTIONS.lock() {
+ *groups = None;
+ }
PROGRESS_ACTIVE.store(false, Ordering::SeqCst);
}
}
@@ -1218,6 +1272,8 @@ async fn render_plain(
/// terminal, the group becomes a section of its in-place region, and prints
/// its final block once when it terminates. Otherwise a standalone plain
/// reporter prints scrolling blocks, and ends when the group terminates.
+/// `refresh_interval_secs` sets that reporter's interval; a section redraws
+/// with its region.
pub(crate) fn report_group_stats(
stats: ProcessingStats,
title: String,
@@ -1296,7 +1352,7 @@ mod tests {
fn status(spec: &BlockSpec<'_>, ready: bool, failed: u64) -> String {
let totals = Totals {
failed,
- unfinished: 0,
+ ..Totals::default()
};
status_line(spec, ready, totals, &Style::PLAIN).render(&Style::PLAIN)
}
@@ -1476,11 +1532,85 @@ mod tests {
);
}
+ #[test]
+ fn test_interrupted_live_run_gets_no_success_mark() {
+ let mut snapshot = VersionedProcessingStats::default();
+ snapshot.stats.insert("main".to_string(), group(1, 0, 0, 0));
+ let lines = stats_block_lines(&spec(true, true, 2.4, None), &snapshot, &Style::PLAIN);
+ assert_eq!(lines[0], "! Stopped after 2.4s · 1 run unfinished");
+ }
+
+ #[test]
+ fn test_final_status_counts_failures_in_groups() {
+ let mut snapshot = VersionedProcessingStats::default();
+ snapshot.stats.insert("main".to_string(), group(1, 1, 0, 0));
+ snapshot.in_groups.num_execution_starts = 3;
+ snapshot.in_groups.num_errors = 3;
+ let lines = stats_block_lines(&spec(false, true, 2.0, None), &snapshot, &Style::PLAIN);
+ assert_eq!(
+ lines,
+ vec!["✗ Done in 2.0s · 3 failed", " ✓ main 1 added"]
+ );
+ }
+
+ #[test]
+ fn test_final_status_counts_runs_cut_off_in_groups() {
+ let mut snapshot = VersionedProcessingStats::default();
+ snapshot.stats.insert("main".to_string(), group(1, 1, 0, 0));
+ snapshot.in_groups.num_execution_starts = 2;
+ let lines = stats_block_lines(&spec(true, true, 2.0, None), &snapshot, &Style::PLAIN);
+ assert_eq!(lines[0], "! Stopped after 2.0s · 2 runs unfinished");
+ }
+
+ #[test]
+ fn test_control_characters_never_reach_the_terminal() {
+ let mut snapshot = VersionedProcessingStats::default();
+ snapshot
+ .stats
+ .insert("name\twith\rcontrols".to_string(), group(1, 0, 0, 1));
+ snapshot.failures.push(failure(
+ "name\twith\rcontrols",
+ item("3"),
+ "col1\tcol2\r\x1b[31mred",
+ ));
+ let spec = BlockSpec {
+ title: Some("Title\there"),
+ ..spec(false, true, 2.0, None)
+ };
+ for line in stats_block_lines(&spec, &snapshot, &narrow(60)) {
+ assert!(!line.contains(char::is_control), "{line:?}");
+ }
+ }
+
+ #[test]
+ fn test_failure_paths_keep_the_end_that_tells_them_apart() {
+ let mut snapshot = VersionedProcessingStats::default();
+ snapshot
+ .stats
+ .insert("process_item".to_string(), group(2, 0, 0, 2));
+ for name in ["page_a.md", "page_b.md"] {
+ let key = format!("docs/src/content/docs/programming_guide/{name}");
+ snapshot
+ .failures
+ .push(failure("process_item", path(&[s(&key)]), "boom"));
+ }
+ let spec = spec(false, true, 2.0, None);
+ let terminal = stats_block_lines(&spec, &snapshot, &narrow(100));
+ assert_eq!(terminal[2], " …ocs/programming_guide/page_a.md boom");
+ assert_eq!(terminal[3], " …ocs/programming_guide/page_b.md boom");
+ // Scrolling output keeps lines whole.
+ let plain = stats_block_lines(&spec, &snapshot, &Style::PLAIN);
+ assert_eq!(
+ plain[2],
+ " docs/src/content/docs/programming_guide/page_a.md boom"
+ );
+ }
+
#[test]
fn test_one_unfinished_run_is_singular() {
let totals = Totals {
- failed: 0,
unfinished: 1,
+ ..Totals::default()
};
let line = status_line(&spec(false, true, 1.0, None), true, totals, &Style::PLAIN)
.render(&Style::PLAIN);
diff --git a/rust/core/src/engine/runtime.rs b/rust/core/src/engine/runtime.rs
index 229e4d1c..f108e676 100644
--- a/rust/core/src/engine/runtime.rs
+++ b/rust/core/src/engine/runtime.rs
@@ -11,12 +11,11 @@ fn init_runtime() -> Runtime {
let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
let _ = tracing_subscriber::registry()
// Logs go to stderr, so they never mix into piped stdout, and are
- // colored only when stderr is a terminal.
- .with(
- fmt::layer()
- .with_writer(std::io::stderr)
- .with_ansi(std::io::IsTerminal::is_terminal(&std::io::stderr())),
- )
+ // colored only when stderr is a terminal and `NO_COLOR` is off.
+ .with(fmt::layer().with_writer(std::io::stderr).with_ansi(
+ std::io::IsTerminal::is_terminal(&std::io::stderr())
+ && crate::engine::progress_display::color_enabled(),
+ ))
.with(env_filter)
.try_init();
diff --git a/rust/core/src/engine/stats.rs b/rust/core/src/engine/stats.rs
index c9ba6f64..4c6f8006 100644
--- a/rust/core/src/engine/stats.rs
+++ b/rust/core/src/engine/stats.rs
@@ -34,6 +34,15 @@ impl ProcessingStatsGroup {
pub fn has_errors(&self) -> bool {
self.num_errors > 0
}
+
+ fn add(&mut self, other: &ProcessingStatsGroup) {
+ self.num_execution_starts += other.num_execution_starts;
+ self.num_unchanged += other.num_unchanged;
+ self.num_adds += other.num_adds;
+ self.num_deletes += other.num_deletes;
+ self.num_reprocesses += other.num_reprocesses;
+ self.num_errors += other.num_errors;
+ }
}
/// Failures kept for the progress summary; the counts in the stats groups
@@ -51,6 +60,15 @@ pub struct FailureRecord {
pub message: String,
}
+/// The message a failure row shows: the first line of the underlying error.
+/// Context layers stay out, as an error's `Display` puts them first, under a
+/// bare `Context:` line.
+pub(crate) fn failure_message(err: &Error) -> String {
+ let text = err.without_contexts().to_string();
+ let line = text.lines().find(|l| !l.trim().is_empty());
+ line.unwrap_or_default().trim().to_string()
+}
+
/// A versioned snapshot of processing stats, combining the stats map with a version counter.
#[derive(Default, Clone)]
pub struct VersionedProcessingStats {
@@ -61,6 +79,9 @@ pub struct VersionedProcessingStats {
pub ready: bool,
/// The first `MAX_RECORDED_FAILURES` failures, in the order they happened.
pub failures: Vec<FailureRecord>,
+ /// 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,
}
/// Thread-safe container for processing stats with version tracking and change notification.
@@ -73,6 +94,8 @@ pub struct ProcessingStats {
/// terminated-only waiters aren't woken on every stats update.
terminated_tx: watch::Sender<bool>,
terminated_rx: watch::Receiver<bool>,
+ /// The enclosing stats, for a stats group.
+ parent: Option<Arc<ProcessingStats>>,
}
impl Default for ProcessingStats {
@@ -91,22 +114,41 @@ impl ProcessingStats {
version_rx,
terminated_tx,
terminated_rx,
+ parent: None,
+ }
+ }
+
+ /// The stats of a group opened under `parent`.
+ pub(crate) fn new_in(parent: &ProcessingStats) -> Self {
+ Self {
+ parent: Some(Arc::new(parent.clone())),
+ ..Self::new()
}
}
- pub fn update(&self, operation_name: &str, mutator: impl FnOnce(&mut ProcessingStatsGroup)) {
+ /// Count what happened: `count` increments a zeroed group, which is added
+ /// to this operation's counts and to `in_groups` of every enclosing stats.
+ /// Those keep their version: their own rows did not change.
+ pub fn update(&self, operation_name: &str, count: impl FnOnce(&mut ProcessingStatsGroup)) {
+ let mut delta = ProcessingStatsGroup::default();
+ count(&mut delta);
let mut guard = self.inner.lock().unwrap();
if let Some(group) = guard.stats.get_mut(operation_name) {
- mutator(group);
+ group.add(&delta);
} else {
- let mut group = ProcessingStatsGroup::default();
- mutator(&mut group);
- guard.stats.insert(operation_name.to_string(), group);
+ guard
+ .stats
+ .insert(operation_name.to_string(), delta.clone());
}
guard.version += 1;
let version = guard.version;
drop(guard);
let _ = self.version_tx.send(version);
+ let mut parent = self.parent.as_deref();
+ while let Some(stats) = parent {
+ stats.inner.lock().unwrap().in_groups.add(&delta);
+ parent = stats.parent.as_deref();
+ }
}
/// Keep a failure for the summary, up to `MAX_RECORDED_FAILURES`. Does not
@@ -167,6 +209,33 @@ impl ProcessingStats {
mod tests {
use super::*;
+ #[test]
+ fn test_failure_message_is_the_first_line_of_the_underlying_error() {
+ let err = Error::internal_msg(" boom\nsecond line").context("while doing x");
+ assert_eq!(failure_message(&err), "boom");
+ }
+
+ #[test]
+ fn test_group_counts_reach_every_enclosing_stats_in_flight_and_failed() {
+ let root = ProcessingStats::new();
+ let group = ProcessingStats::new_in(&root);
+ let nested = ProcessingStats::new_in(&group);
+ nested.update("p", |g| {
+ g.num_execution_starts += 2;
+ g.num_errors += 1;
+ });
+
+ assert_eq!(nested.snapshot().stats["p"].num_errors, 1);
+ assert_eq!(nested.snapshot().in_groups.num_errors, 0);
+ for stats in [&group, &root] {
+ let snapshot = stats.snapshot();
+ assert!(snapshot.stats.is_empty(), "the rows stay split out");
+ assert_eq!(snapshot.in_groups.num_errors, 1);
+ assert_eq!(snapshot.in_groups.num_in_progress(), 1);
+ }
+ assert_eq!(root.snapshot().version, 0, "its own rows did not change");
+ }
+
#[test]
fn test_version_increments_on_update() {
let stats = ProcessingStats::new();
diff --git a/rust/sdk/cocoindex/src/app.rs b/rust/sdk/cocoindex/src/app.rs
index df8f0cc7..40a07bdd 100644
--- a/rust/sdk/cocoindex/src/app.rs
+++ b/rust/sdk/cocoindex/src/app.rs
@@ -12,7 +12,7 @@ use cocoindex_core::engine::app::{App as CoreApp, AppOpHandle, AppUpdateOptions}
use cocoindex_core::engine::deadline::DeadlineContext;
use cocoindex_core::engine::environment::{Environment as CoreEnvironment, EnvironmentSettings};
use cocoindex_core::engine::progress_display::{ProgressDisplayOptions, show_progress};
-use cocoindex_core::engine::stats::{ProcessingStats, TERMINATED_VERSION};
+use cocoindex_core::engine::stats::{ProcessingStats, ProcessingStatsGroup, TERMINATED_VERSION};
use cocoindex_core::engine::target_state::{
TargetStateProvider as CoreTargetStateProvider, TargetStateProviderRegistry,
};
@@ -796,22 +796,18 @@ impl App {
/// [`RunStats`] flattens away).
pub(crate) fn update_stats_from_processing(processing_stats: &ProcessingStats) -> UpdateStats {
let snapshot = processing_stats.snapshot();
+ let component_stats = |group: &ProcessingStatsGroup| ComponentStats {
+ num_execution_starts: group.num_execution_starts,
+ num_unchanged: group.num_unchanged,
+ num_adds: group.num_adds,
+ num_deletes: group.num_deletes,
+ num_reprocesses: group.num_reprocesses,
+ num_errors: group.num_errors,
+ };
let by_component = snapshot
.stats
.iter()
- .map(|(name, group)| {
- (
- name.clone(),
- ComponentStats {
- num_execution_starts: group.num_execution_starts,
- num_unchanged: group.num_unchanged,
- num_adds: group.num_adds,
- num_deletes: group.num_deletes,
- num_reprocesses: group.num_reprocesses,
- num_errors: group.num_errors,
- },
- )
- })
+ .map(|(name, group)| (name.clone(), component_stats(group)))
.collect();
let status = if snapshot.ready {
UpdateStatus::Ready
@@ -821,6 +817,7 @@ impl App {
UpdateStats {
by_component,
status,
+ in_groups: component_stats(&snapshot.in_groups),
}
}
diff --git a/rust/sdk/cocoindex/src/cli/protocol.rs b/rust/sdk/cocoindex/src/cli/protocol.rs
index 58ddbe2d..4b02c410 100644
--- a/rust/sdk/cocoindex/src/cli/protocol.rs
+++ b/rust/sdk/cocoindex/src/cli/protocol.rs
@@ -41,6 +41,9 @@ pub enum Event {
version: u64,
ready: bool,
by_component: BTreeMap<String, ComponentStatsWire>,
+ /// What the stats groups under the app count, for the final status.
+ #[serde(default)]
+ in_groups: ComponentStatsWire,
},
/// The child needs a yes/no answer before a destructive step (`drop`, or
/// `update --reset` with state to drop); sent only when the CLI passed
@@ -202,6 +205,7 @@ impl Event {
.iter()
.map(|(k, v)| (k.clone(), ComponentStatsWire::from(v)))
.collect(),
+ in_groups: ComponentStatsWire::from(&stats.in_groups),
}
}
}
diff --git a/rust/sdk/cocoindex/src/stats.rs b/rust/sdk/cocoindex/src/stats.rs
index 81516ad3..4a31cbdc 100644
--- a/rust/sdk/cocoindex/src/stats.rs
+++ b/rust/sdk/cocoindex/src/stats.rs
@@ -116,6 +116,9 @@ pub struct UpdateStats {
pub by_component: BTreeMap<String, ComponentStats>,
/// Whether initial processing has caught up.
pub status: UpdateStatus,
+ /// What the stats groups under this scope count, at any depth. Their work is
+ /// split out of `by_component`, and of [`UpdateStats::total`].
+ pub in_groups: ComponentStats,
}
impl UpdateStats {
diff --git a/rust/sdk/cocoindex/tests/detailed_stats.rs b/rust/sdk/cocoindex/tests/detailed_stats.rs
index a270732e..f60f1206 100644
--- a/rust/sdk/cocoindex/tests/detailed_stats.rs
+++ b/rust/sdk/cocoindex/tests/detailed_stats.rs
@@ -70,6 +70,7 @@ fn update_stats_total_aggregates_components() {
let stats = UpdateStats {
by_component,
status: UpdateStatus::Ready,
+ ..Default::default()
};
let total = stats.total();
assert_eq!(total.num_adds, 5);
@@ -95,6 +96,7 @@ fn update_stats_run_stats_derives_coarse_view() {
let stats = UpdateStats {
by_component,
status: UpdateStatus::Ready,
+ ..Default::default()
};
let run = stats.run_stats();
// Same mapping as the engine→RunStats conversion: skipped=unchanged,