Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
test(ci): distinguish scheduler waits from host pressure (#1909)
Call Whitedd0b738a9c52
diff --git a/docs/plans/ci-wait-attribution.md b/docs/plans/ci-wait-attribution.mdnew file mode 100644index 000000000..516b8fe8c--- /dev/null+++ b/docs/plans/ci-wait-attribution.md@@ -0,0 +1,64 @@+# CI Wait Attribution++## Outcome and Order++The owner approved diagnosing long-tail waits, then removing proven repeated+test preparation, then reviewing the remaining installation chain. Start from+master `3619b19d9`. This first PR is observational, not completion of that order.++Seven first-attempt green runs each covered all 405 selected files. Workflow wall+time ranged from 6m04s to 9m00s. On the identical final PR/merge source trees,+config-save tests took 18.72s/46.35s while process CPU fell from 16.51s to 11.20s.+Show and media tests on the same shard also grew in elapsed time. Existing CPU,+context-switch and byte counters cannot attribute that gap to scheduler delay,+disk latency, database locks, child processes, or application waits.++## Scope and Measurement Contract++Only the existing per-file metrics helper, its consuming pipeline tests and this+plan change. Retain the original selection, one interpreter per file, six shards,+300-second visible watchdog, 20-minute job bound, all 17 checks and their+fail-closed aggregates. No new dependency, sampling thread, runtime hook,+privileged command, kernel setting or application change is needed.++Take two bounded, read-only snapshots: at metrics initialization (after the+launcher imports pytest) and just after pytest returns, before interpreter+shutdown. Emit their interval separately from the existing launcher wall and+process-lifetime counters. The existing shell Finished line remains authoritative.++- Thread CPU and Linux schedstat deltas belong only to the launcher thread,+ not all application threads or children. A changed thread identity invalidates+ thread deltas. Runqueue time means runnable but waiting to receive a CPU.+- Require schedstats enabled at both endpoints before exposing scheduler deltas.+ Disabled, unavailable, malformed or decreasing counters produce null, not a+ fabricated zero. No attempt is made to enable kernel accounting.+- CPU, I/O and memory PSI deltas describe the whole host during that interval,+ not this process. They are contextual evidence, not per-test I/O/lock latency.+ System-wide CPU full pressure is undefined and deliberately omitted.+- Do not subtract overlapping or differently scoped counters to label a residual+ as disk time. Neither absent counters nor host pressure alone proves a cause.+ These observations cannot retroactively explain prior runs.++The kernel documents [schedstat counters](https://docs.kernel.org/scheduler/sched-stats.html)+and [PSI scope and units](https://docs.kernel.org/accounting/psi.html).++## Verification and Delivery++Contracts cover counter parsing, availability, disabled accounting, changes at+the interval boundaries, reset counters, thread identity, nanosecond/microsecond+units, and host/thread separation. Existing real subprocess contracts continue+to verify collection, execution, teardown, child CPU and failed process exits.++Require a new head-bound bot pass, complete review/thread inventory, every+exact-head lint run and all 17 checks before guarded integration. Inspect all+405 file exits and metrics, plus actual distribution/installation suites, then+the exact merged-source CI. Record the observed wait evidence before choosing+the next bounded preparation optimization. Do not rebalance from variance or+replace real migration, locking, legacy-import or package-install coverage.++Local validation: 60 pipeline/metrics cases, 6 shard contracts and 12 private+database fixture contracts passed in separate processes. Ruff 0.4.9, dependency+consistency (84 packages) and whitespace checks passed. The Linux readers have+synthetic parser/interval coverage on macOS; actual hosted counter availability+and full-suite noninterference still require this head's CI. Review inventory+starts at zero findings-bearing heads. No previous PASS applies to this PR.diff --git a/scripts/ci_pytest_metrics.py b/scripts/ci_pytest_metrics.pyindex 72dfd4f6a..cdde19a9a 100644--- a/scripts/ci_pytest_metrics.py+++ b/scripts/ci_pytest_metrics.py@@ -7,6 +7,7 @@ import jsonimport osfrom pathlib import Pathimport sys+import threadingimport timeimport pytest@@ -48,15 +49,95 @@ def linux_io() -> dict[str, int] | None:return None+def linux_scheduler() -> dict | None:+ try:+ enabled = {"0": False, "1": True}[Path("/proc/sys/kernel/sched_schedstats").read_text().strip()]+ values = [int(value) for value in Path("/proc/thread-self/schedstat").read_text().split()]+ if len(values) != 3 or min(values) < 0:+ return None+ return {"enabled": enabled, "run_ns": values[0], "runqueue_ns": values[1]}+ except (OSError, ValueError, KeyError):+ return None+++def linux_pressure(resource_name: str) -> dict[str, int] | None:+ try:+ totals = {}+ for line in Path(f"/proc/pressure/{resource_name}").read_text().splitlines():+ name, *fields = line.split()+ total = int(dict(field.split("=", 1) for field in fields)["total"])+ if total < 0 or name in totals:+ return None+ totals[name] = total+ required = {"some"} if resource_name == "cpu" else {"some", "full"}+ if not required <= totals.keys():+ return None+ # System-wide CPU "full" is undefined, even when the kernel emits zero.+ return {name: totals[name] for name in sorted(required)}+ except (OSError, ValueError, KeyError):+ return None+++def _counter_seconds(before: int | float | None, after: int | float | None, units: int = 1) -> float | None:+ if before is None or after is None or after < before:+ return None+ return round((after - before) / units, 6)+++def wait_observation(before: dict, after: dict) -> dict:+ same_thread = before["thread"] == after["thread"]+ first, last = before["scheduler"] or {}, after["scheduler"] or {}+ scheduler_enabled = first.get("enabled") is True and last.get("enabled") is True and same_thread+ return {+ "interval": "metrics_initialization_to_pytest_return",+ "wall_seconds": _counter_seconds(before["wall"], after["wall"]),+ "launcher_thread_cpu_seconds": (+ _counter_seconds(before["cpu"], after["cpu"]) if same_thread else None+ ),+ "linux_scheduler": {+ "scope": "launcher_thread",+ "enabled_at_start": first.get("enabled"),+ "enabled_at_end": last.get("enabled"),+ "run_seconds": _counter_seconds(first.get("run_ns"), last.get("run_ns"), 10**9)+ if scheduler_enabled else None,+ "runqueue_seconds": _counter_seconds(first.get("runqueue_ns"), last.get("runqueue_ns"), 10**9)+ if scheduler_enabled else None,+ },+ "linux_host_pressure": {+ "scope": "host",+ **{+ name: {+ kind + "_seconds": _counter_seconds(+ (before["pressure"][name] or {}).get(kind),+ (after["pressure"][name] or {}).get(kind), 10**6,+ )+ for kind in (("some",) if name == "cpu" else ("some", "full"))+ }+ for name in ("cpu", "io", "memory")+ },+ },+ }++class FileMetrics:def __init__(self, test_file: str, started_at: float):self.test_file = test_fileself.started_at = started_atself._clock = time.perf_counter+ self._thread_clock = time.thread_time+ self._thread_id = threading.get_ident+ self._wait_started = self._wait_snapshot()self.phases = dict.fromkeys(("collection", "setup", "call", "teardown"), 0.0)self.phase_counts = dict.fromkeys(self.phases, 0)self.slowest: list[tuple[float, str, str]] = []+ def _wait_snapshot(self) -> dict:+ return {+ "wall": self._clock(), "cpu": self._thread_clock(), "thread": self._thread_id(),+ "scheduler": linux_scheduler(),+ "pressure": {name: linux_pressure(name) for name in ("cpu", "io", "memory")},+ }+def _record(self, phase: str, started_at: float, nodeid: str = "") -> None:duration = self._clock() - started_atself.phases[phase] += duration@@ -100,6 +181,7 @@ class FileMetrics:self._record("teardown", started, item.nodeid)def emit(self, stream, exit_code: int) -> None:+ wait_finished = self._wait_snapshot()wall = self._clock() - self.started_ataffinity = Noneif hasattr(os, "sched_getaffinity"):@@ -119,6 +201,7 @@ class FileMetrics:"process_usage": process_usage(),"linux_proc_io": linux_io(),"cpu_affinity_count": affinity,+ "wait_observation": wait_observation(self._wait_started, wait_finished),"slowest_phases": [{"seconds": round(duration, 6), "phase": phase, "test": nodeid}for duration, phase, nodeid in sorted(self.slowest, reverse=True)diff --git a/tests/test_ci_pipeline.py b/tests/test_ci_pipeline.pyindex 943a2a87e..20ecd2987 100644--- a/tests/test_ci_pipeline.py+++ b/tests/test_ci_pipeline.py@@ -221,6 +221,13 @@ def test_file_metrics_observe_real_phases_and_waited_child_cpu(tmp_path: Path) -assert all(value >= 0.02 for value in record["phase_seconds"].values())assert record["outside_phases_seconds"] >= 0assert record["wall_seconds"] >= sum(record["phase_seconds"].values())+ observation = record["wait_observation"]+ assert observation["interval"] == "metrics_initialization_to_pytest_return"+ assert 0.02 <= observation["launcher_thread_cpu_seconds"] <= observation["wall_seconds"]+ assert observation["wall_seconds"] <= record["wall_seconds"]+ assert observation["linux_scheduler"]["scope"] == "launcher_thread"+ assert observation["linux_host_pressure"]["scope"] == "host"+ assert "full_seconds" not in observation["linux_host_pressure"]["cpu"]if sys.platform != "win32":usage = record["process_usage"]for scope in ("self", "waited_children"):@@ -287,6 +294,104 @@ def test_file_metrics_mark_unavailable_platform_counters_explicitly(monkeypatch)metrics.emit(stream, 0)payload = json.loads(stream.getvalue().removeprefix("CI_TEST_METRICS "))assert payload["cpu_affinity_count"] is None+ observation = payload["wait_observation"]+ assert observation["linux_scheduler"]["enabled_at_start"] is None+ assert observation["linux_scheduler"]["runqueue_seconds"] is None+ assert observation["linux_host_pressure"]["io"] == {"some_seconds": None, "full_seconds": None}++[email protected]("enabled,contents,expected", [+ ("1", "3000000000 7000000000 12", {"enabled": True, "run_ns": 3000000000, "runqueue_ns": 7000000000}),+ ("0", "3 0 12", {"enabled": False, "run_ns": 3, "runqueue_ns": 0}),+ ("unknown", "3 4 12", None),+ ("1", "3 4", None),+ ("1", "3 bad 12", None),+ ("1", "3 -4 12", None),+])+def test_wait_scheduler_parses_only_known_nonnegative_counters(monkeypatch, enabled, contents, expected):+ from scripts import ci_pytest_metrics as metrics++ paths = {+ "/proc/sys/kernel/sched_schedstats": enabled,+ "/proc/thread-self/schedstat": contents,+ }+ monkeypatch.setattr(metrics.Path, "read_text", lambda path: paths[str(path)])+ assert metrics.linux_scheduler() == expected++[email protected]("resource_name,contents,expected", [+ ("cpu", "some avg10=1.00 avg60=0.00 avg300=0.00 total=123\nfull total=0", {"some": 123}),+ ("io", "some total=123\nfull total=100", {"some": 123, "full": 100}),+ ("memory", "some total=2\nfull total=1", {"some": 2, "full": 1}),+ ("cpu", "some total=0", {"some": 0}),+ ("io", "some total=123", None),+ ("io", "some total=-1\nfull total=0", None),+ ("cpu", "some total=123\nsome total=124", None),+ ("cpu", "some avg10=1.00", None),+ ("cpu", "some total=invalid", None),+ ("cpu", "", None),+])+def test_wait_pressure_has_explicit_host_scope_and_units(monkeypatch, resource_name, contents, expected):+ from scripts import ci_pytest_metrics as metrics++ def read(path):+ assert str(path) == f"/proc/pressure/{resource_name}"+ return contents++ monkeypatch.setattr(metrics.Path, "read_text", read)+ assert metrics.linux_pressure(resource_name) == expected+++def _wait_counter_snapshot(*, multiplier=1, thread=7, enabled=True):+ return {+ "wall": 20 * multiplier, "cpu": 2 * multiplier, "thread": thread,+ "scheduler": {"enabled": enabled, "run_ns": 2_000_000_000 * multiplier,+ "runqueue_ns": 3_000_000_000 * multiplier},+ "pressure": {name: {"some": 9_000_000 * multiplier, "full": 5_000_000 * multiplier}+ for name in ("cpu", "io", "memory")},+ }+++def test_wait_interval_deltas_do_not_mix_thread_and_host_counters():+ from scripts.ci_pytest_metrics import wait_observation++ result = wait_observation(_wait_counter_snapshot(), _wait_counter_snapshot(multiplier=2))+ assert result["wall_seconds"] == 20+ assert result["launcher_thread_cpu_seconds"] == 2+ assert result["linux_scheduler"] == {+ "scope": "launcher_thread", "enabled_at_start": True, "enabled_at_end": True,+ "run_seconds": 2, "runqueue_seconds": 3,+ }+ assert result["linux_host_pressure"] == {+ "scope": "host", "cpu": {"some_seconds": 9},+ "io": {"some_seconds": 9, "full_seconds": 5},+ "memory": {"some_seconds": 9, "full_seconds": 5},+ }++[email protected]("first_enabled,last_enabled", [(False, False), (False, True), (True, False), (None, True)])+def test_wait_interval_never_treats_disabled_accounting_as_no_wait(first_enabled, last_enabled):+ from scripts.ci_pytest_metrics import wait_observation++ result = wait_observation(_wait_counter_snapshot(enabled=first_enabled),+ _wait_counter_snapshot(multiplier=2, enabled=last_enabled))+ assert result["linux_scheduler"]["enabled_at_start"] is first_enabled+ assert result["linux_scheduler"]["enabled_at_end"] is last_enabled+ assert result["linux_scheduler"]["runqueue_seconds"] is None+ assert result["linux_scheduler"]["run_seconds"] is None+ assert result["launcher_thread_cpu_seconds"] == 2+++def test_wait_interval_rejects_reset_counters_and_changed_thread_identity():+ from scripts.ci_pytest_metrics import wait_observation++ reset = wait_observation(_wait_counter_snapshot(multiplier=2), _wait_counter_snapshot())+ assert reset["linux_scheduler"]["runqueue_seconds"] is None+ assert reset["linux_host_pressure"]["io"]["some_seconds"] is None+ changed = wait_observation(_wait_counter_snapshot(), _wait_counter_snapshot(multiplier=2, thread=8))+ assert changed["launcher_thread_cpu_seconds"] is None+ assert changed["linux_scheduler"]["runqueue_seconds"] is None+ assert changed["linux_host_pressure"]["io"]["some_seconds"] == 9@pytest.mark.parametrize("timeout", ["0", "00", "-1", "invalid"])