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
perf(ci): measure long tails and remove repeated setup (#1889)
Call White1e21561fa374
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlindex b0868d04b..2c6b15461 100644--- a/.github/workflows/lint.yml+++ b/.github/workflows/lint.yml@@ -89,13 +89,10 @@ jobs:SETUPTOOLS_SCM_PRETEND_VERSION_FOR_AVIBE_OS: 3.0.99rc1SETUPTOOLS_SCM_PRETEND_VERSION_FOR_AVIBE_MEMORY: 3.0.99rc1run: |- pip install -e . build hatchling hatch-vcs pytest+ pip install -e . build hatchling hatch-vcspython scripts/prepare_local_show_runtime_manifest.pypython -m build --outdir memory-dist packaging/avibe-memorypython -m build- AVIBE_CORE_WHEEL="$(ls dist/avibe_os-*.whl)" \- AVIBE_MEMORY_WHEEL="$(ls memory-dist/avibe_memory-*.whl)" \- pytest tests/test_memory_distribution.py -v- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6with:@@ -111,6 +108,19 @@ jobs:if-no-files-found: errorretention-days: 1+ # Keep the existing core-only wheel artifact stable for all consumers.+ # Multiple source directories preserve dist/ and memory-dist/ in this+ # companion artifact, consumed only by the distribution contracts.+ - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6+ with:+ name: vibe-package-contracts-linux+ path: |+ dist/*.tar.gz+ memory-dist/*.whl+ memory-dist/*.tar.gz+ if-no-files-found: error+ retention-days: 1+unit-test-shards:name: unit-tests (${{ matrix.shard }}/${{ matrix.shard-total }})runs-on: ubuntu-latest@@ -288,6 +298,12 @@ jobs:name: vibe-wheel-linuxpath: dist+ - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8+ if: matrix.suite == 'installer'+ with:+ name: vibe-package-contracts-linux+ path: .+- uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6with:python-version: "3.12"@@ -308,6 +324,21 @@ jobs:GITHUB_TOKEN: ${{ github.token }}run: python scripts/prepare_local_show_runtime_manifest.py+ - name: Verify built distribution contracts+ if: matrix.suite == 'installer'+ env:+ AVIBE_PACKAGE_CONTRACT_VERSION: 3.0.99rc1+ run: |+ set -o pipefail+ output="$RUNNER_TEMP/distribution-contracts.log"+ AVIBE_CORE_WHEEL="$(ls dist/avibe_os-*.whl)" \+ AVIBE_MEMORY_WHEEL="$(ls memory-dist/avibe_memory-*.whl)" \+ pytest tests/test_memory_distribution.py -v -ra | tee "$output"+ if grep -Eq '(^|[[:space:]])[0-9]+ skipped|SKIPPED' "$output"; then+ echo "Distribution contracts must not skip."+ exit 1+ fi+- name: Run packaged Memory package-shape smokeif: matrix.suite == 'packaged-memory'run: |diff --git a/docs/plans/ci-tail-observability.md b/docs/plans/ci-tail-observability.mdnew file mode 100644index 000000000..66180bf32--- /dev/null+++ b/docs/plans/ci-tail-observability.md@@ -0,0 +1,190 @@+# CI Tail Observability++## Outcome and sequence++Reduce the long tail before further fixture and artifact-pipeline optimization.+This follows #1879, #1882 and #1886. The initial scope is observational only:+`scripts/ci_unit_tests.sh`, its metrics helper, the consuming pipeline contracts,+and this plan. No new dependency, runner, test selection, timeout, application+behavior, or deployment changes are included.++Three green samples at the end of the previous iteration took 6m24s, 12m40s+and 11m54s (runs 33967285557, 33968815151 and 33969694784). The slowest shard+moved between runners. In the two slow samples, 18 and 19 files respectively+took at least 1.5 times their three-sample median. Total runner occupation grew+only 9-12% relative to the fast sample. CPU contention, I/O, and application+waiting cannot be distinguished from the old elapsed-only logs.++The sequence authorized by the owner is:++1. Collect per-file resource and phase measurements without changing execution.+2. Use those measurements to remove repeated setup where coverage is independent+ of initialization, retaining private databases and real migration/import tests.+3. Shorten the artifact-to-install chain without dropping distribution contracts+ or weakening the existing fail-closed aggregates.++Do not rebalance from a single slow runner, rerun to select a fast result, or+claim a stable improvement from one sample. Later scope decisions need their own+measured justification and consuming tests.++## Measurement contract++The existing launcher still runs one interpreter per file, with its original+300-second stack-dumping watchdog and 20-minute outer job limit. It keeps the+same discovery, integration exclusion, exit handling and subsequent-file+execution after failures. A small pytest plugin observes hooks; it never changes+items, fixtures, reports, assertions or outcomes.++One `CI_TEST_METRICS` JSON record goes to the original diagnostic descriptor+after pytest returns, including failure and empty-selection results. It contains:++- Wall time from the launcher entry, including pytest import and configuration.+- Non-overlapping collection/setup/call/teardown hook durations and invocation+ counts. Parent call timing includes subtests exactly once, not once per report.+- The remaining time outside those hooks, which is not labeled pure import time.+- Cumulative process CPU, block I/O and context switches, separately from waited+ child usage; self peak RSS is in bytes. Children not yet waited are excluded.+- Linux `/proc/self/io` counters and CPU affinity count when available. Unsupported+ or inaccessible optional counters are null, never fabricated zeros. Block I/O+ and proc byte/character counters are different measurements, not interchangeable.+- At most five slow test phases; diagnostic node IDs are capped at 512 characters.++The record explicitly says `pytest_returned_before_interpreter_shutdown`.+It is not proof that a file process exited. The shell's existing `Finished ...`+line and exit code remain authoritative, including interpreter-shutdown hangs.+A timeout during collection/execution may have no metrics record; visible stack+output and the nonzero process exit remain the primary evidence.++CPU/wall ratios and I/O counts provide clues, not direct measurements of CPU+steal time or storage latency. Avoid claiming a host-resource cause from those+counters alone. No host-wide sampler or persistent metrics service is added.++## Verification++Consuming subprocess contracts exercise real phase delays, CPU work in both the+parent and a waited child, bounded subtest summaries, assertion/collection/fixture+failures, empty selection, and all three watchdog boundaries. Optional platform+counters have an explicit unavailable-state test. Existing workflow and shard+contracts remain mandatory. Full exact-head CI must validate every selected file+and all 17 expected checks before integration.++At base `902a97a8824e23d57a184e5c9354cc303db36a78`, local workflow/shard/fixture+contracts passed (38 cases), as did Ruff 0.4.9, dependency consistency and shell+syntax checks. The real delivery-state-machine suite passed all 177 tests with+the observer: 16.30s launcher wall, 6.78s collection, 4.09s setup, 4.71s call,+0.38s teardown. These macOS values are not predictions for hosted Linux runners.+Four alternating small-suite measurements had medians of 0.757s without and+0.762s with the observer. This is a coarse overhead check, not a speedup claim;+the machine was not reserved for benchmarking.++The implementation follows pytest's public wrapper hooks and Python's resource+accounting APIs: [pytest hook reference](https://docs.pytest.org/en/stable/reference/reference.html#hooks),+[resource accounting](https://docs.python.org/3.12/library/resource.html).++## Measured setup reduction++Head `bc1970b2c8` passed the head-bound automatic review (reaction 490355915),+with zero complete reviews or threads. Run 33973069748 passed all 17 checks in+6m57s. All 399 discovered files ran exactly once, with successful shell exits+and one metrics record each. Six shard jobs took 5m28s-6m33s; summed file wall+time was 1999.63s versus 1658.03s parent plus waited-child CPU. This sample did+not reproduce the earlier extreme runner skew and cannot explain it retroactively.++Two existing fixtures are independently dominated by repeated initialization:++| Suite | File wall | Setup | Call | Recorded write bytes |+| --- | ---: | ---: | ---: | ---: |+| Delivery FSM | 33.28s | 19.44s | 10.37s | 571 MB |+| Harness definition lifecycle | 29.11s | 26.02s | 2.02s | 282 MB |++The orchestrator extends scope to these two test modules, `tests/conftest.py`+and `tests/test_ci_test_fixtures.py`. Reuse the existing private-copy factory+with an explicit module-owned template, without changing its default migrated+template. Build each template with the fixture's original initializer, close+its engines and checkpoint the WAL before any copy. FSM retains metadata-only+empty tables, with its original per-test session seed. Harness retains exactly+the schema/data from the explicit-path background-store constructor. Neither+may inherit the default importer's markers or seeded rows.++Contracts compare each template's complete schema, rows and persistent pragmas+with a fresh real initialization, and verify private-copy identity, mutation isolation,+no-overwrite and path confinement. Original test bodies and assertions remain+unchanged; all migration and legacy-import suites continue real initialization.+This is a bounded fixture change, not a production database optimization.++The initial equivalence check exposed nondeterministic constraint/index emission+order across real Alembic rebuilds. Harness therefore reuses the existing migration+suite's whole-schema fingerprint (including constraints and expression indexes),+plus all dumped rows, rather than treating DDL order as behavior. FSM's direct+metadata initializer remains byte-for-byte SQL-dump comparable.++Local validation passed 263 fixture/FSM/lifecycle cases and 169+workflow/shard/fixture/real-migration cases. All 217 original non-fixture+functions/classes in the two business modules are AST-identical. Ruff 0.4.9+and dependency consistency passed. Observer measurements after the change:+FSM 178 cases, 5.91s wall/1.00s setup; lifecycle 74 cases, 2.21s wall/0.51s+setup. These include the two new equivalence contracts and are local samples,+not hosted-CI speedup estimates. The lifecycle baseline profile independently+attributed 14.05s to 41 real migration calls out of 15.88s profiled execution.++Hosted step-two run 33974210485 on `925722ae9` passed all 17 checks in 7m22s,+again with all 399 files, successful shell exits and metrics exactly once.+FSM fell from 33.28s to 15.11s, setup 19.44s to 1.78s, recorded writes 571MB+to 175MB. Lifecycle fell from 29.11s to 4.97s, setup 26.02s to 1.06s, writes+282MB to 58MB. Their original call-phase work remains exercised, with one new+equivalence test each. The unchanged shard 4 rose from 393s to 427s, while its+summed CPU fell from 337s to 263s. This is not evidence of a faster whole run+or proof of a particular host bottleneck; the two fixture reductions are the+demonstrated result. Automatic review completed with new reaction 490371521+on the unchanged head; complete review/thread collections were empty.++## Artifact-chain scope decision++Run 33973069748 spent 99.55s in the 21 distribution contracts before uploading+artifacts. The producer took 218s, then the installer/Memory/Windows consumers+took 123s/149s/176s. This is independent validation work, not a build prerequisite.++Extend scope only to `.github/workflows/lint.yml` and the existing pipeline+contracts. Move the unchanged distribution suite into the existing installer+matrix member, still under the required fail-closed install aggregate. Do not+add runners or combine mutable environments. Keep the producer's exact core+wheel artifact unchanged; publish an additional same-run artifact containing+both sdists and the Memory wheel with their directory layout preserved. Only+the installer member downloads that companion artifact. Distribution tests+continue to use the exact producer wheel pair and explicit contract version,+with all real isolated installs and sdist resolution tests intact. Any skipped+contract or nonzero pytest result must fail the job and existing aggregate.++This trades approximately 100s of all-consumer waiting for approximately 100s+of work on the shorter installer branch; it is not a promise of 100s saved on+the whole workflow. The old timestamps suggest about 50s less artifact-chain+tail, subject to download/setup/runner variance. Only a complete new green run+can supply an actual result. Real migration tests remain unchanged: repeated+reference construction is not this iteration's scope.++The companion layout follows the artifact action's documented+[multiple-path common-ancestor behavior](https://github.com/actions/upload-artifact#upload-using-multiple-paths-and-exclusions).++Local workflow/fixture/shard/source-package validation passed 59 cases. Actual+core and Memory wheels plus sdists were built at contract version 3.0.99rc1;+all 21 unchanged distribution cases passed across the initial 20 successes and+one targeted recovery after provisioning missing `pip` in the private test venv.+The original failure occurred before sdist resolution because `uv venv` does+not seed pip; hosted setup-python already provides it. No package/runtime+dependency was added. The local wheels use the unit-test UI placeholder, while+the unchanged hosted production UI build and exact same-run artifact transfer+still require full new-head CI. Ruff 0.4.9 and dependency consistency passed.++Before integration, master advanced to `a8145d683b302a1d5411db8e97bf3db5d462ebe1`+through #1888. The orchestrator inspected its API change and consuming dependency+tests: no overlap with this PR's nine-file scope, no allocated artifact-name+collision. Integrate that source and run its new dependency-consumer tests with+the changed fixture/workflow contracts; the new file uses the existing shard+planner fallback, with no invented timing entry.++After merging that exact master, all 561 dependency-consumer/FSM/lifecycle/+workflow/shard/fixture cases passed. The new inventory is 400 files; the previous+399-file hosted comparisons remain pinned to their original heads. The final+scope remains nine files relative to the integrated master. The prior automatic+review was terminal before the next push (live bot +1, no reviews or threads);+the next head requires its own complete review and CI evidence before merge.diff --git a/scripts/ci_pytest_metrics.py b/scripts/ci_pytest_metrics.pynew file mode 100644index 000000000..72dfd4f6a--- /dev/null+++ b/scripts/ci_pytest_metrics.py@@ -0,0 +1,127 @@+"""Bounded, observational metrics for the one-interpreter-per-file CI launcher."""++from __future__ import annotations++import heapq+import json+import os+from pathlib import Path+import sys+import time++import pytest++try:+ import resource+except ImportError: # The shell launcher is POSIX, but importing this helper is portable.+ resource = None+++def process_usage() -> dict | None:+ if resource is None:+ return None+ result = {}+ for name, who in (("self", resource.RUSAGE_SELF), ("waited_children", resource.RUSAGE_CHILDREN)):+ usage = resource.getrusage(who)+ result[name] = {+ "user_cpu_seconds": round(usage.ru_utime, 6),+ "system_cpu_seconds": round(usage.ru_stime, 6),+ "input_blocks": usage.ru_inblock,+ "output_blocks": usage.ru_oublock,+ "voluntary_context_switches": usage.ru_nvcsw,+ "involuntary_context_switches": usage.ru_nivcsw,+ }+ # getrusage reports bytes on macOS and KiB on Linux. This is a peak, not a delta.+ peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss+ result["self"]["peak_rss_bytes"] = peak * (1 if sys.platform == "darwin" else 1024)+ return result+++def linux_io() -> dict[str, int] | None:+ try:+ values = {}+ for line in Path("/proc/self/io").read_text().splitlines():+ name, value = line.split(":", 1)+ values[name] = int(value)+ return values+ except (OSError, ValueError):+ return None+++class FileMetrics:+ def __init__(self, test_file: str, started_at: float):+ self.test_file = test_file+ self.started_at = started_at+ self._clock = time.perf_counter+ 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 _record(self, phase: str, started_at: float, nodeid: str = "") -> None:+ duration = self._clock() - started_at+ self.phases[phase] += duration+ self.phase_counts[phase] += 1+ if nodeid:+ heapq.heappush(self.slowest, (duration, phase, nodeid[:512]))+ if len(self.slowest) > 5:+ heapq.heappop(self.slowest)++ @pytest.hookimpl(wrapper=True, tryfirst=True)+ def pytest_collection(self):+ started = self._clock()+ try:+ return (yield)+ finally:+ self._record("collection", started)++ # Time phase execution, not reports: subtest reports overlap their parent call.+ @pytest.hookimpl(wrapper=True, tryfirst=True)+ def pytest_runtest_setup(self, item):+ started = self._clock()+ try:+ return (yield)+ finally:+ self._record("setup", started, item.nodeid)++ @pytest.hookimpl(wrapper=True, tryfirst=True)+ def pytest_runtest_call(self, item):+ started = self._clock()+ try:+ return (yield)+ finally:+ self._record("call", started, item.nodeid)++ @pytest.hookimpl(wrapper=True, tryfirst=True)+ def pytest_runtest_teardown(self, item):+ started = self._clock()+ try:+ return (yield)+ finally:+ self._record("teardown", started, item.nodeid)++ def emit(self, stream, exit_code: int) -> None:+ wall = self._clock() - self.started_at+ affinity = None+ if hasattr(os, "sched_getaffinity"):+ try:+ affinity = len(os.sched_getaffinity(0))+ except OSError:+ pass # Sandboxes can deny optional process counters.+ payload = {+ "schema_version": 1,+ "file": self.test_file,+ "boundary": "pytest_returned_before_interpreter_shutdown",+ "exit_code": exit_code,+ "wall_seconds": round(wall, 6),+ "phase_seconds": {name: round(value, 6) for name, value in self.phases.items()},+ "phase_counts": self.phase_counts,+ "outside_phases_seconds": round(wall - sum(self.phases.values()), 6),+ "process_usage": process_usage(),+ "linux_proc_io": linux_io(),+ "cpu_affinity_count": affinity,+ "slowest_phases": [+ {"seconds": round(duration, 6), "phase": phase, "test": nodeid}+ for duration, phase, nodeid in sorted(self.slowest, reverse=True)+ ],+ }+ print("CI_TEST_METRICS " + json.dumps(payload, sort_keys=True), file=stream, flush=True)diff --git a/scripts/ci_unit_tests.sh b/scripts/ci_unit_tests.shindex 3471f6858..3c10ab5ec 100755--- a/scripts/ci_unit_tests.sh+++ b/scripts/ci_unit_tests.sh@@ -75,13 +75,18 @@ fi# Keep one interpreter per file. The watchdog also covers collection and# interpreter shutdown; pytest's per-test faulthandler timer would replace it.PYTEST=("$PYTHON_BIN" -u -c '-import faulthandler, os, sys+import faulthandler, os, sys, time+started_at = time.perf_counter()# Retain the original output even while pytest redirects descriptor 2.diagnostics = os.fdopen(os.dup(sys.stderr.fileno()), "w")faulthandler.enable(file=diagnostics)faulthandler.dump_traceback_later(int(sys.argv.pop(1)), file=diagnostics, exit=True)import pytest-sys.exit(pytest.main(sys.argv[1:]))+from scripts.ci_pytest_metrics import FileMetrics+metrics = FileMetrics(sys.argv[1], started_at)+exit_code = pytest.main(sys.argv[1:], plugins=[metrics])+metrics.emit(diagnostics, int(exit_code))+sys.exit(exit_code)' "$FILE_TIMEOUT")select_unit_test_files() {diff --git a/tests/conftest.py b/tests/conftest.pyindex 1220c3f2f..5c66edf37 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -144,14 +144,16 @@ def sqlite_db_factory(tmp_path, _sqlite_state_template_factory):"""Give behavioral tests independent, fully initialized state databases.This is opt-in: migration/import tests still initialize their own empty DBs.+ An explicit template must be closed and checkpointed by its owning fixture.Only new paths inside this test's temporary directory may receive a copy."""- def create(db_path: Path) -> Path:+ def create(db_path: Path, *, template: Path | None = None) -> Path:db_path = db_path.resolve()db_path.relative_to(tmp_path.resolve())db_path.parent.mkdir(parents=True, exist_ok=True)- with _sqlite_state_template_factory().open("rb") as source, db_path.open("xb") as target:+ source_path = template if template is not None else _sqlite_state_template_factory()+ with source_path.open("rb") as source, db_path.open("xb") as target:shutil.copyfileobj(source, target)return db_pathdiff --git a/tests/test_ci_pipeline.py b/tests/test_ci_pipeline.pyindex 97720a7d4..82fc4543b 100644--- a/tests/test_ci_pipeline.py+++ b/tests/test_ci_pipeline.py@@ -1,6 +1,8 @@from __future__ import annotationsimport itertools+import io+import jsonimport osfrom pathlib import Pathimport shutil@@ -24,6 +26,7 @@ def _run_isolated_unit_files(tmp_path: Path, sources: dict[str, str], *, timeoutfor name, source in sources.items():(tmp_path / "tests" / name).write_text(source, encoding="utf-8")shutil.copyfile(ROOT / "scripts/ci_unit_test_shards.py", tmp_path / "scripts/ci_unit_test_shards.py")+ shutil.copyfile(ROOT / "scripts/ci_pytest_metrics.py", tmp_path / "scripts/ci_pytest_metrics.py")return subprocess.run(["bash", str(ROOT / "scripts/ci_unit_tests.sh")], cwd=tmp_path,env={**os.environ, "PYTHON": sys.executable, "CI_TEST_FILE_TIMEOUT_SECONDS": timeout,@@ -63,6 +66,13 @@ def test_unit_file_watchdog_dumps_stacks_and_continues_fail_closed(tmp_path: Patassert "test_after_stuck_file PASSED" in result.stdoutassert "FAILED files:\n tests/test_a_stuck.py" in result.stdoutassert "All unit test files passed." not in result.stdout+ records = _metrics(result)+ assert records[-1]["file"] == "tests/test_b_pass.py"+ if phase == "shutdown":+ assert records[0]["file"] == "tests/test_a_stuck.py"+ assert records[0]["boundary"] == "pytest_returned_before_interpreter_shutdown"+ else:+ assert len(records) == 1@pytest.mark.parametrize("failed", [False, True])@@ -74,6 +84,108 @@ def test_unit_file_runner_preserves_assertions_and_integration_selection(tmp_patassert result.returncode == int(failed), result.stdout + result.stderrassert "Ran 2 unit test file(s), one process each" in result.stdoutassert "No unit tests collected (skipped):\n tests/test_integration.py" in result.stdout+ records = _metrics(result)+ assert [(row["file"], row["exit_code"]) for row in records] == [+ ("tests/test_assertion.py", int(failed)), ("tests/test_integration.py", 5),+ ]+++def _metrics(result) -> list[dict]:+ prefix = "CI_TEST_METRICS "+ return [json.loads(line.removeprefix(prefix)) for line in result.stderr.splitlines() if line.startswith(prefix)]+++def test_file_metrics_observe_real_phases_and_waited_child_cpu(tmp_path: Path) -> None:+ result = _run_isolated_unit_files(tmp_path, {"test_metrics.py": (+ "import subprocess, sys, time, pytest\n"+ "time.sleep(0.03)\n"+ "@pytest.fixture\n"+ "def prepared():\n"+ " time.sleep(0.03)\n"+ " yield\n"+ " time.sleep(0.03)\n"+ "def test_work(prepared):\n"+ " started = time.process_time()\n"+ " while time.process_time() - started < 0.03: pass\n"+ " subprocess.run([sys.executable, '-c', "+ "'import time; start=time.process_time()\\nwhile time.process_time()-start<0.03: pass'], check=True)\n"+ )})+ assert result.returncode == 0, result.stdout + result.stderr+ record, = _metrics(result)+ assert record["schema_version"] == 1+ assert record["boundary"] == "pytest_returned_before_interpreter_shutdown"+ assert record["file"] == "tests/test_metrics.py"+ assert record["exit_code"] == 0+ assert record["phase_counts"] == {"collection": 1, "setup": 1, "call": 1, "teardown": 1}+ assert all(value >= 0.02 for value in record["phase_seconds"].values())+ assert record["outside_phases_seconds"] >= 0+ assert record["wall_seconds"] >= sum(record["phase_seconds"].values())+ if sys.platform != "win32":+ usage = record["process_usage"]+ for scope in ("self", "waited_children"):+ assert usage[scope]["user_cpu_seconds"] + usage[scope]["system_cpu_seconds"] >= 0.02+ assert usage["self"]["peak_rss_bytes"] > 0+ if sys.platform == "linux":+ assert record["linux_proc_io"]["rchar"] > 0+ assert record["cpu_affinity_count"] >= 1+ assert {row["phase"] for row in record["slowest_phases"]} == {"setup", "call", "teardown"}+++def test_file_metrics_do_not_double_count_subtests_or_grow_with_test_count(tmp_path: Path) -> None:+ result = _run_isolated_unit_files(tmp_path, {"test_subtests.py": (+ "import pytest\n"+ "@pytest.mark.parametrize('case', range(8))\n"+ "def test_subtests(case, subtests):\n"+ " for item in range(4):\n"+ " with subtests.test(item=item):\n"+ " assert item < 4\n"+ )})+ assert result.returncode == 0, result.stdout + result.stderr+ record, = _metrics(result)+ assert record["phase_counts"] == {"collection": 1, "setup": 8, "call": 8, "teardown": 8}+ assert len(record["slowest_phases"]) == 5+++def test_file_metrics_do_not_turn_collection_errors_into_success(tmp_path: Path) -> None:+ result = _run_isolated_unit_files(tmp_path, {"test_collection.py": "raise RuntimeError('collection failed')\n"})+ assert result.returncode == 1+ record, = _metrics(result)+ assert record["exit_code"] == 2+ assert record["phase_counts"] == {"collection": 1, "setup": 0, "call": 0, "teardown": 0}++[email protected]("phase", ["setup", "teardown"])+def test_file_metrics_preserve_fixture_failures(tmp_path: Path, phase: str) -> None:+ setup = " raise RuntimeError('setup failed')\n" if phase == "setup" else ""+ teardown = " raise RuntimeError('teardown failed')\n" if phase == "teardown" else ""+ result = _run_isolated_unit_files(tmp_path, {"test_fixture.py": (+ "import pytest\[email protected]\ndef broken():\n" + setup + " yield\n" + teardown+ + "def test_fixture(broken): pass\n"+ )})+ assert result.returncode == 1+ record, = _metrics(result)+ assert record["exit_code"] == 1+ assert record["phase_counts"]["call"] == (0 if phase == "setup" else 1)+ assert record["phase_counts"][phase] == 1+++def test_file_metrics_mark_unavailable_platform_counters_explicitly(monkeypatch) -> None:+ from scripts import ci_pytest_metrics++ monkeypatch.setattr(ci_pytest_metrics, "resource", None)+ assert ci_pytest_metrics.process_usage() is None++ def denied(_path):+ raise PermissionError("proc is unavailable")++ monkeypatch.setattr(ci_pytest_metrics.Path, "read_text", denied)+ monkeypatch.setattr(ci_pytest_metrics.os, "sched_getaffinity", denied, raising=False)+ assert ci_pytest_metrics.linux_io() is None+ stream = io.StringIO()+ metrics = ci_pytest_metrics.FileMetrics("tests/test_unavailable.py", ci_pytest_metrics.time.perf_counter())+ metrics.emit(stream, 0)+ payload = json.loads(stream.getvalue().removeprefix("CI_TEST_METRICS "))+ assert payload["cpu_affinity_count"] is None@pytest.mark.parametrize("timeout", ["0", "00", "-1", "invalid"])@@ -141,6 +253,71 @@ def test_install_suites_run_independently_without_losing_checks() -> None:assert jobs["install-upgrade-regression"]["needs"] == "install-upgrade-shards"+def test_distribution_contracts_consume_same_run_artifacts_without_fencing_other_installers() -> None:+ jobs = _jobs()+ build = jobs["build-linux-artifacts"]+ installers = jobs["install-upgrade-shards"]+ uploads = {+ step["with"]["name"]: step+ for step in build["steps"] if step.get("uses", "").startswith("actions/upload-artifact@")+ }+ assert uploads["vibe-wheel-linux"]["with"]["path"] == "dist/*.whl"+ companion = uploads["vibe-package-contracts-linux"]+ assert set(companion["with"]["path"].splitlines()) == {+ "dist/*.tar.gz", "memory-dist/*.whl", "memory-dist/*.tar.gz",+ }+ assert companion["with"]["if-no-files-found"] == "error"+ assert not companion.get("if") and not companion.get("continue-on-error")+ downloads = [+ step for step in installers["steps"]+ if step.get("with", {}).get("name") == "vibe-package-contracts-linux"+ ]+ download, = downloads+ assert download["uses"].startswith("actions/download-artifact@")+ assert download["if"] == "matrix.suite == 'installer'"+ assert download["with"] == {"name": "vibe-package-contracts-linux", "path": "."}+ assert not download.get("continue-on-error")+ owners = [+ (name, step) for name, job in jobs.items() for step in job["steps"]+ if "tests/test_memory_distribution.py" in step.get("run", "")+ ]+ (owner, contracts), = owners+ assert owner == "install-upgrade-shards"+ assert contracts["if"] == "matrix.suite == 'installer'"+ assert installers["strategy"]["matrix"]["suite"].count("installer") == 1+ assert installers["steps"].index(download) < installers["steps"].index(contracts)+ build_environment = next(step["env"] for step in build["steps"] if step.get("name") == "Build package artifact")+ assert contracts["env"] == {"AVIBE_PACKAGE_CONTRACT_VERSION": build_environment["AVIBE_PACKAGE_CONTRACT_VERSION"]}+ assert 'AVIBE_CORE_WHEEL="$(ls dist/avibe_os-*.whl)"' in contracts["run"]+ assert 'AVIBE_MEMORY_WHEEL="$(ls memory-dist/avibe_memory-*.whl)"' in contracts["run"]+ assert "pytest tests/test_memory_distribution.py -v -ra" in contracts["run"]+ assert not contracts.get("continue-on-error")+ assert jobs["install-upgrade-regression"]["needs"] == "install-upgrade-shards"+ assert jobs["windows-install-smoke"]["needs"] == "build-linux-artifacts"++[email protected](("pytest_exit", "summary"), [(0, "21 passed"), (1, "1 failed"), (0, "14 passed, 7 skipped")])+def test_distribution_contract_command_fails_on_errors_and_skips(tmp_path, pytest_exit, summary):+ for directory, filename in (("dist", "avibe_os-test.whl"), ("memory-dist", "avibe_memory-test.whl")):+ (tmp_path / directory).mkdir()+ (tmp_path / directory / filename).touch()+ binary = tmp_path / "bin"+ binary.mkdir()+ pytest_stub = binary / "pytest"+ pytest_stub.write_text(f"#!/bin/sh\nprintf '%s\\n' '{summary}'\nexit {pytest_exit}\n")+ pytest_stub.chmod(0o755)+ step = next(+ step for step in _jobs()["install-upgrade-shards"]["steps"]+ if step.get("name") == "Verify built distribution contracts"+ )+ result = subprocess.run(+ ["bash", "-e", "-c", step["run"]], cwd=tmp_path,+ env={**os.environ, "PATH": f"{binary}{os.pathsep}{os.environ['PATH']}", "RUNNER_TEMP": str(tmp_path)},+ capture_output=True, text=True,+ )+ assert (result.returncode == 0) == (pytest_exit == 0 and "skipped" not in summary), result.stdout + result.stderr++@pytest.mark.parametrize("result", ["success", "failure", "cancelled", "skipped", ""])def test_install_gate_fails_unless_all_suites_succeeded(tmp_path: Path, result: str) -> None:gate = _jobs()["install-upgrade-regression"]diff --git a/tests/test_ci_test_fixtures.py b/tests/test_ci_test_fixtures.pyindex 3b6fb4454..8782dd735 100644--- a/tests/test_ci_test_fixtures.py+++ b/tests/test_ci_test_fixtures.py@@ -12,44 +12,58 @@ import pytestfrom tests.conftest import _reset_cached_sqlite_engines, _reset_oauth_runtime_state[email protected](params=[False, True])+def custom_template(request, tmp_path):+ if not request.param:+ return None+ template = tmp_path / "custom-template.sqlite"+ with closing(sqlite3.connect(template)) as connection, connection:+ connection.execute("CREATE TABLE fixture_rows (value TEXT)")+ connection.execute("INSERT INTO fixture_rows VALUES ('original')")+ return template++def test_database_copies_preserve_the_entire_template_and_isolate_mutations(- tmp_path, sqlite_db_factory, _sqlite_state_template_factory+ tmp_path, sqlite_db_factory, _sqlite_state_template_factory, custom_template,):- template = _sqlite_state_template_factory()+ template = custom_template if custom_template is not None else _sqlite_state_template_factory()original = template.read_bytes()- first = sqlite_db_factory(tmp_path / "first" / "vibe.sqlite")- second = sqlite_db_factory(tmp_path / "second" / "vibe.sqlite")+ first = sqlite_db_factory(tmp_path / "first" / "vibe.sqlite", template=custom_template)+ second = sqlite_db_factory(tmp_path / "second" / "vibe.sqlite", template=custom_template)assert first.read_bytes() == second.read_bytes() == originalwith closing(sqlite3.connect(first)) as connection, connection:connection.execute("CREATE TABLE test_mutation (value TEXT)")connection.execute("INSERT INTO test_mutation VALUES ('first only')")- third = sqlite_db_factory(tmp_path / "third" / "vibe.sqlite")+ third = sqlite_db_factory(tmp_path / "third" / "vibe.sqlite", template=custom_template)assert template.read_bytes() == second.read_bytes() == third.read_bytes() == originalassert first.read_bytes() != originalwith closing(sqlite3.connect(third)) as connection:assert connection.execute("PRAGMA integrity_check").fetchone() == ("ok",)- assert connection.execute("SELECT version_num FROM alembic_version").fetchone()+ if custom_template is None:+ assert connection.execute("SELECT version_num FROM alembic_version").fetchone()+ else:+ assert connection.execute("SELECT * FROM fixture_rows").fetchall() == [("original",)]-def test_database_factory_never_overwrites_existing_state(tmp_path, sqlite_db_factory):+def test_database_factory_never_overwrites_existing_state(tmp_path, sqlite_db_factory, custom_template):target = tmp_path / "vibe.sqlite"target.write_bytes(b"existing database")with pytest.raises(FileExistsError):- sqlite_db_factory(target)+ sqlite_db_factory(target, template=custom_template)assert target.read_bytes() == b"existing database"-def test_database_factory_rejects_paths_outside_test_isolation(tmp_path, sqlite_db_factory):+def test_database_factory_rejects_paths_outside_test_isolation(tmp_path, sqlite_db_factory, custom_template):outside = tmp_path.parent / f"{tmp_path.name}-outside"with pytest.raises(ValueError):- sqlite_db_factory(outside / "vibe.sqlite")+ sqlite_db_factory(outside / "vibe.sqlite", template=custom_template)assert not outside.exists()link = tmp_path / "outside-link"link.symlink_to(tmp_path.parent, target_is_directory=True)with pytest.raises(ValueError):- sqlite_db_factory(link / outside.name / "vibe.sqlite")+ sqlite_db_factory(link / outside.name / "vibe.sqlite", template=custom_template)assert not outside.exists()diff --git a/tests/test_harness_definition_lifecycle.py b/tests/test_harness_definition_lifecycle.pyindex a5d15dde4..128aa1659 100644--- a/tests/test_harness_definition_lifecycle.py+++ b/tests/test_harness_definition_lifecycle.py@@ -17,7 +17,9 @@ payload contract) and §5.from __future__ import annotationsimport re+import sqlite3import sys+from contextlib import closingfrom datetime import datetime, timedelta, timezonefrom pathlib import Pathfrom zoneinfo import ZoneInfo@@ -59,15 +61,45 @@ FUTURE = (datetime.now(timezone.utc) + timedelta(days=2)).isoformat()PAST = (datetime.now(timezone.utc) - timedelta(days=2)).isoformat()[email protected](scope="module")+def _background_store_template(tmp_path_factory):+ path = tmp_path_factory.mktemp("background-store") / "empty.sqlite"+ sqlite = SQLiteBackgroundTaskStore(path)+ sqlite.close()+ with closing(sqlite3.connect(path)) as connection:+ connection.execute("PRAGMA wal_checkpoint(TRUNCATE)")+ return path++@pytest.fixture()-def store(tmp_path: Path):- sqlite = SQLiteBackgroundTaskStore(tmp_path / "state" / "vibe.sqlite")+def store(tmp_path: Path, sqlite_db_factory, _background_store_template):+ path = sqlite_db_factory(tmp_path / "state" / "vibe.sqlite", template=_background_store_template)+ sqlite = SQLiteBackgroundTaskStore(path)try:yield sqlitefinally:sqlite.close()+def test_background_template_matches_real_store_initialization(+ tmp_path, _background_store_template, sqlite_db_factory,+):+ from tests.test_sqlite_state_migration import _schema_fingerprint++ reference = tmp_path / "reference.sqlite"+ sqlite = SQLiteBackgroundTaskStore(reference)+ sqlite.close()+ copied = sqlite_db_factory(tmp_path / "copied.sqlite", template=_background_store_template)+ with closing(sqlite3.connect(reference)) as fresh, closing(sqlite3.connect(copied)) as clone:+ assert _schema_fingerprint(fresh) == _schema_fingerprint(clone)+ assert sorted(row for row in fresh.iterdump() if row.startswith("INSERT INTO")) == sorted(+ row for row in clone.iterdump() if row.startswith("INSERT INTO")+ )+ for pragma in ("journal_mode", "user_version", "application_id"):+ assert fresh.execute(f"PRAGMA {pragma}").fetchall() == clone.execute(f"PRAGMA {pragma}").fetchall()+ assert clone.execute("PRAGMA integrity_check").fetchone() == ("ok",)++def _task(store: SQLiteBackgroundTaskStore, task_id: str, **overrides) -> None:payload = {"id": task_id,diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.pyindex 86188e7e8..7f3e00cff 100644--- a/tests/test_session_delivery_fsm.py+++ b/tests/test_session_delivery_fsm.py@@ -3,9 +3,10 @@ from __future__ import annotationsimport asyncioimport gcimport json+import sqlite3import threadingfrom concurrent.futures import ThreadPoolExecutor-from contextlib import asynccontextmanager+from contextlib import asynccontextmanager, closingfrom pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, patch@@ -180,12 +181,24 @@ def _seed_session(engine, session_id: str = "ses_fsm") -> None:)[email protected](scope="module")+def _fsm_schema_template(tmp_path_factory):+ path = tmp_path_factory.mktemp("fsm-schema") / "empty.sqlite"+ engine = create_sqlite_engine(path)+ try:+ metadata.create_all(engine)+ finally:+ engine.dispose()+ with closing(sqlite3.connect(path)) as connection:+ connection.execute("PRAGMA wal_checkpoint(TRUNCATE)")+ return path++@pytest.fixture-def managers(tmp_path: Path):- db_path = tmp_path / "fsm.sqlite"+def managers(tmp_path: Path, sqlite_db_factory, _fsm_schema_template):+ db_path = sqlite_db_factory(tmp_path / "fsm.sqlite", template=_fsm_schema_template)engine_a = create_sqlite_engine(db_path)engine_b = create_sqlite_engine(db_path)- metadata.create_all(engine_a)_seed_session(engine_a)controller_a = _Controller()@@ -209,6 +222,23 @@ def managers(tmp_path: Path):engine_b.dispose()+def test_fsm_template_matches_real_empty_metadata(tmp_path, _fsm_schema_template, sqlite_db_factory):+ reference = tmp_path / "reference.sqlite"+ engine = create_sqlite_engine(reference)+ try:+ metadata.create_all(engine)+ with engine.connect() as connection:+ assert all(connection.execute(select(table)).first() is None for table in metadata.tables.values())+ finally:+ engine.dispose()+ copied = sqlite_db_factory(tmp_path / "copied.sqlite", template=_fsm_schema_template)+ with closing(sqlite3.connect(reference)) as fresh, closing(sqlite3.connect(copied)) as clone:+ assert list(fresh.iterdump()) == list(clone.iterdump())+ for pragma in ("journal_mode", "user_version", "application_id"):+ assert fresh.execute(f"PRAGMA {pragma}").fetchall() == clone.execute(f"PRAGMA {pragma}").fetchall()+ assert clone.execute("PRAGMA integrity_check").fetchone() == ("ok",)++@pytest.mark.anyioasync def test_completed_memory_lifecycle_state_does_not_accumulate(managers) -> None:"""Scenario: MEMORY-INDEP-005.