From c8562ceb69a6552d703a6671deda50dd073c68eb Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sat, 5 Dec 2026 01:41:38 +0000 Subject: [PATCH 1/4] A dispatched hosted workflow measures how many source worker copies one Loom process keeps served The MCP source worker copy capacity workflow starts ClickHouse and Postgres, Loom from the checkout with worker copies on, the bundled worker's read and enrollment service and two owned synthetic MCP upstreams (resource and mapped tool) with set latencies and per-resource faults. bench/source_worker_copies.py registers N snapshot and selected_refresh sources of M resources each through the setup operations, runs a fixed number of sync passes in its own process, and writes one JSON file of fixed shape: per-copy and per-check latency, copies confirmed per pass, listing lapses, pass bound marks and the worker's 429s. Only a harness error fails the run. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- .../workflows/mcp-source-worker-capacity.yml | 224 +++++ bench/README.md | 8 + bench/source_worker_copies.py | 874 ++++++++++++++++++ bench/source_worker_copies_fixture.py | 674 ++++++++++++++ .../mcp-source-worker-boundary.md | 4 +- docs/benchmarks/running.md | 48 + tests/unit/test_bench_source_worker_copies.py | 269 ++++++ 7 files changed, 2100 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/mcp-source-worker-capacity.yml create mode 100644 bench/source_worker_copies.py create mode 100644 bench/source_worker_copies_fixture.py create mode 100644 tests/unit/test_bench_source_worker_copies.py diff --git a/.github/workflows/mcp-source-worker-capacity.yml b/.github/workflows/mcp-source-worker-capacity.yml new file mode 100644 index 0000000000..749a6cfd98 --- /dev/null +++ b/.github/workflows/mcp-source-worker-capacity.yml @@ -0,0 +1,224 @@ +name: MCP source worker copy capacity + +# Measures how many owner-only worker copies one Loom process keeps served: Loom from +# this checkout with its own ClickHouse and Postgres, the bundled source worker and two +# owned synthetic MCP upstreams on one GitHub-hosted runner. It records figures and +# gates on none of them; only a harness error fails the run +# (bench/source_worker_copies.py, docs/benchmarks/running.md#source-worker-copy-capacity). +on: + workflow_dispatch: + inputs: + sources: + description: Worker sources (1 to 2000) + type: number + default: 24 + resources: + description: Resources each source selects (1 to 240) + type: number + default: 10 + collections: + description: Collections the sources spread over, one owner each (1 to 64) + type: number + default: 4 + passes: + description: Sync passes to run (1 to 100) + type: number + default: 8 + pass_interval: + description: Seconds from one pass's start to the next (0 runs them back to back) + type: number + default: 60 + max_pass_seconds: + description: LOOM_KNOWLEDGE_SOURCE_SYNC_MAX_PASS_SECONDS (at least 180) + type: number + default: 180 + acl_stale_seconds: + description: LOOM_KNOWLEDGE_SOURCE_ACL_STALE_SECONDS (a copy is checked every half) + type: number + default: 240 + mirror_documents_per_pass: + description: LOOM_KNOWLEDGE_SOURCE_MIRROR_DOCUMENTS_PER_PASS (copies per pass) + type: number + default: 40 + refresh_interval: + description: interval_seconds of the selected_refresh sources (300 to 86400) + type: number + default: 300 + faults: + description: Resources per fault, of denied, unsupported, timeout, unavailable, slow + type: string + default: denied=1,unsupported=1,timeout=1,unavailable=1,slow=2 + upstream_latency_ms: + description: Added latency of each upstream read + type: number + default: 20 + credential_latency_ms: + description: Added latency of each worker credential lookup + type: number + default: 2 + worker_concurrent: + description: The worker's read_limits.concurrent (2 to 16) + type: number + default: 8 + worker_concurrent_per_org: + description: The worker's read_limits.concurrent_per_org (2 to the above) + type: number + default: 4 + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false + +permissions: + contents: read + +env: + PYTHON_VERSION: "3.12" + UV_VERSION: "0.12.19" + +jobs: + measure: + name: Copy and check capacity on one hosted runner + runs-on: ubuntu-24.04 + timeout-minutes: 90 + env: + SOURCES: ${{ inputs.sources }} + RESOURCES: ${{ inputs.resources }} + COLLECTIONS: ${{ inputs.collections }} + PASSES: ${{ inputs.passes }} + PASS_INTERVAL: ${{ inputs.pass_interval }} + REFRESH_INTERVAL: ${{ inputs.refresh_interval }} + FAULTS: ${{ inputs.faults }} + UPSTREAM_LATENCY_MS: ${{ inputs.upstream_latency_ms }} + CREDENTIAL_LATENCY_MS: ${{ inputs.credential_latency_ms }} + WORKER_CONCURRENT: ${{ inputs.worker_concurrent }} + WORKER_CONCURRENT_PER_ORG: ${{ inputs.worker_concurrent_per_org }} + LOOM_ENV_FILE: "" + LOOM_CH_HOST: localhost + LOOM_CH_PORT: "8123" + LOOM_CH_USER: loom + LOOM_CH_READER_USER: loom_reader + LOOM_CH_PASSWORD: loomdev + LOOM_CH_DATABASE: loom + LOOM_CH_SECURE: "false" + LOOM_STORAGE_AUTHORITY: postgres + LOOM_PG_DSN: postgres://loom:loomdev@localhost:5432/loom + LOOM_AUTH_REQUIRED: "true" + LOOM_INSTANCE_LABEL: ci-source-worker-capacity-${{ github.run_id }}-${{ github.run_attempt }} + LOOM_BUILD_COMMIT: ${{ github.sha }} + LOOM_EMBEDDING_MODEL: fake-ngram-1024 + LOOM_LLM_PROVIDER: fake + LOOM_WORKERS_PROCESS: inline + LOOM_BACKGROUND_WORKERS: auto + # The server's own sync stays off: the driver runs every pass, so it counts them. + LOOM_KNOWLEDGE_SOURCE_SYNC_ENABLED: "false" + LOOM_KNOWLEDGE_MIRRORED_SOURCES_ENABLED: "true" + LOOM_KNOWLEDGE_SOURCE_WORKER_COPIES_ENABLED: "true" + LOOM_KNOWLEDGE_SOURCE_SYNC_INTERVAL_SECONDS: "60" + LOOM_KNOWLEDGE_SOURCE_SYNC_MAX_PASS_SECONDS: ${{ inputs.max_pass_seconds }} + LOOM_KNOWLEDGE_SOURCE_ACL_STALE_SECONDS: ${{ inputs.acl_stale_seconds }} + LOOM_KNOWLEDGE_SOURCE_MIRROR_DOCUMENTS_PER_PASS: ${{ inputs.mirror_documents_per_pass }} + # Quotas sized past any run, so a measurement never stops at a source count. + LOOM_KNOWLEDGE_SOURCES_MAX_PER_NAMESPACE: "2000" + LOOM_KNOWLEDGE_CONNECTED_SOURCES_MAX_PER_NAMESPACE: "2000" + LOOM_KNOWLEDGE_CONNECTED_SOURCES_MAX_PER_PERSON: "2000" + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + id: python + with: + python-version: ${{ env.PYTHON_VERSION }} + - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 + with: + version: ${{ env.UV_VERSION }} + enable-cache: false + - name: Install Loom from uv.lock + env: + PYTHON_PATH: ${{ steps.python.outputs.python-path }} + run: uv sync --locked --python "${PYTHON_PATH}" --extra dev --extra code + # The worker runs from its own wheel and lock, as the image ships it. + - name: Install the source worker + run: | + uv build --wheel source_worker --out-dir "$RUNNER_TEMP/source-worker-wheel" + uv venv "$RUNNER_TEMP/source-worker" + uv export --frozen --project source_worker --no-emit-project \ + -o "$RUNNER_TEMP/source-worker-locked.txt" + uv pip install --python "$RUNNER_TEMP/source-worker/bin/python" \ + -r "$RUNNER_TEMP/source-worker-locked.txt" + uv pip install --python "$RUNNER_TEMP/source-worker/bin/python" --no-deps \ + "$RUNNER_TEMP/source-worker-wheel"/*.whl + - name: Configure the run's signer and paths + run: | + signer="$(openssl rand -hex 32)" + printf '::add-mask::%s\n' "$signer" + { + printf 'LOOM_JWT_SECRET=%s\n' "$signer" + printf 'FIXTURE=%s\n' "$RUNNER_TEMP/capacity" + printf 'LOOM_KNOWLEDGE_SOURCE_WORKER_ROUTES_FILE=%s\n' "$RUNNER_TEMP/capacity/loom/routes.json" + } >> "$GITHUB_ENV" + - name: Start ClickHouse + run: | + LOOM_CLICKHOUSE_IMAGE="$(bash dev/clickhouse_release.sh)" + export LOOM_CLICKHOUSE_IMAGE + bash dev/ci_start_clickhouse.sh + - name: Start Postgres with a synchronous standby + run: bash dev/ci_start_postgres.sh + - name: Apply migrations + run: .venv/bin/python -m server.core.schema.migrate + - name: Prepare the worker, its upstreams and the routes file + run: | + "$RUNNER_TEMP/source-worker/bin/python" -I bench/source_worker_copies_fixture.py prepare \ + --dir "$FIXTURE" --org "capacity-${GITHUB_RUN_ID}" --collections "$COLLECTIONS" \ + --concurrent "$WORKER_CONCURRENT" --concurrent-per-org "$WORKER_CONCURRENT_PER_ORG" + - name: Start the worker and its upstreams + run: | + nohup "$RUNNER_TEMP/source-worker/bin/python" -I bench/source_worker_copies_fixture.py serve \ + --dir "$FIXTURE" --upstream-latency-ms "$UPSTREAM_LATENCY_MS" \ + --credential-latency-ms "$CREDENTIAL_LATENCY_MS" > fixture.log 2>&1 & + echo "FIXTURE_PID=$!" >> "$GITHUB_ENV" + for _ in $(seq 1 60); do + test -f "$FIXTURE/ready" && exit 0 + sleep 1 + done + echo "the fixture never became ready" >&2 + cat fixture.log >&2 + exit 1 + - name: Boot Loom from the checkout + run: | + PATH="$PWD/.venv/bin:$PATH" LOOM_WEB_WORKERS=1 nohup sh scripts/serve.sh > server.log 2>&1 & + echo "SERVER_PID=$!" >> "$GITHUB_ENV" + for _ in $(seq 1 90); do + curl -fsS http://localhost:7777/v1/health >/dev/null && exit 0 + sleep 1 + done + echo "the server never became healthy" >&2 + tail -100 server.log >&2 + exit 1 + - name: Measure + timeout-minutes: 75 + run: | + PYTHONPATH="$PWD" .venv/bin/python bench/source_worker_copies.py \ + --base-url http://localhost:7777 --harness "$FIXTURE/harness.json" \ + --sources "$SOURCES" --resources "$RESOURCES" --passes "$PASSES" \ + --pass-interval "$PASS_INTERVAL" --refresh-interval "$REFRESH_INTERVAL" \ + --faults "$FAULTS" --out source-worker-copies.json + - name: Stop the server and the fixture + if: always() + run: | + for pid in "${SERVER_PID:-}" "${FIXTURE_PID:-}"; do + if [ -n "$pid" ]; then kill "$pid" 2>/dev/null || true; fi + done + docker logs loom-ch > clickhouse.log 2>&1 || true + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: always() + with: + name: source-worker-copies + path: | + source-worker-copies.json + server.log + fixture.log + clickhouse.log + if-no-files-found: warn + retention-days: 30 diff --git a/bench/README.md b/bench/README.md index a55d4615fc..e3fd1aef01 100644 --- a/bench/README.md +++ b/bench/README.md @@ -342,6 +342,14 @@ Latency, throughput and storage at scale. org, Postgres sizes, vacuum and a one-org dump, and `memory.set` at fixed rates over several servers. Free with the fake providers; point it only at a private ClickHouse and Postgres ([results](../docs/benchmarks/results.md#memory-at-scale)). +- **`source_worker_copies.py`** — how many owner-only source worker copies one Loom + process keeps served: sources set up through the worker setup operations, then fixed + sync passes, recording per-copy and per-check latency, copies confirmed per pass, + listing lapses, pass bound marks and the worker's 429s in one JSON file. Its fixture, + `source_worker_copies_fixture.py`, runs the bundled worker and two owned synthetic MCP + upstreams in the worker's own environment. Free; it runs in the dispatched `MCP source + worker copy capacity` workflow + ([running](../docs/benchmarks/running.md#source-worker-copy-capacity)). - **`ch_cost_by_op.py`** — ClickHouse cost per loom operation from `system.query_log`, joined through the `log_comment` tag every loom query carries (`" "` / `"worker."`). diff --git a/bench/source_worker_copies.py b/bench/source_worker_copies.py new file mode 100644 index 0000000000..f27ab400aa --- /dev/null +++ b/bench/source_worker_copies.py @@ -0,0 +1,874 @@ +"""Source worker copy capacity: how many owner-only worker copies one Loom process keeps +served, measured through the real setup operations and sync passes. + +The `MCP source worker copy capacity` workflow runs this against a Loom server started +from the checkout, its own ClickHouse and Postgres, and the fixture of +`bench/source_worker_copies_fixture.py` (the bundled source worker and two owned +synthetic MCP upstreams). Free: no model, provider or external service is called. + +Setup goes through the server's HTTP operations as the people who own the sources would: +an org administrator creates `--collections` collections (the fixture's count) and grants +each its owner the writer role; the administrator approves both provisioned profiles +(`knowledge.source.worker_profiles`, `knowledge.source.worker_approve`); each owner links +one account per profile (`knowledge.source.worker_enroll`) and registers its sources +(`knowledge.source.worker_preview`, `knowledge.source.worker_register`). Each request +declares session protection (`X-Loom-Session-Protection: v1`), as this harness's own +client, and carries a personal sign-in token minted here with a session id; the +directory contacts those sign-ins need are written straight into ClickHouse as trusted +fixture inputs. Source `i` lives in collection `i % collections`, is a `snapshot` source +when `i` is even and a `selected_refresh` one when odd, and reads through the resource +profile when `i // 2` is even and the mapped-tool profile otherwise; each selects +`--resources` resources. + +After setup the driver writes the fixture's fault table (`--faults`, at most one fault per +resource, never on a source's first resource when another source can take it) and runs +`--passes` sync passes in this process, each the pass the `knowledge_source_sync` worker +runs (`run_sync()` over every source), `--pass-interval` seconds apart from start to start +or back to back when a pass overruns. The server runs with that worker off, so these are +the only passes. Per pass it records: + +- every worker request a turn makes, timed from its authority read to its last check + (`copy` reads content, `check` confirms access), and its answer: confirmed, or the + refusal reason (`overloaded` is the worker's 429 or this process's channel share); +- each source's turn: its status, whether the pass bound cut it, and the listing it + recorded; +- listing lapses: a source is served while its recorded listing is younger than + `knowledge_source_acl_stale_seconds` at the pass's end; a lapse is a source that was + served and is not; +- the worker's own request counts by route and HTTP status, and its request durations. + +It writes one JSON document of fixed shape (`SCHEMA`, checked by `validate_metrics`) to +`--out`. It exits 1 only on a harness error (a setup step that did not answer `ok`, a +pass that raised, a fixture that could not be read) and records the error in the +document; capacity figures never fail the run. + + PYTHONPATH=$PWD .venv/bin/python bench/source_worker_copies.py \\ + --base-url http://127.0.0.1:7777 --harness "$FIXTURE/harness.json" \\ + --sources 40 --resources 20 --passes 6 --out source-worker-copies.json +""" + +from __future__ import annotations + +import argparse +import asyncio +import json +import math +import sys +import time +import uuid +from collections import Counter +from collections.abc import Callable, Iterable +from dataclasses import asdict, dataclass, field +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any + +SCHEMA = "loom.bench.source_worker_copies.v1" +FAULT_KINDS = ("denied", "unsupported", "timeout", "unavailable", "slow") +KINDS = ("resource", "mapped") +SETUP_OPS = ( + "collection.create", + "grants.create", + "knowledge.source.worker_profiles", + "knowledge.source.worker_approve", + "knowledge.source.worker_enroll", + "knowledge.source.worker_preview", + "knowledge.source.worker_register", +) +# The setup answers a retry may clear: another proof or enrollment held the slot. +_RETRIED = frozenset({"overloaded", "timeout"}) +_SETUP_ATTEMPTS = 5 +_ADMIN = "capacity-admin" +# Every percentile summary has exactly these keys. +SUMMARY_KEYS = ("count", "mean", "p50", "p90", "p99", "max") + + +# --- pure parts ------------------------------------------------------------------------ + + +@dataclass(frozen=True) +class Config: + base_url: str + harness: Path + out: Path + sources: int + resources: int + passes: int + pass_interval: float + refresh_interval: int + faults: dict[str, int] + + +def parse_faults(spec: str) -> dict[str, int]: + """`denied=1,timeout=2` as {kind: count}, every kind present; '' or 'none' for none.""" + counts = dict.fromkeys(FAULT_KINDS, 0) + spec = spec.strip() + if spec in ("", "none"): + return counts + for part in spec.split(","): + name, sep, value = part.strip().partition("=") + if not sep or name not in counts: + raise ValueError(f"unknown fault {name!r}; known: {', '.join(FAULT_KINDS)}") + if not value.isdigit(): + raise ValueError(f"fault {name} needs a whole count, got {value!r}") + counts[name] += int(value) + return counts + + +def parse_config(argv: list[str] | None = None) -> Config: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--base-url", required=True, help="The Loom server under test") + parser.add_argument("--harness", required=True, help="The fixture's harness.json") + parser.add_argument("--out", required=True, help="Where the metrics JSON goes") + parser.add_argument("--sources", type=int, default=40, help="Worker sources, 1 to 2000") + parser.add_argument("--resources", type=int, default=20, help="Resources per source, 1 to 240") + parser.add_argument("--passes", type=int, default=6, help="Sync passes, 1 to 100") + parser.add_argument( + "--pass-interval", + type=float, + default=60.0, + help="Seconds from one pass's start to the next's (0: back to back)", + ) + parser.add_argument( + "--refresh-interval", + type=int, + default=300, + help="interval_seconds of the selected_refresh sources, 300 to 86400", + ) + parser.add_argument( + "--faults", + default="denied=1,unsupported=1,timeout=1,unavailable=1,slow=2", + help=f"Resources per fault kind ({', '.join(FAULT_KINDS)}), or 'none'", + ) + args = parser.parse_args(argv) + try: + faults = parse_faults(args.faults) + except ValueError as error: + parser.error(str(error)) + checks = ( + (1 <= args.sources <= 2000, "--sources must be 1 to 2000"), + (1 <= args.resources <= 240, "--resources must be 1 to 240"), + (1 <= args.passes <= 100, "--passes must be 1 to 100"), + (0 <= args.pass_interval <= 3600, "--pass-interval must be 0 to 3600"), + (300 <= args.refresh_interval <= 86_400, "--refresh-interval must be 300 to 86400"), + ( + sum(faults.values()) <= args.sources * args.resources, + "--faults names more resources than the sources select", + ), + ) + for ok, message in checks: + if not ok: + parser.error(message) + return Config( + base_url=args.base_url.rstrip("/"), + harness=Path(args.harness), + out=Path(args.out), + sources=args.sources, + resources=args.resources, + passes=args.passes, + pass_interval=args.pass_interval, + refresh_interval=args.refresh_interval, + faults=faults, + ) + + +@dataclass(frozen=True) +class SourcePlan: + index: int + name: str + collection: int + mode: str + kind: str + resources: tuple[str, ...] + + +def resource_id(kind: str, source: int, resource: int) -> str: + return f"urn:capacity:{kind}:s{source:05d}:r{resource:04d}" + + +def plan_sources(sources: int, resources: int, collections: int) -> list[SourcePlan]: + plans = [] + for i in range(sources): + kind = KINDS[(i // 2) % 2] + plans.append( + SourcePlan( + index=i, + name=f"cap{i:05d}", + collection=i % collections, + mode="snapshot" if i % 2 == 0 else "selected_refresh", + kind=kind, + resources=tuple(resource_id(kind, i, r) for r in range(resources)), + ) + ) + return plans + + +def plan_faults(plans: list[SourcePlan], faults: dict[str, int]) -> dict[str, str]: + """{resource id: fault}, deterministic: faults go in `FAULT_KINDS` order to the first + resource of sources 1, 2, ..., then source 0, then the second resource of each, so each + fault lands on its own source while there are sources enough.""" + order = [*plans[1:], *plans[:1]] + slots = [plan.resources[r] for r in range(len(plans[0].resources)) for plan in order] + wanted = [kind for kind in FAULT_KINDS for _ in range(faults.get(kind, 0))] + if len(wanted) > len(slots): + raise ValueError("more faults than resources") + return dict(zip(slots, wanted, strict=False)) + + +def percentile(sorted_values: list[float], q: float) -> float: + """Nearest-rank percentile of an ascending list: the smallest value with at least + q percent of the values at or below it.""" + if not sorted_values: + raise ValueError("no values") + if not 0 < q <= 100: + raise ValueError("q must be in (0, 100]") + rank = math.ceil(q / 100 * len(sorted_values)) + return sorted_values[rank - 1] + + +def summarize(values: Iterable[float]) -> dict[str, float | int | None]: + ordered = sorted(values) + if not ordered: + return {"count": 0, "mean": None, "p50": None, "p90": None, "p99": None, "max": None} + return { + "count": len(ordered), + "mean": round(sum(ordered) / len(ordered), 3), + "p50": round(percentile(ordered, 50), 3), + "p90": round(percentile(ordered, 90), 3), + "p99": round(percentile(ordered, 99), 3), + "max": round(ordered[-1], 3), + } + + +def count_diff( + after: dict[str, dict[str, int]], before: dict[str, dict[str, int]] +) -> dict[str, dict[str, int]]: + """What cumulative {route: {status: count}} counters gained between two reads.""" + gained: dict[str, dict[str, int]] = {} + for route, statuses in after.items(): + for status, count in statuses.items(): + delta = count - before.get(route, {}).get(status, 0) + if delta: + gained.setdefault(route, {})[status] = delta + return gained + + +def listing_state( + listed: dict[str, str], names: Iterable[str], at: datetime, stale_seconds: int +) -> dict[str, list[str]]: + """Which sources the mirror read gate serves at `at`: those whose recorded listing is + younger than the stale window. `never` have recorded none.""" + window = timedelta(seconds=stale_seconds) + state: dict[str, list[str]] = {"served": [], "unserved": [], "never": []} + for name in names: + stamp = listed.get(name, "") + if not stamp: + state["never"].append(name) + continue + when = datetime.fromisoformat(stamp) + state["served" if at - when < window else "unserved"].append(name) + return state + + +@dataclass +class Exchange: + """One worker request a turn made.""" + + source: str + operation: str # "copy" or "check" + ms: float + outcome: str # "confirmed" or the refusal reason + + +@dataclass +class TurnRecord: + source: str + status: str + cut: bool + seen: int + changed: int + removed: int + note: str + seconds: float + + +@dataclass +class PassRecord: + index: int + started_s: float + seconds: float + exchanges: list[Exchange] = field(default_factory=list) + turns: list[TurnRecord] = field(default_factory=list) + cut: bool = False + errors: int = 0 + listing: dict[str, list[str]] = field(default_factory=dict) + lapsed: list[str] = field(default_factory=list) + worker_counts: dict[str, dict[str, int]] = field(default_factory=dict) + worker_ms: dict[str, list[float]] = field(default_factory=dict) + + +def _exchange_summary(exchanges: list[Exchange], operation: str) -> dict[str, Any]: + mine = [e for e in exchanges if e.operation == operation] + return { + "attempted": len(mine), + "confirmed": sum(e.outcome == "confirmed" for e in mine), + "outcomes": dict(sorted(Counter(e.outcome for e in mine).items())), + "latency_ms": summarize(e.ms for e in mine if e.outcome == "confirmed"), + } + + +def _worker_429(counts: dict[str, dict[str, int]]) -> int: + return sum(statuses.get("429", 0) for statuses in counts.values()) + + +def pass_metrics(record: PassRecord) -> dict[str, Any]: + exchanges = record.exchanges + return { + "index": record.index, + "started_s": round(record.started_s, 3), + "seconds": round(record.seconds, 3), + "cut": record.cut, + "errors": record.errors, + "turns": len(record.turns), + "turn_statuses": dict(sorted(Counter(t.status for t in record.turns).items())), + "pass_bound_marks": sum(t.cut for t in record.turns), + "copies": _exchange_summary(exchanges, "copy"), + "checks": _exchange_summary(exchanges, "check"), + "confirmed": sum(e.outcome == "confirmed" for e in exchanges), + "written": sum(t.changed for t in record.turns), + "retired": sum(t.removed for t in record.turns), + "overloaded": sum(e.outcome == "overloaded" for e in exchanges), + "listing": { + "served": len(record.listing.get("served", [])), + "unserved": len(record.listing.get("unserved", [])), + "never": len(record.listing.get("never", [])), + "lapses": len(record.lapsed), + "lapsed_sources": sorted(record.lapsed), + }, + "worker": { + "counts": record.worker_counts, + "status_429": _worker_429(record.worker_counts), + "latency_ms": { + route: summarize(values) for route, values in sorted(record.worker_ms.items()) + }, + }, + } + + +def build_metrics( + *, + config: Config, + environment: dict[str, Any], + setup: dict[str, Any], + passes: list[PassRecord], + errors: list[str], +) -> dict[str, Any]: + exchanges = [e for p in passes for e in p.exchanges] + worker_ms: dict[str, list[float]] = {} + for p in passes: + for route, values in p.worker_ms.items(): + worker_ms.setdefault(route, []).extend(values) + settings = asdict(config) + settings["harness"], settings["out"] = str(config.harness), str(config.out) + return { + "schema": SCHEMA, + "config": settings, + "environment": environment, + "setup": setup, + "passes": [pass_metrics(p) for p in passes], + "totals": { + "passes": len(passes), + "copy_latency_ms": summarize( + e.ms for e in exchanges if e.operation == "copy" and e.outcome == "confirmed" + ), + "check_latency_ms": summarize( + e.ms for e in exchanges if e.operation == "check" and e.outcome == "confirmed" + ), + "confirmed": sum(e.outcome == "confirmed" for e in exchanges), + "outcomes": dict(sorted(Counter(e.outcome for e in exchanges).items())), + "overloaded": sum(e.outcome == "overloaded" for e in exchanges), + "worker_429": sum(_worker_429(p.worker_counts) for p in passes), + "worker_latency_ms": { + route: summarize(values) for route, values in sorted(worker_ms.items()) + }, + "pass_bound_marks": sum(t.cut for p in passes for t in p.turns), + "passes_cut": sum(p.cut for p in passes), + "lapses": sum(len(p.lapsed) for p in passes), + }, + "harness_errors": list(errors), + } + + +_TOP = { + "schema": str, + "config": dict, + "environment": dict, + "setup": dict, + "passes": list, + "totals": dict, + "harness_errors": list, +} +_PASS = { + "index": int, + "started_s": float, + "seconds": float, + "cut": bool, + "errors": int, + "turns": int, + "turn_statuses": dict, + "pass_bound_marks": int, + "copies": dict, + "checks": dict, + "confirmed": int, + "written": int, + "retired": int, + "overloaded": int, + "listing": dict, + "worker": dict, +} +_TOTALS = { + "passes": int, + "copy_latency_ms": dict, + "check_latency_ms": dict, + "confirmed": int, + "outcomes": dict, + "overloaded": int, + "worker_429": int, + "worker_latency_ms": dict, + "pass_bound_marks": int, + "passes_cut": int, + "lapses": int, +} + + +def _check_fields(where: str, value: Any, fields: dict[str, type]) -> list[str]: + if not isinstance(value, dict): + return [f"{where}: not an object"] + problems = ( + [f"{where}: keys {sorted(value)} != {sorted(fields)}"] if set(value) != set(fields) else [] + ) + for name, kind in fields.items(): + if name not in value: + continue + item = value[name] + # A whole number is a valid float; a bool is never an int here. + ok = ( + isinstance(item, (int, float)) and not isinstance(item, bool) + if kind is float + else isinstance(item, kind) and not (kind is int and isinstance(item, bool)) + ) + if not ok: + problems.append(f"{where}.{name}: expected {kind.__name__}") + return problems + + +def _check_summary(where: str, value: Any) -> list[str]: + if not isinstance(value, dict) or tuple(value) != SUMMARY_KEYS: + return [f"{where}: summary keys must be {SUMMARY_KEYS}"] + return [] + + +def validate_metrics(doc: Any) -> list[str]: + """Every way `doc` departs from the fixed shape; empty when it conforms.""" + problems = _check_fields("metrics", doc, _TOP) + if problems: + return problems + if doc["schema"] != SCHEMA: + problems.append(f"schema: expected {SCHEMA}") + for i, entry in enumerate(doc["passes"]): + where = f"passes[{i}]" + found = _check_fields(where, entry, _PASS) + problems += found + if found: + continue + for part in ("copies", "checks"): + problems += _check_summary(f"{where}.{part}.latency_ms", entry[part].get("latency_ms")) + for route, summary in entry["worker"].get("latency_ms", {}).items(): + problems += _check_summary(f"{where}.worker.latency_ms.{route}", summary) + totals = doc["totals"] + problems += _check_fields("totals", totals, _TOTALS) + if not problems: + for name in ("copy_latency_ms", "check_latency_ms"): + problems += _check_summary(f"totals.{name}", totals[name]) + if totals["passes"] != len(doc["passes"]): + problems.append("totals.passes: does not match the pass list") + return problems + + +# --- the run --------------------------------------------------------------------------- + + +class HarnessError(Exception): + """A step of the harness itself failed; the run's figures are incomplete.""" + + +class _Setup: + """The setup operations over HTTP, each timed and its answer recorded.""" + + def __init__(self, client: Any, org: str) -> None: + self.client = client + self.org = org + self.ms: dict[str, list[float]] = {op: [] for op in SETUP_OPS} + self.statuses: dict[str, Counter[str]] = {op: Counter() for op in SETUP_OPS} + self.retries = 0 + + async def call(self, op: str, bearer: str, body: dict[str, Any]) -> dict[str, Any]: + payload = {"org": self.org, **body} + for attempt in range(_SETUP_ATTEMPTS): + started = time.perf_counter() + response = await self.client.post( + f"/v1/{op}", + json=payload, + headers={ + "Authorization": f"Bearer {bearer}", + # This harness's own client keeps no session content, so it declares + # protection as the integration witnesses' clients do. + "X-Loom-Session-Protection": "v1", + }, + ) + self.ms[op].append((time.perf_counter() - started) * 1000) + last = attempt == _SETUP_ATTEMPTS - 1 + if response.status_code == 429 and not last: + # Loom's own rate limit: wait as it asks, then send the same request again. + self.statuses[op]["http_429"] += 1 + self.retries += 1 + await asyncio.sleep(float(response.headers.get("retry-after", "1"))) + continue + if response.status_code != 200: + self.statuses[op][f"http_{response.status_code}"] += 1 + raise HarnessError(f"{op}: HTTP {response.status_code}: {response.text[:300]}") + answer = response.json() + status = str(answer.get("status", "ok")) + self.statuses[op][status] += 1 + if status == "ok": + return answer + if status not in _RETRIED or last: + raise HarnessError(f"{op}: answered {status!r} for {body.get('namespace')}") + self.retries += 1 + await asyncio.sleep(0.5 * (attempt + 1)) + raise AssertionError("unreachable") + + def report(self, seconds: float, sources: int, resources: int) -> dict[str, Any]: + return { + "seconds": round(seconds, 3), + "sources": sources, + "resources": resources, + "retries": self.retries, + "ops": { + op: { + "statuses": dict(sorted(self.statuses[op].items())), + "latency_ms": summarize(self.ms[op]), + } + for op in SETUP_OPS + }, + } + + +def _bearer(subject: str, org: str, namespaces: list[str], role: str) -> str: + """A personal sign-in with a session id, which worker setup needs.""" + from server.auth.jwt import mint_token + + return mint_token( + subject, + org, + namespaces, + [role], + is_service_account=False, + session_id=uuid.uuid4().hex, + ttl_seconds=4 * 3600, + ) + + +def collection_name(index: int) -> str: + return f"col-capacity-{index:03d}" + + +async def _seed_identities(org: str, subjects: list[str]) -> None: + """Directory contacts for the sign-ins, as trusted fixture inputs: an owner's standing + and the setup caller check resolve each subject through them.""" + from server.core.ch import get_client, set_query_tag + + set_query_tag("bench.source_worker_copies.identities") + rows = [ + { + "org": org, + "namespace": f"identity-{subject}", + "owner_email": subject, + "contact_email": f"{subject}@example.test", + "password_hash": "", + "active": True, + } + for subject in subjects + ] + await get_client().insert("loom.namespaces", rows) + + +async def run_setup( + config: Config, harness: dict[str, Any], plans: list[SourcePlan], client: Any +) -> _Setup: + org = harness["org"] + collections = int(harness["collections"]) + owners = {a["collection"]: a["owner"] for a in harness["accounts"]} + accounts = {(a["collection"], a["kind"]): a["connection_id"] for a in harness["accounts"]} + if len(accounts) != collections * len(KINDS): + raise HarnessError("harness.json: expected one account per collection and profile") + await _seed_identities(org, [_ADMIN, *owners.values()]) + setup = _Setup(client, org) + admin = _bearer(_ADMIN, org, ["*"], "org_admin") + worker_id, digests = harness["worker_id"], harness["profiles"] + for c in range(collections): + ns = collection_name(c) + await setup.call("collection.create", admin, {"namespace": ns}) + await setup.call( + "grants.create", admin, {"namespace": ns, "subject": owners[c], "role": "writer"} + ) + listed = await setup.call("knowledge.source.worker_profiles", admin, {"namespace": ns}) + offered = {(p["worker_id"], p["profile_digest"]): p for p in listed["profiles"]} + for kind in KINDS: + profile = offered.get((worker_id, digests[kind])) + if profile is None or "snapshot" not in profile["provisioned_modes"]: + raise HarnessError(f"{ns}: the {kind} profile is not provisioned") + await setup.call( + "knowledge.source.worker_approve", + admin, + { + "namespace": ns, + "worker_id": worker_id, + "profile_digest": digests[kind], + "modes": ["live", "snapshot", "selected_refresh"], + "expected_generation": profile["approval_generation"], + }, + ) + owner = _bearer(owners[c], org, [ns], "writer") + for kind in KINDS: + await setup.call( + "knowledge.source.worker_enroll", + owner, + { + "namespace": ns, + "worker_id": worker_id, + "profile_digest": digests[kind], + "connection_id": accounts[(c, kind)], + "connection_generation": "1", + }, + ) + owner_tokens = { + c: _bearer(owners[c], org, [collection_name(c)], "writer") for c in range(collections) + } + for plan in plans: + body: dict[str, Any] = { + "namespace": collection_name(plan.collection), + "name": plan.name, + "worker_id": worker_id, + "profile_digest": digests[plan.kind], + "connection_id": accounts[(plan.collection, plan.kind)], + "mode": plan.mode, + "selection": [{"type": "resource", "id": rid} for rid in plan.resources], + } + if plan.mode == "selected_refresh": + body["interval_seconds"] = config.refresh_interval + token = owner_tokens[plan.collection] + preview = await setup.call("knowledge.source.worker_preview", token, body) + await setup.call( + "knowledge.source.worker_register", + token, + {**body, "fingerprint": preview["fingerprint"], "evidence": preview["evidence"]}, + ) + return setup + + +class _Recorder: + """Times each worker request and each turn the sync makes in this process.""" + + def __init__(self) -> None: + self.current: PassRecord | None = None + self.listed: dict[str, str] = {} + + def install(self) -> Callable[[], None]: + from server.knowledge.app import source_sync_worker as worker + from server.knowledge.app.mcp_worker_read import WorkerReadRefused + + exchange, turn = worker._Turn._exchange, worker.turn + recorder = self + + async def timed_exchange(self: Any, item: Any, *, content: bool) -> Any: + started, outcome = time.perf_counter(), "confirmed" + try: + return await exchange(self, item, content=content) + except WorkerReadRefused as refusal: + # The upstream's own refusal of the account is the one denial that retires. + upstream = refusal.reason == "denied" and refusal.upstream_access + outcome = "denied_upstream" if upstream else str(refusal.reason) + raise + except BaseException as error: + outcome = f"raised:{type(error).__name__}" + raise + finally: + if recorder.current is not None: + recorder.current.exchanges.append( + Exchange( + self.src.name, + "copy" if content else "check", + (time.perf_counter() - started) * 1000, + outcome, + ) + ) + + async def timed_turn(src: Any, state: Any, run: Any) -> Any: + started = time.perf_counter() + result = await turn(src, state, run) + listed = str(result.kind_state.get(worker._LISTED) or "") + if listed: + recorder.listed[src.name] = listed + if recorder.current is not None: + recorder.current.turns.append( + TurnRecord( + src.name, + result.status, + result.cut, + result.documents_seen, + result.changed, + result.removed, + result.note, + time.perf_counter() - started, + ) + ) + return result + + worker._Turn._exchange = timed_exchange + worker.turn = timed_turn + + def restore() -> None: + worker._Turn._exchange = exchange + worker.turn = turn + + return restore + + +async def _worker_stats(client: Any, url: str) -> dict[str, Any]: + response = await client.get(url) + response.raise_for_status() + return response.json() + + +async def run_passes( + config: Config, harness: dict[str, Any], plans: list[SourcePlan], client: Any +) -> list[PassRecord]: + from server.core.ch import set_query_tag + from server.knowledge.app.mcp_worker_runtime import source_worker_runtime + from server.knowledge.app.source_sync import run_sync + from server.settings import settings + + set_query_tag("bench.source_worker_copies.passes") + recorder = _Recorder() + restore = recorder.install() + names = [plan.name for plan in plans] + passes: list[PassRecord] = [] + served_before: set[str] = set() + counts = (await _worker_stats(client, harness["stats_url"]))["counts"] + try: + async with source_worker_runtime(settings.knowledge_source_worker_routes_file): + origin = time.monotonic() + for index in range(config.passes): + wait = origin + index * config.pass_interval - time.monotonic() + if wait > 0: + await asyncio.sleep(wait) + record = PassRecord(index=index, started_s=time.monotonic() - origin, seconds=0) + recorder.current = record + started = time.monotonic() + try: + result = await run_sync() + except Exception as error: # any failure of a pass is the harness's error + raise HarnessError( + f"pass {index} raised {type(error).__name__}: {error}" + ) from error + finally: + recorder.current = None + record.seconds = time.monotonic() - started + record.cut, record.errors = result.cut, len(result.errors) + record.listing = listing_state( + recorder.listed, + names, + datetime.now(UTC), + int(settings.knowledge_source_acl_stale_seconds), + ) + served = set(record.listing["served"]) + record.lapsed = sorted(served_before - served) + served_before = served + stats = await _worker_stats(client, harness["stats_url"]) + record.worker_counts = count_diff(stats["counts"], counts) + record.worker_ms = stats["duration_ms"] + counts = stats["counts"] + passes.append(record) + print(json.dumps(pass_metrics(record)["listing"] | {"pass": index}), flush=True) + finally: + restore() + return passes + + +def _environment(harness: dict[str, Any]) -> dict[str, Any]: + from server.settings import settings + + names = ( + "knowledge_source_worker_copies_enabled", + "knowledge_source_acl_stale_seconds", + "knowledge_source_sync_interval_seconds", + "knowledge_source_sync_max_pass_seconds", + "knowledge_source_mirror_documents_per_pass", + "knowledge_source_worker_live_timeout_s", + ) + return { + "loom": {name: getattr(settings, name) for name in names}, + "worker": harness.get("worker", {}), + "python": sys.version.split()[0], + } + + +async def _run(config: Config) -> dict[str, Any]: + import httpx + + errors: list[str] = [] + harness: dict[str, Any] = {} + environment: dict[str, Any] = {} + setup_report: dict[str, Any] = {} + passes: list[PassRecord] = [] + try: + harness = json.loads(config.harness.read_text()) + environment = _environment(harness) + if not environment["loom"]["knowledge_source_worker_copies_enabled"]: + raise HarnessError("LOOM_KNOWLEDGE_SOURCE_WORKER_COPIES_ENABLED is off") + plans = plan_sources(config.sources, config.resources, int(harness["collections"])) + async with httpx.AsyncClient(base_url=config.base_url, timeout=120) as client: + started = time.monotonic() + setup = await run_setup(config, harness, plans, client) + setup_report = setup.report( + time.monotonic() - started, len(plans), len(plans) * config.resources + ) + Path(harness["faults_file"]).write_text( + json.dumps(plan_faults(plans, config.faults), indent=2) + ) + passes = await run_passes(config, harness, plans, client) + except (HarnessError, OSError, ValueError, KeyError) as error: + errors.append(f"{type(error).__name__}: {error}") + return build_metrics( + config=config, environment=environment, setup=setup_report, passes=passes, errors=errors + ) + + +def main(argv: list[str] | None = None) -> int: + config = parse_config(argv) + from server.cli._ch import run_connected + + harness_org = json.loads(config.harness.read_text())["org"] + metrics = run_connected(lambda _ch: _run(config), orgs=(harness_org,)) + problems = validate_metrics(metrics) + metrics["harness_errors"] += [f"metrics shape: {p}" for p in problems] + config.out.write_text(json.dumps(metrics, indent=2, sort_keys=False) + "\n") + print(json.dumps(metrics["totals"], indent=2)) + for error in metrics["harness_errors"]: + print(f"harness error: {error}", file=sys.stderr) + return 1 if metrics["harness_errors"] else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/bench/source_worker_copies_fixture.py b/bench/source_worker_copies_fixture.py new file mode 100644 index 0000000000..5f9262ad8a --- /dev/null +++ b/bench/source_worker_copies_fixture.py @@ -0,0 +1,674 @@ +"""The bundled source worker and two owned synthetic MCP upstreams for +`bench/source_worker_copies.py`. + +Runs in the source worker's own environment (its wheel and lock), not Loom's: + + python -I bench/source_worker_copies_fixture.py prepare --dir DIR --org ORG --collections 4 + python -I bench/source_worker_copies_fixture.py serve --dir DIR + +`prepare` writes synthetic keys and certificates under one fixture CA, the worker's +configuration with two profiles (one read with `resources/read`, one through a mapped +`read_document` tool), a Loom routes file for that worker, one synthetic account per +collection and profile, and `harness.json`, the driver's inputs (no credential in it). + +`serve` runs, in one process until SIGTERM: + +- the worker's own read and enrollment service (`loom_source_worker.http_service`) over an + mTLS listener on `localhost`, standing in for the TLS proxy in front of its Unix socket; +- an in-memory credential store with the synthetic accounts in place of the KV backend, + each lookup delayed by `--credential-latency-ms`; +- the two upstreams, official MCP SDK servers over TLS, each read delayed by + `--upstream-latency-ms`. Their hosts are `.invalid` names the worker pins to loopback, + and the fixture CA is added to the worker's public roots in this process only; +- a plain loopback stats endpoint, `GET /stats`, which answers the worker's request counts + by route and HTTP status and drains the duration samples taken since the last call. + +Per-resource faults come from `faults.json` in the fixture directory, which the driver +writes once setup is done (setup proves every resource, so none fails before then): +`{"": "denied" | "unsupported" | "timeout" | "unavailable" | "slow"}`. +`denied` answers the read itself with HTTP 403 (the upstream's access refusal), `unavailable` +with 503, `timeout` stalls past the worker's read deadline, `slow` adds `--slow-ms`, and +`unsupported` returns an empty document. The file is read again when it changes. +""" + +from __future__ import annotations + +import argparse +import asyncio +import ipaddress +import json +import os +import signal +import ssl +import time +from collections.abc import Iterator +from contextlib import AsyncExitStack, contextmanager +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any +from uuid import UUID, uuid4 + +import certifi +import uvicorn +from cryptography import x509 +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey +from cryptography.hazmat.primitives.serialization import ( + Encoding, + NoEncryption, + PrivateFormat, + PublicFormat, + load_pem_private_key, + load_pem_public_key, +) +from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID +from loom_source_worker import mcp_client +from loom_source_worker.credential_store import CredentialRecord +from loom_source_worker.direct_backend import DirectBackend +from loom_source_worker.enrollment import EnrollmentService +from loom_source_worker.http_service import create_app +from loom_source_worker.main import _parse_settings +from loom_source_worker.protocol import ConnectionBinding +from loom_source_worker.read_service import ReadFailure, ReadService +from mcp import types +from mcp.server import Server +from mcp.server.streamable_http_manager import StreamableHTTPSessionManager +from pydantic import AnyUrl, SecretStr +from starlette.requests import Request +from starlette.responses import JSONResponse, Response +from starlette.types import ASGIApp, Message, Receive, Scope, Send + +ISSUER = "urn:loom:capacity" +HOSTS = {"resource": "resource-upstream.invalid", "mapped": "mapped-upstream.invalid"} +KINDS = ("resource", "mapped") +FAULTS = ("denied", "unsupported", "timeout", "unavailable", "slow") +# Fewer upstream bytes than the default, so the worker admits up to 16 concurrent reads. +MAX_WIRE_BYTES = 1_000_000 + + +def _schema(*names: str) -> dict[str, Any]: + return { + "type": "object", + "properties": {name: {"type": "string"} for name in names}, + "required": list(names), + "additionalProperties": False, + } + + +INPUT_SCHEMA = _schema("id") +OUTPUT_SCHEMA = _schema("id", "title", "uri", "text") + + +def text_of(resource_id: str) -> str: + """The synthetic document text for one resource: fixed, so a refresh changes nothing.""" + return f"Synthetic capacity document {resource_id}. Owned fixture text, no real data." + + +# --- prepare ------------------------------------------------------------------------- + + +def _write(path: Path, data: bytes, mode: int = 0o600) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode), "wb") as out: + out.write(data) + + +def _private_pem(key: ec.EllipticCurvePrivateKey | Ed25519PrivateKey) -> bytes: + return key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()) + + +def _certificate( + ca: tuple[ec.EllipticCurvePrivateKey, x509.Certificate] | None, + name: str, + *, + sans: tuple[str, ...] = (), + purpose: x509.ObjectIdentifier | None = None, +) -> tuple[ec.EllipticCurvePrivateKey, x509.Certificate]: + key = ec.generate_private_key(ec.SECP256R1()) + subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)]) + signer, issuer = (key, subject) if ca is None else (ca[0], ca[1].subject) + now = datetime.now(UTC) + builder = ( + x509.CertificateBuilder() + .subject_name(subject) + .issuer_name(issuer) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - timedelta(minutes=5)) + .not_valid_after(now + timedelta(hours=12)) + .add_extension(x509.BasicConstraints(ca=ca is None, path_length=None), critical=True) + .add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()), critical=False) + .add_extension( + x509.KeyUsage( + digital_signature=ca is not None, + content_commitment=False, + key_encipherment=False, + data_encipherment=False, + key_agreement=False, + key_cert_sign=ca is None, + crl_sign=ca is None, + encipher_only=False, + decipher_only=False, + ), + critical=True, + ) + ) + if ca is not None: + builder = builder.add_extension( + x509.AuthorityKeyIdentifier.from_issuer_public_key(ca[0].public_key()), critical=False + ) + if purpose is not None: + builder = builder.add_extension(x509.ExtendedKeyUsage([purpose]), critical=False) + if sans: + builder = builder.add_extension( + x509.SubjectAlternativeName([x509.DNSName(s) for s in sans]), critical=False + ) + return key, builder.sign(signer, hashes.SHA256()) + + +def _profile(org: str, kind: str, port: int) -> dict[str, Any]: + endpoint = f"https://{HOSTS[kind]}:{port}/mcp" + config: dict[str, Any] = { + "endpoint": endpoint, + "bearer_audience": endpoint, + "limits": {"max_wire_bytes": MAX_WIRE_BYTES}, + } + if kind == "mapped": + config["read"] = { + "name": "read_document", + "argument_name": "id", + "input_schema": INPUT_SCHEMA, + "output_schema": OUTPUT_SCHEMA, + } + return {"organizations": [org], "config": config} + + +def prepare(args: argparse.Namespace) -> None: + root = Path(args.dir) + root.mkdir(parents=True, exist_ok=False) + loom, worker = root / "loom", root / "worker" + ca = _certificate(None, "Source worker capacity fixture root") + ca_pem = ca[1].public_bytes(Encoding.PEM) + listener = _certificate( + ca, "localhost", sans=("localhost",), purpose=ExtendedKeyUsageOID.SERVER_AUTH + ) + upstream = _certificate( + ca, HOSTS["resource"], sans=tuple(HOSTS.values()), purpose=ExtendedKeyUsageOID.SERVER_AUTH + ) + client = _certificate(ca, "loom-capacity-client", purpose=ExtendedKeyUsageOID.CLIENT_AUTH) + grant_key, enrollment_key = Ed25519PrivateKey.generate(), Ed25519PrivateKey.generate() + public = PublicFormat.SubjectPublicKeyInfo + + _write(loom / "worker-ca.pem", ca_pem, 0o644) + _write(loom / "client.pem", client[1].public_bytes(Encoding.PEM), 0o644) + _write(loom / "client-key.pem", _private_pem(client[0])) + _write(loom / "grant-key.pem", _private_pem(grant_key)) + _write( + loom / "enrollment-verifier.pem", + enrollment_key.public_key().public_bytes(Encoding.PEM, public), + 0o644, + ) + _write(worker / "ca.pem", ca_pem, 0o644) + for name, (key, cert) in (("listener", listener), ("upstream", upstream)): + _write(worker / f"{name}.pem", cert.public_bytes(Encoding.PEM), 0o644) + _write(worker / f"{name}-key.pem", _private_pem(key)) + _write(worker / "grant-verifier.pem", grant_key.public_key().public_bytes(Encoding.PEM, public)) + _write(worker / "enrollment-key.pem", _private_pem(enrollment_key)) + + worker_id = str(uuid4()) + ports = {"resource": args.resource_port, "mapped": args.mapped_port} + settings = { + "transport": "tls_proxy_unix", + "worker_id": worker_id, + "issuer": ISSUER, + # Never contacted: `serve` reads the accounts from memory instead. + "vault": {"origin": "https://credentials.invalid", "mount": "capacity"}, + "read_limits": { + "concurrent": args.concurrent, + "concurrent_per_org": args.concurrent_per_org, + "timeout_seconds": args.read_timeout_seconds, + "content_bytes": 100_000, + }, + "enrollment": True, + "profiles": [_profile(args.org, kind, ports[kind]) for kind in KINDS], + } + raw = json.dumps(settings).encode() + digests = dict(zip(KINDS, (p.digest for p in _parse_settings(raw).profiles), strict=True)) + _write(worker / "config.json", raw) + + routes = { + "version": 1, + "workers": [ + { + "worker_id": worker_id, + "origin": f"https://localhost:{args.worker_port}", + "issuer": ISSUER, + "trust_ca_file": "worker-ca.pem", + "client_certificate_file": "client.pem", + "client_key_file": "client-key.pem", + "grant_key_file": "grant-key.pem", + "enrollment_verifier_file": "enrollment-verifier.pem", + "profiles": { + args.org: [ + {"digest": digests[kind], "modes": ["live", "snapshot", "selected_refresh"]} + for kind in KINDS + ] + }, + "max_live_requests": 8, + } + ], + } + _write(loom / "routes.json", json.dumps(routes, indent=2).encode(), 0o644) + + accounts = [ + { + "collection": index, + "owner": f"capacity-owner-{index:03d}", + "kind": kind, + "connection_id": str(uuid4()), + } + for index in range(args.collections) + for kind in KINDS + ] + _write(worker / "accounts.json", json.dumps(accounts).encode()) + harness = { + "org": args.org, + "worker_id": worker_id, + "profiles": digests, + "accounts": accounts, + "collections": args.collections, + "routes_file": str((loom / "routes.json").resolve()), + "stats_url": f"http://127.0.0.1:{args.stats_port}/stats", + "faults_file": str((root / "faults.json").resolve()), + "read_timeout_seconds": args.read_timeout_seconds, + "worker": { + "concurrent": args.concurrent, + "concurrent_per_org": args.concurrent_per_org, + "ports": {"worker": args.worker_port, **ports, "stats": args.stats_port}, + }, + } + _write(root / "harness.json", json.dumps(harness, indent=2).encode(), 0o644) + print(json.dumps({"worker_id": worker_id, "profiles": digests})) + + +# --- serve --------------------------------------------------------------------------- + + +class _Accounts: + """The synthetic accounts, read as the KV backend's records would be.""" + + def __init__(self, records: dict[UUID, CredentialRecord], latency_s: float) -> None: + self._records = records + self._latency = latency_s + + async def get(self, connection_id: UUID) -> CredentialRecord: + if self._latency: + await asyncio.sleep(self._latency) + record = self._records.get(connection_id) + if record is None: + raise ReadFailure("reconnect") + return record + + +def _records( + root: Path, org: str, worker_id: UUID, digests: dict[str, str], ports: dict[str, int] +) -> dict[UUID, CredentialRecord]: + records = {} + for account in json.loads((root / "worker/accounts.json").read_text()): + connection = UUID(account["connection_id"]) + kind = account["kind"] + records[connection] = CredentialRecord( + binding=ConnectionBinding( + worker_id=worker_id, + org=org, + owner=account["owner"], + connection_id=connection, + generation=1, + profile_digest=digests[kind], + ), + state="active", + auth="bearer", + audience=f"https://{HOSTS[kind]}:{ports[kind]}/mcp", + token=SecretStr(f"capacity-{connection}"), + expires_at=int(time.time()) + 86_400, + ) + return records + + +class _Faults: + """`faults.json`, read again whenever its modification time changes.""" + + def __init__(self, path: Path) -> None: + self._path = path + self._stamp: int | None = None + self._faults: dict[str, str] = {} + + def of(self, resource_id: str) -> str: + try: + stamp = self._path.stat().st_mtime_ns + except FileNotFoundError: + return "" + if stamp != self._stamp: + loaded = json.loads(self._path.read_text()) + if not isinstance(loaded, dict) or not set(loaded.values()) <= set(FAULTS): + raise ValueError("invalid faults file") + self._faults, self._stamp = loaded, stamp + return self._faults.get(resource_id, "") + + +class _Stats: + def __init__(self) -> None: + self.counts: dict[str, dict[str, int]] = {} + self.samples: dict[str, list[float]] = {} + + def record(self, route: str, status: int, seconds: float) -> None: + by_status = self.counts.setdefault(route, {}) + by_status[str(status)] = by_status.get(str(status), 0) + 1 + self.samples.setdefault(route, []).append(round(seconds * 1000, 3)) + + def drain(self) -> dict[str, Any]: + samples, self.samples = self.samples, {} + return {"counts": self.counts, "duration_ms": samples} + + +def _measured(app: ASGIApp, stats: _Stats) -> ASGIApp: + async def measured(scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": + await app(scope, receive, send) + return + started, status = time.monotonic(), 0 + + async def observe(message: Message) -> None: + nonlocal status + if message["type"] == "http.response.start": + status = message["status"] + await send(message) + + try: + await app(scope, receive, observe) + finally: + stats.record(scope["path"], status, time.monotonic() - started) + + return measured + + +def _sdk_server(kind: str, faults: _Faults) -> StreamableHTTPSessionManager: + sdk: Server[Any, Any] = Server(f"capacity-{kind}") + + def text(resource_id: str) -> str: + # An empty document: the worker answers `unsupported`. + return "" if faults.of(resource_id) == "unsupported" else text_of(resource_id) + + if kind == "resource": + + @sdk.read_resource() + async def read_resource(uri: AnyUrl) -> str: + return text(str(uri)) + + else: + + @sdk.list_tools() + async def list_tools() -> list[types.Tool]: + return [ + types.Tool( + name="read_document", inputSchema=INPUT_SCHEMA, outputSchema=OUTPUT_SCHEMA + ) + ] + + @sdk.call_tool() + async def call_tool(name: str, arguments: dict[str, Any]) -> dict[str, str]: + resource_id = str(arguments["id"]) + return { + "id": resource_id, + "title": resource_id, + "uri": resource_id, + "text": text(resource_id), + } + + return StreamableHTTPSessionManager(app=sdk, json_response=kind == "mapped", stateless=False) + + +def _read_target(kind: str, body: bytes) -> str | None: + """The resource a JSON-RPC request reads, or None for any other request.""" + try: + message = json.loads(body) + except ValueError: + return None + if not isinstance(message, dict) or not isinstance(message.get("params"), dict): + return None + params = message["params"] + if kind == "resource" and message.get("method") == "resources/read": + return str(params.get("uri")) + if kind == "mapped" and message.get("method") == "tools/call": + arguments = params.get("arguments") + return str(arguments.get("id")) if isinstance(arguments, dict) else None + return None + + +def _upstream( + kind: str, + manager: StreamableHTTPSessionManager, + faults: _Faults, + *, + latency_s: float, + slow_s: float, + stall_s: float, +) -> ASGIApp: + async def app(scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": + return + request = Request(scope, receive) + if not request.headers.get("authorization", "").startswith("Bearer capacity-"): + await Response(status_code=401)(scope, receive, send) + return + body = await request.body() if request.method == "POST" else b"" + target = _read_target(kind, body) + fault = faults.of(target) if target is not None else "" + if target is not None: + if latency_s: + await asyncio.sleep(latency_s) + if fault == "denied": + await Response(status_code=403)(scope, receive, send) + return + if fault == "unavailable": + await Response(status_code=503)(scope, receive, send) + return + if fault in ("slow", "timeout"): + await asyncio.sleep(slow_s if fault == "slow" else stall_s) + replayed = False + + async def replay() -> Message: + nonlocal replayed + if request.method != "POST" or replayed: + return await receive() + replayed = True + return {"type": "http.request", "body": body, "more_body": False} + + await manager.handle_request(scope, replay, send) + + return app + + +@contextmanager +def _trusted_fixture_roots(root: Path) -> Iterator[None]: + """The worker's outbound client trusts its public roots; add the fixture CA to them.""" + bundle = Path(certifi.where()) + combined = root / "worker/public-and-fixture-roots.pem" + combined.write_bytes(bundle.read_bytes() + b"\n" + (root / "worker/ca.pem").read_bytes()) + original = ssl.SSLContext.load_verify_locations + + def load( + context: ssl.SSLContext, + cafile: str | os.PathLike[str] | None = None, + capath: str | os.PathLike[str] | None = None, + cadata: str | bytes | None = None, + ) -> None: + if cafile is not None and Path(cafile) == bundle: + cafile = str(combined) + original(context, cafile=cafile, capath=capath, cadata=cadata) + + ssl.SSLContext.load_verify_locations = load + try: + yield + finally: + ssl.SSLContext.load_verify_locations = original + + +class _Server(uvicorn.Server): + @contextmanager + def capture_signals(self) -> Iterator[None]: + yield # this process handles SIGTERM itself and stops every listener + + +def _config(app: ASGIApp, port: int, **tls: Any) -> uvicorn.Config: + return uvicorn.Config( + app, + host="127.0.0.1", + port=port, + http="h11", + ws="none", + lifespan="off", + log_config=None, + access_log=False, + proxy_headers=False, + server_header=False, + timeout_graceful_shutdown=3, + **tls, + ) + + +async def serve(args: argparse.Namespace) -> None: + root = Path(args.dir) + harness = json.loads((root / "harness.json").read_text()) + settings = _parse_settings((root / "worker/config.json").read_bytes()) + worker = root / "worker" + verifier = load_pem_public_key((worker / "grant-verifier.pem").read_bytes()) + signer = load_pem_private_key((worker / "enrollment-key.pem").read_bytes(), password=None) + assert isinstance(signer, Ed25519PrivateKey) and isinstance(verifier, Ed25519PublicKey) + ports = harness["worker"]["ports"] + store = _Accounts( + _records(root, harness["org"], settings.worker_id, harness["profiles"], ports), + args.credential_latency_ms / 1000, + ) + backend = DirectBackend(store, settings.profiles) + service = ReadService( + worker_id=settings.worker_id, + issuer=settings.issuer, + verifier=verifier, + backend=backend, + limits=settings.read_limits, + ) + enrollment = EnrollmentService( + worker_id=settings.worker_id, + issuer=settings.issuer, + verifier=verifier, + signer=signer, + backend=backend, + ) + stats = _Stats() + + async def stats_app(scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] == "http": + await JSONResponse(stats.drain())(scope, receive, send) + + pinned = {host: ipaddress.IPv4Address("127.0.0.1") for host in HOSTS.values()} + + async def resolve(host: str) -> ipaddress.IPv4Address | None: + return pinned.get(host) + + mcp_client.resolve_public_address = resolve + faults = _Faults(Path(harness["faults_file"])) + managers = {kind: _sdk_server(kind, faults) for kind in KINDS} + stall = float(harness["read_timeout_seconds"]) * 2 + tls = { + "ssl_certfile": str(worker / "upstream.pem"), + "ssl_keyfile": str(worker / "upstream-key.pem"), + } + servers = [ + _Server( + _config( + _measured(create_app(service, enrollment), stats), + ports["worker"], + ssl_certfile=str(worker / "listener.pem"), + ssl_keyfile=str(worker / "listener-key.pem"), + ssl_ca_certs=str(worker / "ca.pem"), + ssl_cert_reqs=ssl.CERT_REQUIRED, + ) + ), + *( + _Server( + _config( + _upstream( + kind, + managers[kind], + faults, + latency_s=args.upstream_latency_ms / 1000, + slow_s=args.slow_ms / 1000, + stall_s=stall, + ), + ports[kind], + **tls, + ) + ) + for kind in KINDS + ), + _Server(_config(stats_app, ports["stats"])), + ] + stop = asyncio.Event() + loop = asyncio.get_running_loop() + for signum in (signal.SIGTERM, signal.SIGINT): + loop.add_signal_handler(signum, stop.set) + with _trusted_fixture_roots(root): + async with AsyncExitStack() as stack: + for manager in managers.values(): + await stack.enter_async_context(manager.run()) + tasks = [asyncio.create_task(server.serve()) for server in servers] + async with asyncio.timeout(30): + while not all(server.started for server in servers): + for task in tasks: + if task.done(): + task.result() + raise SystemExit("a fixture listener exited before startup") + await asyncio.sleep(0.05) + (root / "ready").touch() + print("fixture ready", flush=True) + await stop.wait() + for server in servers: + server.should_exit = True + await asyncio.gather(*tasks) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + sub = parser.add_subparsers(dest="command", required=True) + p = sub.add_parser("prepare", help="Write the keys, configuration and harness inputs") + p.add_argument("--dir", required=True, help="A new directory for the fixture files") + p.add_argument("--org", required=True) + p.add_argument("--collections", type=int, default=4) + p.add_argument("--concurrent", type=int, default=8, help="worker read_limits.concurrent") + p.add_argument("--concurrent-per-org", type=int, default=4) + p.add_argument("--read-timeout-seconds", type=int, default=6) + p.add_argument("--worker-port", type=int, default=18601) + p.add_argument("--resource-port", type=int, default=18602) + p.add_argument("--mapped-port", type=int, default=18603) + p.add_argument("--stats-port", type=int, default=18604) + s = sub.add_parser("serve", help="Run the worker, the upstreams and the stats endpoint") + s.add_argument("--dir", required=True) + s.add_argument("--upstream-latency-ms", type=float, default=20.0) + s.add_argument("--credential-latency-ms", type=float, default=2.0) + s.add_argument("--slow-ms", type=float, default=1500.0) + args = parser.parse_args() + if args.command == "prepare": + if not 1 <= args.collections <= 64: + parser.error("--collections must be 1 to 64") + # Setup's selection proof runs two checks at once; the wire budget caps it at 16. + if not 2 <= args.concurrent_per_org <= args.concurrent <= 16: + parser.error("need 2 <= --concurrent-per-org <= --concurrent <= 16") + prepare(args) + else: + asyncio.run(serve(args)) + + +if __name__ == "__main__": + main() diff --git a/docs/architecture/mcp-source-worker-boundary.md b/docs/architecture/mcp-source-worker-boundary.md index dae2bde286..43f6157e29 100644 --- a/docs/architecture/mcp-source-worker-boundary.md +++ b/docs/architecture/mcp-source-worker-boundary.md @@ -424,7 +424,9 @@ a turn the bound cuts reads `pass bound reached`, and a source the phase does no keeps its last state. A `selected_refresh` copy is read again at most once a pass and spends the mirror document bound even when its digest is unchanged, so `interval_seconds` is the least time between copies, not a schedule. This feature is -experimental and off by default. +experimental and off by default. A dispatched workflow measures the bound on one hosted +runner ([source worker copy +capacity](../benchmarks/running.md#source-worker-copy-capacity)). Of the worker's answers, only its report that the upstream refused the account retires a copy at once: a `403` whose body is exactly diff --git a/docs/benchmarks/running.md b/docs/benchmarks/running.md index e34dad3fab..311ad81118 100644 --- a/docs/benchmarks/running.md +++ b/docs/benchmarks/running.md @@ -348,6 +348,54 @@ make bench OP=memory.search C=5 D=60 # point --namespace at one the rows. `scripts/ops/benchmark.py` records the base URL, build commit, schema version and assigned traffic class; exit 0 means at least one call succeeded. +### Source worker copy capacity + +The `MCP source worker copy capacity` workflow +(`.github/workflows/mcp-source-worker-capacity.yml`) measures how many owner-only worker +copies one Loom process keeps served, the bound the [stored copies +section](../architecture/mcp-source-worker-boundary.md#stored-copies-and-refresh) +describes. It runs only when dispatched, on one GitHub-hosted runner, and calls no model, +provider or external service. It starts ClickHouse and Postgres, Loom from the checkout +with `LOOM_KNOWLEDGE_SOURCE_WORKER_COPIES_ENABLED` on and its own sync worker off, and +`bench/source_worker_copies_fixture.py`: the bundled source worker's read and enrollment +service behind an mTLS listener, an in-memory credential store in place of the KV +backend, and two owned MCP SDK upstreams, one read with `resources/read` and one through a +mapped tool. `bench/source_worker_copies.py` then sets up the sources through the +operations a person would call (collection, grant, profile approval, account enrollment, +preview and registration), with a test client that declares session protection, and runs a +fixed number of sync passes in its own process. + +Dispatch it from the Actions tab, or with +`gh workflow run mcp-source-worker-capacity.yml -f sources=200 -f resources=20`. The inputs +set the number of sources, resources per source, collections and passes, the time between +passes, `LOOM_KNOWLEDGE_SOURCE_SYNC_MAX_PASS_SECONDS`, +`LOOM_KNOWLEDGE_SOURCE_ACL_STALE_SECONDS`, `LOOM_KNOWLEDGE_SOURCE_MIRROR_DOCUMENTS_PER_PASS`, +the refresh interval of the `selected_refresh` sources, the upstream and credential +latencies, the worker's read limits and the faults (resources whose upstream denies the +read, returns an empty document, stalls past the read deadline, answers 503 or answers +slowly; each applies once setup is done). The defaults shorten the stale window and the +pass bound so a run reaches both within its time limit. + +The run uploads `source-worker-copies.json` (schema `loom.bench.source_worker_copies.v1`) +with the server and fixture logs. Per pass, and in total: + +- `copies` and `checks`: the worker requests the sync made, each timed in Loom from its + authority read to the check after the reply, with latency percentiles over the + confirmed ones and a count per outcome (`confirmed`, `denied_upstream`, `denied`, + `unsupported`, `timeout`, `overloaded`, `unavailable`, `reconnect`). +- `confirmed`: copies written or rechecked and checks that confirmed access. +- `written` and `retired`: copies stored and removed. +- `pass_bound_marks` and `cut`: turns the pass bound stopped, and passes it cut. +- `listing`: sources whose recorded listing is younger than the stale window at the end of + the pass (`served`), older (`unserved`) or never recorded (`never`); `lapses` counts + sources served at the previous pass and not at this one. +- `overloaded` and `worker.status_429`: refusals for lack of a slot, as Loom saw them and + as the worker answered them, with the worker's own request counts and durations by route. + +The driver exits 1 only for a harness error, which `harness_errors` names; the figures +never fail the run. Unit tests for the driver's configuration, layout, percentiles and +metrics shape are in `tests/unit/test_bench_source_worker_copies.py`. + ### Everything else Every other harness is `python bench/.py --base-url … --token …` plus its dataset diff --git a/tests/unit/test_bench_source_worker_copies.py b/tests/unit/test_bench_source_worker_copies.py new file mode 100644 index 0000000000..4c6bfe6143 --- /dev/null +++ b/tests/unit/test_bench_source_worker_copies.py @@ -0,0 +1,269 @@ +"""Pure parts of the source worker copy capacity harness: its configuration, the source and +fault layout, the percentile math, the listing state and the fixed metrics shape.""" + +from __future__ import annotations + +import inspect +import json +from datetime import UTC, datetime, timedelta +from pathlib import Path + +import pytest + +from bench.source_worker_copies import ( + FAULT_KINDS, + SCHEMA, + SETUP_OPS, + SUMMARY_KEYS, + Config, + Exchange, + PassRecord, + TurnRecord, + build_metrics, + count_diff, + listing_state, + parse_config, + parse_faults, + percentile, + plan_faults, + plan_sources, + summarize, + validate_metrics, +) + +_REQUIRED = ["--base-url", "http://127.0.0.1:7777", "--harness", "h.json", "--out", "m.json"] + + +def test_faults_parse_to_every_kind(): + assert parse_faults("") == dict.fromkeys(FAULT_KINDS, 0) + assert parse_faults("none") == dict.fromkeys(FAULT_KINDS, 0) + assert parse_faults("denied=1, slow=2,denied=1") == { + **dict.fromkeys(FAULT_KINDS, 0), + "denied": 2, + "slow": 2, + } + + +@pytest.mark.parametrize("spec", ["broken=1", "denied", "denied=-1", "denied=x", "slow=1.5"]) +def test_faults_refuse_an_unknown_kind_or_count(spec): + with pytest.raises(ValueError): + parse_faults(spec) + + +def test_config_defaults(): + config = parse_config(_REQUIRED) + assert config == Config( + base_url="http://127.0.0.1:7777", + harness=Path("h.json"), + out=Path("m.json"), + sources=40, + resources=20, + passes=6, + pass_interval=60.0, + refresh_interval=300, + faults={ + **dict.fromkeys(FAULT_KINDS, 0), + "denied": 1, + "unsupported": 1, + "timeout": 1, + "unavailable": 1, + "slow": 2, + }, + ) + + +@pytest.mark.parametrize( + "extra", + [ + ["--sources", "0"], + ["--sources", "2001"], + ["--resources", "241"], + ["--passes", "0"], + ["--pass-interval", "-1"], + ["--refresh-interval", "299"], + ["--faults", "nope=1"], + ["--sources", "1", "--resources", "2", "--faults", "denied=3"], + ], +) +def test_config_refuses_out_of_range_inputs(extra, capsys): + with pytest.raises(SystemExit) as stopped: + parse_config([*_REQUIRED, *extra]) + assert stopped.value.code == 2 + assert "error" in capsys.readouterr().err + + +def test_sources_cover_both_modes_and_profiles_in_every_collection(): + from server.knowledge.domain.mcp_identity import ResourceIdentity + from server.knowledge.domain.mcp_worker_setup import checked_worker_selection + from server.tracker.domain.sources import SOURCE_NAME_RE + + plans = plan_sources(8, 3, 2) + assert [(p.mode, p.kind, p.collection) for p in plans[:4]] == [ + ("snapshot", "resource", 0), + ("selected_refresh", "resource", 1), + ("snapshot", "mapped", 0), + ("selected_refresh", "mapped", 1), + ] + assert len({p.name for p in plans}) == 8 + ids = [rid for p in plans for rid in p.resources] + assert len(set(ids)) == 24 + for plan in plans: + assert SOURCE_NAME_RE.fullmatch(plan.name) + selection = tuple(ResourceIdentity(type="resource", id=rid) for rid in plan.resources) + assert checked_worker_selection(selection, plan.mode) == selection + + +def test_faults_land_on_distinct_sources_first_and_never_on_source_zero_first(): + plans = plan_sources(4, 2, 1) + faults = plan_faults(plans, {"denied": 1, "unsupported": 1, "timeout": 1, "slow": 1}) + assert faults == { + plans[1].resources[0]: "denied", + plans[2].resources[0]: "unsupported", + plans[3].resources[0]: "timeout", + plans[0].resources[0]: "slow", + } + # Past one per source, the second resource of each takes the next. + more = plan_faults(plans, {"unavailable": 5}) + assert list(more) == [*(p.resources[0] for p in (*plans[1:], plans[0])), plans[1].resources[1]] + assert plan_faults(plans, dict.fromkeys(FAULT_KINDS, 0)) == {} + with pytest.raises(ValueError): + plan_faults(plans, {"denied": 9}) + + +def test_percentile_is_nearest_rank(): + values = [float(v) for v in range(1, 11)] + assert percentile(values, 50) == 5.0 + assert percentile(values, 90) == 9.0 + assert percentile(values, 99) == 10.0 + assert percentile(values, 100) == 10.0 + assert percentile([7.0], 50) == 7.0 + with pytest.raises(ValueError): + percentile([], 50) + with pytest.raises(ValueError): + percentile(values, 0) + + +def test_summary_keys_are_fixed_with_or_without_values(): + assert tuple(summarize([])) == SUMMARY_KEYS + assert set(summarize([]).values()) == {0, None} + summary = summarize([3.0, 1.0, 2.0, 10.0]) + assert tuple(summary) == SUMMARY_KEYS + assert summary == {"count": 4, "mean": 4.0, "p50": 2.0, "p90": 10.0, "p99": 10.0, "max": 10.0} + + +def test_counters_diff_keeps_only_what_grew(): + before = {"/v1/live": {"200": 3}, "/v1/check-access": {"200": 5, "429": 1}} + after = { + "/v1/live": {"200": 4}, + "/v1/check-access": {"200": 5, "429": 3}, + "/v1/enroll": {"200": 1}, + } + assert count_diff(after, before) == { + "/v1/live": {"200": 1}, + "/v1/check-access": {"429": 2}, + "/v1/enroll": {"200": 1}, + } + + +def test_listing_is_served_inside_the_stale_window(): + at = datetime(2030, 1, 1, tzinfo=UTC) + listed = { + "fresh": (at - timedelta(seconds=59)).isoformat(), + "edge": (at - timedelta(seconds=60)).isoformat(), + } + state = listing_state(listed, ["fresh", "edge", "none"], at, 60) + assert state == {"served": ["fresh"], "unserved": ["edge"], "never": ["none"]} + + +def _config() -> Config: + return parse_config(_REQUIRED) + + +def _record() -> PassRecord: + record = PassRecord(index=0, started_s=0.0, seconds=12.5) + record.exchanges = [ + Exchange("cap00000", "copy", 40.0, "confirmed"), + Exchange("cap00000", "check", 10.0, "confirmed"), + Exchange("cap00001", "check", 30.0, "overloaded"), + Exchange("cap00001", "check", 20.0, "denied_upstream"), + ] + record.turns = [ + TurnRecord("cap00000", "ok", False, 2, 1, 0, "", 1.0), + TurnRecord("cap00001", "overloaded", True, 2, 0, 1, "", 2.0), + ] + record.listing = {"served": ["cap00000"], "unserved": ["cap00001"], "never": []} + record.lapsed = ["cap00001"] + record.worker_counts = {"/v1/check-access": {"200": 1, "429": 1}} + record.worker_ms = {"/v1/check-access": [4.0, 6.0]} + return record + + +def test_metrics_carry_the_fixed_shape_and_the_pass_figures(): + metrics = build_metrics( + config=_config(), environment={}, setup={}, passes=[_record()], errors=[] + ) + assert validate_metrics(metrics) == [] + assert metrics["schema"] == SCHEMA + json.dumps(metrics) # serializable as written + entry = metrics["passes"][0] + assert entry["copies"]["confirmed"] == 1 and entry["checks"]["attempted"] == 3 + assert entry["checks"]["outcomes"] == {"confirmed": 1, "denied_upstream": 1, "overloaded": 1} + assert entry["checks"]["latency_ms"]["count"] == 1 # refusals are not timed as checks + assert entry["pass_bound_marks"] == 1 and entry["overloaded"] == 1 + assert entry["listing"]["lapses"] == 1 and entry["worker"]["status_429"] == 1 + assert entry["written"] == 1 and entry["retired"] == 1 + totals = metrics["totals"] + assert totals["confirmed"] == 2 and totals["worker_429"] == 1 and totals["lapses"] == 1 + assert totals["worker_latency_ms"]["/v1/check-access"]["p50"] == 4.0 + + +def test_metrics_without_passes_still_conform(): + metrics = build_metrics( + config=_config(), environment={}, setup={}, passes=[], errors=["setup failed"] + ) + assert validate_metrics(metrics) == [] + assert metrics["totals"]["copy_latency_ms"]["count"] == 0 + + +def test_validation_names_each_departure(): + good = build_metrics(config=_config(), environment={}, setup={}, passes=[_record()], errors=[]) + missing = json.loads(json.dumps(good)) + del missing["totals"]["lapses"] + assert any("totals" in p for p in validate_metrics(missing)) + flagged = json.loads(json.dumps(good)) + flagged["passes"][0]["turns"] = True + assert validate_metrics(flagged) == ["passes[0].turns: expected int"] + renamed = json.loads(json.dumps(good)) + renamed["schema"] = "other" + assert validate_metrics(renamed) == [f"schema: expected {SCHEMA}"] + summary = json.loads(json.dumps(good)) + summary["totals"]["check_latency_ms"] = {"count": 0} + assert validate_metrics(summary) == [ + f"totals.check_latency_ms: summary keys must be {SUMMARY_KEYS}" + ] + assert validate_metrics([]) == ["metrics: not an object"] + + +def test_the_timed_sync_seams_exist(): + """The harness wraps these to time each worker request and each turn.""" + from server.knowledge.app import source_sync, source_sync_worker + + exchange = inspect.signature(source_sync_worker._Turn._exchange) + assert list(exchange.parameters) == ["self", "item", "content"] + assert exchange.parameters["content"].kind is inspect.Parameter.KEYWORD_ONLY + assert list(inspect.signature(source_sync_worker.turn).parameters) == ["src", "state", "run"] + assert isinstance(source_sync_worker._LISTED, str) + # The sync looks the turn up at call time, so the wrapped one runs. + assert "return source_sync_worker.turn" in inspect.getsource(source_sync._turn_of) + assert list(inspect.signature(source_sync.run_sync).parameters) == [ + "org", + "namespace", + "only", + "full", + ] + + +def test_setup_ops_are_served(): + from server.operations.registry import OPERATIONS_BY_NAME + + assert set(SETUP_OPS) <= set(OPERATIONS_BY_NAME) From 8f5fde3ae5ed0dc2e52b59d3e2bb315360e778a2 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sat, 5 Dec 2026 02:29:17 +0000 Subject: [PATCH 2/4] The capacity driver counts unreached sources as a cut pass and keeps its document through a stopped run Every worker source is mirrored, so the pass result never records the mirrored phase running out of time. The driver now counts the sources with no turn in a pass (`sources_not_reached`, per pass and in total) and calls a pass cut when one is left or a turn was cut. It writes the metrics document after every pass by replacing the file whole, refuses passes times the pass interval beyond the Measure step's budget less a setup allowance, records an HTTP failure or an unreadable harness file as a harness error in the document instead of exiting with a traceback, and reports per-turn time percentiles in place of turn fields it never emitted. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- .../workflows/mcp-source-worker-capacity.yml | 6 +- bench/source_worker_copies.py | 159 ++++++++++++----- docs/benchmarks/running.md | 16 +- tests/unit/test_bench_source_worker_copies.py | 161 +++++++++++++++++- 4 files changed, 287 insertions(+), 55 deletions(-) diff --git a/.github/workflows/mcp-source-worker-capacity.yml b/.github/workflows/mcp-source-worker-capacity.yml index 749a6cfd98..6a57803cfe 100644 --- a/.github/workflows/mcp-source-worker-capacity.yml +++ b/.github/workflows/mcp-source-worker-capacity.yml @@ -21,11 +21,11 @@ on: type: number default: 4 passes: - description: Sync passes to run (1 to 100) + description: Sync passes to run (1 to 100; passes times pass_interval at most 3600 s) type: number default: 8 pass_interval: - description: Seconds from one pass's start to the next (0 runs them back to back) + description: Seconds from one pass's start to the next (0 back to back; see passes) type: number default: 60 max_pass_seconds: @@ -196,6 +196,8 @@ jobs: echo "the server never became healthy" >&2 tail -100 server.log >&2 exit 1 + # STEP_BUDGET_SECONDS in the driver: it refuses passes that cannot fit, and writes its + # document after each pass so a run this limit stops keeps the passes it finished. - name: Measure timeout-minutes: 75 run: | diff --git a/bench/source_worker_copies.py b/bench/source_worker_copies.py index f27ab400aa..a30f3c886c 100644 --- a/bench/source_worker_copies.py +++ b/bench/source_worker_copies.py @@ -21,26 +21,32 @@ `--resources` resources. After setup the driver writes the fixture's fault table (`--faults`, at most one fault per -resource, never on a source's first resource when another source can take it) and runs -`--passes` sync passes in this process, each the pass the `knowledge_source_sync` worker -runs (`run_sync()` over every source), `--pass-interval` seconds apart from start to start -or back to back when a pass overruns. The server runs with that worker off, so these are -the only passes. Per pass it records: +resource: the first resource of sources 1, 2, ... in turn, then of source 0, then each +source's second resource, so source 0's first resource is the last first resource to take +one) and runs `--passes` sync passes in this process, each the pass the +`knowledge_source_sync` worker runs (`run_sync()` over every source), `--pass-interval` +seconds apart from start to start or back to back when a pass overruns. The server runs +with that worker off, so these are the only passes. `passes * pass_interval` may be at +most `PASS_BUDGET_SECONDS`, the workflow step's time less `SETUP_ALLOWANCE_SECONDS` for +setup; a pass that runs past its interval extends the run. Per pass it records: - every worker request a turn makes, timed from its authority read to its last check (`copy` reads content, `check` confirms access), and its answer: confirmed, or the refusal reason (`overloaded` is the worker's 429 or this process's channel share); -- each source's turn: its status, whether the pass bound cut it, and the listing it - recorded; +- each source's turn: its status, whether the pass bound cut it, its time, the copies it + wrote and retired, and the listing it recorded; a source with no turn in the pass is one + the pass did not reach, and a pass with such a source or a cut turn is cut; - listing lapses: a source is served while its recorded listing is younger than `knowledge_source_acl_stale_seconds` at the pass's end; a lapse is a source that was served and is not; - the worker's own request counts by route and HTTP status, and its request durations. It writes one JSON document of fixed shape (`SCHEMA`, checked by `validate_metrics`) to -`--out`. It exits 1 only on a harness error (a setup step that did not answer `ok`, a -pass that raised, a fixture that could not be read) and records the error in the -document; capacity figures never fail the run. +`--out` after every pass, replacing the last one whole, and once more at the end, so a run +stopped by its time limit keeps the passes it finished. It exits 1 only on a harness error +(a setup step that did not answer `ok`, an HTTP failure, a pass that raised, a fixture that +could not be read) and records the error in the document; capacity figures never fail the +run. PYTHONPATH=$PWD .venv/bin/python bench/source_worker_copies.py \\ --base-url http://127.0.0.1:7777 --harness "$FIXTURE/harness.json" \\ @@ -53,6 +59,7 @@ import asyncio import json import math +import os import sys import time import uuid @@ -63,6 +70,8 @@ from pathlib import Path from typing import Any +import httpx + SCHEMA = "loom.bench.source_worker_copies.v1" FAULT_KINDS = ("denied", "unsupported", "timeout", "unavailable", "slow") KINDS = ("resource", "mapped") @@ -81,6 +90,10 @@ _ADMIN = "capacity-admin" # Every percentile summary has exactly these keys. SUMMARY_KEYS = ("count", "mean", "p50", "p90", "p99", "max") +# The workflow's Measure step runs 75 minutes; setup gets 15 of them, the passes the rest. +STEP_BUDGET_SECONDS = 75 * 60 +SETUP_ALLOWANCE_SECONDS = 15 * 60 +PASS_BUDGET_SECONDS = STEP_BUDGET_SECONDS - SETUP_ALLOWANCE_SECONDS # --- pure parts ------------------------------------------------------------------------ @@ -155,6 +168,11 @@ def parse_config(argv: list[str] | None = None) -> Config: sum(faults.values()) <= args.sources * args.resources, "--faults names more resources than the sources select", ), + ( + args.passes * args.pass_interval <= PASS_BUDGET_SECONDS, + f"--passes times --pass-interval must be at most {PASS_BUDGET_SECONDS} seconds " + f"(the {STEP_BUDGET_SECONDS} s step less {SETUP_ALLOWANCE_SECONDS} s for setup)", + ), ) for ok, message in checks: if not ok: @@ -274,7 +292,6 @@ def listing_state( class Exchange: """One worker request a turn made.""" - source: str operation: str # "copy" or "check" ms: float outcome: str # "confirmed" or the refusal reason @@ -285,10 +302,8 @@ class TurnRecord: source: str status: str cut: bool - seen: int changed: int removed: int - note: str seconds: float @@ -297,9 +312,10 @@ class PassRecord: index: int started_s: float seconds: float + # The sources the pass had to visit: one without a turn is one it did not reach. + sources: int exchanges: list[Exchange] = field(default_factory=list) turns: list[TurnRecord] = field(default_factory=list) - cut: bool = False errors: int = 0 listing: dict[str, list[str]] = field(default_factory=dict) lapsed: list[str] = field(default_factory=list) @@ -321,15 +337,28 @@ def _worker_429(counts: dict[str, dict[str, int]]) -> int: return sum(statuses.get("429", 0) for statuses in counts.values()) +def not_reached(record: PassRecord) -> int: + """Sources the pass ended before: every source is mirrored, and the mirrored phase stops + starting turns once its budget is spent, which `PassResult.cut` does not record.""" + return max(0, record.sources - len({t.source for t in record.turns})) + + +def pass_cut(record: PassRecord) -> bool: + """The pass bound stopped the pass: a source it did not reach, or a turn it cut.""" + return not_reached(record) > 0 or any(t.cut for t in record.turns) + + def pass_metrics(record: PassRecord) -> dict[str, Any]: exchanges = record.exchanges return { "index": record.index, "started_s": round(record.started_s, 3), "seconds": round(record.seconds, 3), - "cut": record.cut, + "cut": pass_cut(record), + "sources_not_reached": not_reached(record), "errors": record.errors, "turns": len(record.turns), + "turn_seconds": summarize(t.seconds for t in record.turns), "turn_statuses": dict(sorted(Counter(t.status for t in record.turns).items())), "pass_bound_marks": sum(t.cut for t in record.turns), "copies": _exchange_summary(exchanges, "copy"), @@ -392,7 +421,9 @@ def build_metrics( route: summarize(values) for route, values in sorted(worker_ms.items()) }, "pass_bound_marks": sum(t.cut for p in passes for t in p.turns), - "passes_cut": sum(p.cut for p in passes), + "passes_cut": sum(pass_cut(p) for p in passes), + "sources_not_reached": sum(not_reached(p) for p in passes), + "turn_seconds": summarize(t.seconds for p in passes for t in p.turns), "lapses": sum(len(p.lapsed) for p in passes), }, "harness_errors": list(errors), @@ -413,8 +444,10 @@ def build_metrics( "started_s": float, "seconds": float, "cut": bool, + "sources_not_reached": int, "errors": int, "turns": int, + "turn_seconds": dict, "turn_statuses": dict, "pass_bound_marks": int, "copies": dict, @@ -437,6 +470,8 @@ def build_metrics( "worker_latency_ms": dict, "pass_bound_marks": int, "passes_cut": int, + "sources_not_reached": int, + "turn_seconds": dict, "lapses": int, } @@ -481,6 +516,7 @@ def validate_metrics(doc: Any) -> list[str]: problems += found if found: continue + problems += _check_summary(f"{where}.turn_seconds", entry["turn_seconds"]) for part in ("copies", "checks"): problems += _check_summary(f"{where}.{part}.latency_ms", entry[part].get("latency_ms")) for route, summary in entry["worker"].get("latency_ms", {}).items(): @@ -488,7 +524,7 @@ def validate_metrics(doc: Any) -> list[str]: totals = doc["totals"] problems += _check_fields("totals", totals, _TOTALS) if not problems: - for name in ("copy_latency_ms", "check_latency_ms"): + for name in ("copy_latency_ms", "check_latency_ms", "turn_seconds"): problems += _check_summary(f"totals.{name}", totals[name]) if totals["passes"] != len(doc["passes"]): problems.append("totals.passes: does not match the pass list") @@ -707,7 +743,6 @@ async def timed_exchange(self: Any, item: Any, *, content: bool) -> Any: if recorder.current is not None: recorder.current.exchanges.append( Exchange( - self.src.name, "copy" if content else "check", (time.perf_counter() - started) * 1000, outcome, @@ -726,10 +761,8 @@ async def timed_turn(src: Any, state: Any, run: Any) -> Any: src.name, result.status, result.cut, - result.documents_seen, result.changed, result.removed, - result.note, time.perf_counter() - started, ) ) @@ -752,8 +785,14 @@ async def _worker_stats(client: Any, url: str) -> dict[str, Any]: async def run_passes( - config: Config, harness: dict[str, Any], plans: list[SourcePlan], client: Any -) -> list[PassRecord]: + config: Config, + harness: dict[str, Any], + plans: list[SourcePlan], + client: Any, + passes: list[PassRecord], + on_pass: Callable[[], None], +) -> None: + """Run the passes, appending each to `passes` and calling `on_pass` after it.""" from server.core.ch import set_query_tag from server.knowledge.app.mcp_worker_runtime import source_worker_runtime from server.knowledge.app.source_sync import run_sync @@ -763,7 +802,6 @@ async def run_passes( recorder = _Recorder() restore = recorder.install() names = [plan.name for plan in plans] - passes: list[PassRecord] = [] served_before: set[str] = set() counts = (await _worker_stats(client, harness["stats_url"]))["counts"] try: @@ -773,7 +811,12 @@ async def run_passes( wait = origin + index * config.pass_interval - time.monotonic() if wait > 0: await asyncio.sleep(wait) - record = PassRecord(index=index, started_s=time.monotonic() - origin, seconds=0) + record = PassRecord( + index=index, + started_s=time.monotonic() - origin, + seconds=0, + sources=len(plans), + ) recorder.current = record started = time.monotonic() try: @@ -785,7 +828,7 @@ async def run_passes( finally: recorder.current = None record.seconds = time.monotonic() - started - record.cut, record.errors = result.cut, len(result.errors) + record.errors = len(result.errors) record.listing = listing_state( recorder.listed, names, @@ -800,10 +843,10 @@ async def run_passes( record.worker_ms = stats["duration_ms"] counts = stats["counts"] passes.append(record) + on_pass() print(json.dumps(pass_metrics(record)["listing"] | {"pass": index}), flush=True) finally: restore() - return passes def _environment(harness: dict[str, Any]) -> dict[str, Any]: @@ -824,14 +867,29 @@ def _environment(harness: dict[str, Any]) -> dict[str, Any]: } -async def _run(config: Config) -> dict[str, Any]: - import httpx +def write_metrics(path: Path, doc: dict[str, Any]) -> None: + """Replace `path` whole with `doc`: a reader, or a run stopped mid-write, sees the + previous document or this one, never part of one.""" + temporary = path.with_name(path.name + ".tmp") + temporary.write_text(json.dumps(doc, indent=2) + "\n") + os.replace(temporary, path) + +async def _run(config: Config) -> dict[str, Any]: errors: list[str] = [] - harness: dict[str, Any] = {} environment: dict[str, Any] = {} setup_report: dict[str, Any] = {} passes: list[PassRecord] = [] + + def snapshot() -> dict[str, Any]: + return build_metrics( + config=config, + environment=environment, + setup=setup_report, + passes=passes, + errors=errors, + ) + try: harness = json.loads(config.harness.read_text()) environment = _environment(harness) @@ -847,28 +905,47 @@ async def _run(config: Config) -> dict[str, Any]: Path(harness["faults_file"]).write_text( json.dumps(plan_faults(plans, config.faults), indent=2) ) - passes = await run_passes(config, harness, plans, client) - except (HarnessError, OSError, ValueError, KeyError) as error: + await run_passes( + config, + harness, + plans, + client, + passes, + lambda: write_metrics(config.out, snapshot()), + ) + except (HarnessError, httpx.HTTPError, OSError, ValueError, KeyError, TypeError) as error: errors.append(f"{type(error).__name__}: {error}") - return build_metrics( - config=config, environment=environment, setup=setup_report, passes=passes, errors=errors - ) + return snapshot() -def main(argv: list[str] | None = None) -> int: - config = parse_config(argv) - from server.cli._ch import run_connected - - harness_org = json.loads(config.harness.read_text())["org"] - metrics = run_connected(lambda _ch: _run(config), orgs=(harness_org,)) +def finish(config: Config, metrics: dict[str, Any]) -> int: + """Write the final document, with any shape problem as a harness error; 1 on an error.""" problems = validate_metrics(metrics) metrics["harness_errors"] += [f"metrics shape: {p}" for p in problems] - config.out.write_text(json.dumps(metrics, indent=2, sort_keys=False) + "\n") + write_metrics(config.out, metrics) print(json.dumps(metrics["totals"], indent=2)) for error in metrics["harness_errors"]: print(f"harness error: {error}", file=sys.stderr) return 1 if metrics["harness_errors"] else 0 +def main(argv: list[str] | None = None) -> int: + config = parse_config(argv) + try: + org = str(json.loads(config.harness.read_text())["org"]) + except (OSError, ValueError, KeyError, TypeError) as error: + failed = f"harness file: {type(error).__name__}: {error}" + metrics = build_metrics(config=config, environment={}, setup={}, passes=[], errors=[failed]) + return finish(config, metrics) + from server.cli._ch import run_connected + + try: + metrics = run_connected(lambda _ch: _run(config), orgs=(org,)) + except Exception as error: # noqa: BLE001 — a store that cannot be reached is recorded + failed = f"connection: {type(error).__name__}: {error}" + metrics = build_metrics(config=config, environment={}, setup={}, passes=[], errors=[failed]) + return finish(config, metrics) + + if __name__ == "__main__": raise SystemExit(main()) diff --git a/docs/benchmarks/running.md b/docs/benchmarks/running.md index 311ad81118..2b4eda9d7a 100644 --- a/docs/benchmarks/running.md +++ b/docs/benchmarks/running.md @@ -369,15 +369,18 @@ Dispatch it from the Actions tab, or with `gh workflow run mcp-source-worker-capacity.yml -f sources=200 -f resources=20`. The inputs set the number of sources, resources per source, collections and passes, the time between passes, `LOOM_KNOWLEDGE_SOURCE_SYNC_MAX_PASS_SECONDS`, -`LOOM_KNOWLEDGE_SOURCE_ACL_STALE_SECONDS`, `LOOM_KNOWLEDGE_SOURCE_MIRROR_DOCUMENTS_PER_PASS`, -the refresh interval of the `selected_refresh` sources, the upstream and credential +`LOOM_KNOWLEDGE_SOURCE_ACL_STALE_SECONDS`, +`LOOM_KNOWLEDGE_SOURCE_MIRROR_DOCUMENTS_PER_PASS`, the refresh interval of the `selected_refresh` sources, the upstream and credential latencies, the worker's read limits and the faults (resources whose upstream denies the read, returns an empty document, stalls past the read deadline, answers 503 or answers slowly; each applies once setup is done). The defaults shorten the stale window and the -pass bound so a run reaches both within its time limit. +pass bound so a run reaches both within its time limit. The measuring step has 75 minutes, +15 of them kept for setup, so the driver refuses a run whose passes times the time between +passes exceeds 3,600 seconds; a pass that runs past its interval extends the run. The run uploads `source-worker-copies.json` (schema `loom.bench.source_worker_copies.v1`) -with the server and fixture logs. Per pass, and in total: +with the server and fixture logs. The driver rewrites the file whole after every pass, so +a run stopped by the step's limit keeps the passes it finished. Per pass, and in total: - `copies` and `checks`: the worker requests the sync made, each timed in Loom from its authority read to the check after the reply, with latency percentiles over the @@ -385,7 +388,10 @@ with the server and fixture logs. Per pass, and in total: `unsupported`, `timeout`, `overloaded`, `unavailable`, `reconnect`). - `confirmed`: copies written or rechecked and checks that confirmed access. - `written` and `retired`: copies stored and removed. -- `pass_bound_marks` and `cut`: turns the pass bound stopped, and passes it cut. +- `turn_seconds`: percentiles of the time each source's turn took. +- `pass_bound_marks`: turns the pass bound stopped. `sources_not_reached`: sources with no + turn in the pass, which the mirrored phase's time ran out before. `cut` (`passes_cut` in + total): a pass with a source not reached or a turn the bound stopped. - `listing`: sources whose recorded listing is younger than the stale window at the end of the pass (`served`), older (`unserved`) or never recorded (`never`); `lapses` counts sources served at the previous pass and not at this one. diff --git a/tests/unit/test_bench_source_worker_copies.py b/tests/unit/test_bench_source_worker_copies.py index 4c6bfe6143..1a6ef64720 100644 --- a/tests/unit/test_bench_source_worker_copies.py +++ b/tests/unit/test_bench_source_worker_copies.py @@ -3,17 +3,23 @@ from __future__ import annotations +import asyncio import inspect import json from datetime import UTC, datetime, timedelta from pathlib import Path +import httpx import pytest +import bench.source_worker_copies as swc from bench.source_worker_copies import ( FAULT_KINDS, + PASS_BUDGET_SECONDS, SCHEMA, + SETUP_ALLOWANCE_SECONDS, SETUP_OPS, + STEP_BUDGET_SECONDS, SUMMARY_KEYS, Config, Exchange, @@ -22,13 +28,17 @@ build_metrics, count_diff, listing_state, + main, + not_reached, parse_config, parse_faults, + pass_cut, percentile, plan_faults, plan_sources, summarize, validate_metrics, + write_metrics, ) _REQUIRED = ["--base-url", "http://127.0.0.1:7777", "--harness", "h.json", "--out", "m.json"] @@ -72,9 +82,18 @@ def test_config_defaults(): ) +def test_passes_fit_the_step_budget(): + assert PASS_BUDGET_SECONDS == STEP_BUDGET_SECONDS - SETUP_ALLOWANCE_SECONDS == 3600 + assert parse_config([*_REQUIRED, "--passes", "60", "--pass-interval", "60"]).passes == 60 + assert parse_config([*_REQUIRED, "--passes", "100", "--pass-interval", "0"]).passes == 100 + assert parse_config([*_REQUIRED, "--passes", "1", "--pass-interval", "3600"]).passes == 1 + + @pytest.mark.parametrize( "extra", [ + ["--passes", "61", "--pass-interval", "60"], + ["--passes", "2", "--pass-interval", "3600"], ["--sources", "0"], ["--sources", "2001"], ["--resources", "241"], @@ -180,16 +199,16 @@ def _config() -> Config: def _record() -> PassRecord: - record = PassRecord(index=0, started_s=0.0, seconds=12.5) + record = PassRecord(index=0, started_s=0.0, seconds=12.5, sources=3) record.exchanges = [ - Exchange("cap00000", "copy", 40.0, "confirmed"), - Exchange("cap00000", "check", 10.0, "confirmed"), - Exchange("cap00001", "check", 30.0, "overloaded"), - Exchange("cap00001", "check", 20.0, "denied_upstream"), + Exchange("copy", 40.0, "confirmed"), + Exchange("check", 10.0, "confirmed"), + Exchange("check", 30.0, "overloaded"), + Exchange("check", 20.0, "denied_upstream"), ] record.turns = [ - TurnRecord("cap00000", "ok", False, 2, 1, 0, "", 1.0), - TurnRecord("cap00001", "overloaded", True, 2, 0, 1, "", 2.0), + TurnRecord("cap00000", "ok", False, 1, 0, 1.0), + TurnRecord("cap00001", "overloaded", True, 0, 1, 2.0), ] record.listing = {"served": ["cap00000"], "unserved": ["cap00001"], "never": []} record.lapsed = ["cap00001"] @@ -215,6 +234,28 @@ def test_metrics_carry_the_fixed_shape_and_the_pass_figures(): totals = metrics["totals"] assert totals["confirmed"] == 2 and totals["worker_429"] == 1 and totals["lapses"] == 1 assert totals["worker_latency_ms"]["/v1/check-access"]["p50"] == 4.0 + assert entry["turn_seconds"]["count"] == 2 and entry["turn_seconds"]["max"] == 2.0 + assert totals["turn_seconds"]["p50"] == 1.0 + + +def test_a_pass_that_leaves_a_source_unreached_is_cut(): + record = _record() # three sources, two turns, one of them cut + assert not_reached(record) == 1 and pass_cut(record) + record.turns = [TurnRecord(f"cap{i:05d}", "ok", False, 0, 0, 1.0) for i in range(3)] + assert not_reached(record) == 0 and not pass_cut(record) + record.turns[1].cut = True + assert pass_cut(record) + # A source with two recorded turns counts once. + record.turns = [TurnRecord("cap00000", "ok", False, 0, 0, 1.0)] * 2 + assert not_reached(record) == 2 + metrics = build_metrics( + config=_config(), environment={}, setup={}, passes=[_record(), record], errors=[] + ) + assert validate_metrics(metrics) == [] + assert [p["sources_not_reached"] for p in metrics["passes"]] == [1, 2] + assert [p["cut"] for p in metrics["passes"]] == [True, True] + assert metrics["totals"]["sources_not_reached"] == 3 + assert metrics["totals"]["passes_cut"] == 2 def test_metrics_without_passes_still_conform(): @@ -263,6 +304,112 @@ def test_the_timed_sync_seams_exist(): ] +def test_metrics_replace_the_file_whole(tmp_path): + out = tmp_path / "m.json" + write_metrics(out, {"first": 1}) + write_metrics(out, {"second": 2}) + assert json.loads(out.read_text()) == {"second": 2} + assert [p.name for p in tmp_path.iterdir()] == ["m.json"] # no temporary left behind + + +def _paths(tmp_path) -> list[str]: + harness = tmp_path / "harness.json" + return [ + "--base-url", + "http://127.0.0.1:9", + "--harness", + str(harness), + "--out", + str(tmp_path / "m.json"), + "--sources", + "2", + "--resources", + "1", + "--faults", + "none", + ] + + +def test_an_unreadable_harness_file_is_a_recorded_harness_error(tmp_path, capsys): + assert main(_paths(tmp_path)) == 1 + metrics = json.loads((tmp_path / "m.json").read_text()) + assert validate_metrics(metrics) == [] + [error] = metrics["harness_errors"] + assert error.startswith("harness file: FileNotFoundError") + assert "harness error" in capsys.readouterr().err + + +def _harness(tmp_path) -> None: + (tmp_path / "harness.json").write_text( + json.dumps( + { + "org": "o", + "collections": 1, + "faults_file": str(tmp_path / "faults.json"), + "worker": {}, + } + ) + ) + + +def _copies_on(_harness: dict) -> dict: + return {"loom": {"knowledge_source_worker_copies_enabled": True}, "worker": {}} + + +@pytest.mark.parametrize( + "failure", + [ + httpx.ConnectError("refused"), + httpx.ReadTimeout("slow"), + httpx.HTTPStatusError( + "bad", + request=httpx.Request("GET", "http://x"), + response=httpx.Response(500, request=httpx.Request("GET", "http://x")), + ), + ], +) +def test_an_http_failure_is_a_recorded_harness_error(tmp_path, monkeypatch, failure): + _harness(tmp_path) + + async def fail(*_args): + raise failure + + monkeypatch.setattr(swc, "_environment", _copies_on) + monkeypatch.setattr(swc, "run_setup", fail) + metrics = asyncio.run(swc._run(parse_config(_paths(tmp_path)))) + assert validate_metrics(metrics) == [] + assert metrics["harness_errors"] == [f"{type(failure).__name__}: {failure}"] + + +def test_the_document_is_written_after_every_pass(tmp_path, monkeypatch): + _harness(tmp_path) + config = parse_config(_paths(tmp_path)) + seen: list[int] = [] + + class _Done: + def report(self, *_args): + return {"seconds": 0.0} + + async def setup(*_args): + return _Done() + + async def passes(_config, _harness, plans, _client, records, on_pass): + for index in range(2): + records.append(PassRecord(index=index, started_s=0.0, seconds=1.0, sources=2)) + on_pass() + seen.append(len(json.loads(config.out.read_text())["passes"])) + raise swc.HarnessError("stopped after two passes") + + monkeypatch.setattr(swc, "_environment", _copies_on) + monkeypatch.setattr(swc, "run_setup", setup) + monkeypatch.setattr(swc, "run_passes", passes) + metrics = asyncio.run(swc._run(config)) + assert seen == [1, 2] + assert len(metrics["passes"]) == 2 + assert metrics["harness_errors"] == ["HarnessError: stopped after two passes"] + assert json.loads((tmp_path / "faults.json").read_text()) == {} + + def test_setup_ops_are_served(): from server.operations.registry import OPERATIONS_BY_NAME From a18c1d3c0615824ef719fa110cd6ad1081739a86 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sat, 5 Dec 2026 02:36:37 +0000 Subject: [PATCH 3/4] The capacity driver records a turn that raised as reached and keeps its document through any failure A turn the sync records as failed after it raised is now a recorded turn with the status raised:, so it no longer counts as a source the pass ran out of time before. Any failure of the run is recorded beside the passes already finished instead of replacing them, and the document is written before and after setup too. The running guide says what a pass bound mark means for each bound, names the raised outcome and the ClickHouse log, wraps at the house width, and says why the sync interval stays set though the server's sync is off. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- .../workflows/mcp-source-worker-capacity.yml | 2 + bench/source_worker_copies.py | 86 +++++++++++------- docs/benchmarks/running.md | 46 ++++++---- tests/unit/test_bench_source_worker_copies.py | 88 +++++++++++++++++++ 4 files changed, 171 insertions(+), 51 deletions(-) diff --git a/.github/workflows/mcp-source-worker-capacity.yml b/.github/workflows/mcp-source-worker-capacity.yml index 6a57803cfe..e38463c02a 100644 --- a/.github/workflows/mcp-source-worker-capacity.yml +++ b/.github/workflows/mcp-source-worker-capacity.yml @@ -114,6 +114,8 @@ jobs: LOOM_KNOWLEDGE_SOURCE_SYNC_ENABLED: "false" LOOM_KNOWLEDGE_MIRRORED_SOURCES_ENABLED: "true" LOOM_KNOWLEDGE_SOURCE_WORKER_COPIES_ENABLED: "true" + # Its least value. The server's sync is off and --pass-interval paces the passes, but a + # turn reads this to decide when a copy that keeps answering unsupported is retired. LOOM_KNOWLEDGE_SOURCE_SYNC_INTERVAL_SECONDS: "60" LOOM_KNOWLEDGE_SOURCE_SYNC_MAX_PASS_SECONDS: ${{ inputs.max_pass_seconds }} LOOM_KNOWLEDGE_SOURCE_ACL_STALE_SECONDS: ${{ inputs.acl_stale_seconds }} diff --git a/bench/source_worker_copies.py b/bench/source_worker_copies.py index a30f3c886c..cb48593ca0 100644 --- a/bench/source_worker_copies.py +++ b/bench/source_worker_copies.py @@ -33,20 +33,21 @@ - every worker request a turn makes, timed from its authority read to its last check (`copy` reads content, `check` confirms access), and its answer: confirmed, or the refusal reason (`overloaded` is the worker's 429 or this process's channel share); -- each source's turn: its status, whether the pass bound cut it, its time, the copies it - wrote and retired, and the listing it recorded; a source with no turn in the pass is one - the pass did not reach, and a pass with such a source or a cut turn is cut; +- each source's turn: its status (`raised:` for one that raised), whether + it reached a pass bound, its time, the copies it wrote and retired, and the listing it + recorded; a source with no turn in the pass is one the mirrored phase's time ran out + before, and a pass with such a source or a marked turn is cut; - listing lapses: a source is served while its recorded listing is younger than `knowledge_source_acl_stale_seconds` at the pass's end; a lapse is a source that was served and is not; - the worker's own request counts by route and HTTP status, and its request durations. It writes one JSON document of fixed shape (`SCHEMA`, checked by `validate_metrics`) to -`--out` after every pass, replacing the last one whole, and once more at the end, so a run -stopped by its time limit keeps the passes it finished. It exits 1 only on a harness error -(a setup step that did not answer `ok`, an HTTP failure, a pass that raised, a fixture that -could not be read) and records the error in the document; capacity figures never fail the -run. +`--out` before setup, after setup and after every pass, replacing the last one whole, and +once more at the end, so a run stopped by its time limit keeps what it finished. It exits 1 +only on a harness error (a setup step that did not answer `ok`, an HTTP failure, a pass +that raised, a fixture that could not be read, any other failure of the run) and records +the error in the document; capacity figures never fail the run. PYTHONPATH=$PWD .venv/bin/python bench/source_worker_copies.py \\ --base-url http://127.0.0.1:7777 --harness "$FIXTURE/harness.json" \\ @@ -64,7 +65,7 @@ import time import uuid from collections import Counter -from collections.abc import Callable, Iterable +from collections.abc import Awaitable, Callable, Iterable from dataclasses import asdict, dataclass, field from datetime import UTC, datetime, timedelta from pathlib import Path @@ -338,8 +339,9 @@ def _worker_429(counts: dict[str, dict[str, int]]) -> int: def not_reached(record: PassRecord) -> int: - """Sources the pass ended before: every source is mirrored, and the mirrored phase stops - starting turns once its budget is spent, which `PassResult.cut` does not record.""" + """Sources the mirrored phase's time ran out before: every source is mirrored, and the + phase stops starting turns once its budget is spent, which `PassResult.cut` does not + record. A turn that raised was reached and recorded.""" return max(0, record.sources - len({t.source for t in record.turns})) @@ -720,6 +722,41 @@ def __init__(self) -> None: self.current: PassRecord | None = None self.listed: dict[str, str] = {} + def timed_turn( + self, turn: Callable[..., Awaitable[Any]], listed_key: str + ) -> Callable[..., Awaitable[Any]]: + """`turn`, recording each call in the current pass. A turn that raises (the sync + records it as the source's failed turn) is still a turn the pass reached.""" + recorder = self + + async def timed(src: Any, state: Any, run: Any) -> Any: + started = time.perf_counter() + result: Any = None + raised = "" + try: + result = await turn(src, state, run) + listed = str(result.kind_state.get(listed_key) or "") + if listed: + recorder.listed[src.name] = listed + return result + except BaseException as error: + raised = f"raised:{type(error).__name__}" + raise + finally: + if recorder.current is not None: + recorder.current.turns.append( + TurnRecord( + src.name, + raised or result.status, + not raised and result.cut, + 0 if raised else result.changed, + 0 if raised else result.removed, + time.perf_counter() - started, + ) + ) + + return timed + def install(self) -> Callable[[], None]: from server.knowledge.app import source_sync_worker as worker from server.knowledge.app.mcp_worker_read import WorkerReadRefused @@ -749,27 +786,8 @@ async def timed_exchange(self: Any, item: Any, *, content: bool) -> Any: ) ) - async def timed_turn(src: Any, state: Any, run: Any) -> Any: - started = time.perf_counter() - result = await turn(src, state, run) - listed = str(result.kind_state.get(worker._LISTED) or "") - if listed: - recorder.listed[src.name] = listed - if recorder.current is not None: - recorder.current.turns.append( - TurnRecord( - src.name, - result.status, - result.cut, - result.changed, - result.removed, - time.perf_counter() - started, - ) - ) - return result - worker._Turn._exchange = timed_exchange - worker.turn = timed_turn + worker.turn = self.timed_turn(turn, worker._LISTED) def restore() -> None: worker._Turn._exchange = exchange @@ -896,12 +914,14 @@ def snapshot() -> dict[str, Any]: if not environment["loom"]["knowledge_source_worker_copies_enabled"]: raise HarnessError("LOOM_KNOWLEDGE_SOURCE_WORKER_COPIES_ENABLED is off") plans = plan_sources(config.sources, config.resources, int(harness["collections"])) + write_metrics(config.out, snapshot()) # a run stopped in setup still leaves a document async with httpx.AsyncClient(base_url=config.base_url, timeout=120) as client: started = time.monotonic() setup = await run_setup(config, harness, plans, client) setup_report = setup.report( time.monotonic() - started, len(plans), len(plans) * config.resources ) + write_metrics(config.out, snapshot()) # a run stopped before a pass keeps setup Path(harness["faults_file"]).write_text( json.dumps(plan_faults(plans, config.faults), indent=2) ) @@ -913,7 +933,7 @@ def snapshot() -> dict[str, Any]: passes, lambda: write_metrics(config.out, snapshot()), ) - except (HarnessError, httpx.HTTPError, OSError, ValueError, KeyError, TypeError) as error: + except Exception as error: # noqa: BLE001 — any failure is recorded beside the passes kept errors.append(f"{type(error).__name__}: {error}") return snapshot() @@ -941,7 +961,7 @@ def main(argv: list[str] | None = None) -> int: try: metrics = run_connected(lambda _ch: _run(config), orgs=(org,)) - except Exception as error: # noqa: BLE001 — a store that cannot be reached is recorded + except Exception as error: # noqa: BLE001 — `_run` records its own; this is the connect failed = f"connection: {type(error).__name__}: {error}" metrics = build_metrics(config=config, environment={}, setup={}, passes=[], errors=[failed]) return finish(config, metrics) diff --git a/docs/benchmarks/running.md b/docs/benchmarks/running.md index 2b4eda9d7a..7a696b3832 100644 --- a/docs/benchmarks/running.md +++ b/docs/benchmarks/running.md @@ -366,37 +366,47 @@ preview and registration), with a test client that declares session protection, fixed number of sync passes in its own process. Dispatch it from the Actions tab, or with -`gh workflow run mcp-source-worker-capacity.yml -f sources=200 -f resources=20`. The inputs -set the number of sources, resources per source, collections and passes, the time between -passes, `LOOM_KNOWLEDGE_SOURCE_SYNC_MAX_PASS_SECONDS`, +`gh workflow run mcp-source-worker-capacity.yml -f sources=200 -f resources=20`. The +inputs set the number of sources, resources per source, collections and passes, the time +between passes, `LOOM_KNOWLEDGE_SOURCE_SYNC_MAX_PASS_SECONDS`, `LOOM_KNOWLEDGE_SOURCE_ACL_STALE_SECONDS`, -`LOOM_KNOWLEDGE_SOURCE_MIRROR_DOCUMENTS_PER_PASS`, the refresh interval of the `selected_refresh` sources, the upstream and credential -latencies, the worker's read limits and the faults (resources whose upstream denies the -read, returns an empty document, stalls past the read deadline, answers 503 or answers -slowly; each applies once setup is done). The defaults shorten the stale window and the -pass bound so a run reaches both within its time limit. The measuring step has 75 minutes, -15 of them kept for setup, so the driver refuses a run whose passes times the time between -passes exceeds 3,600 seconds; a pass that runs past its interval extends the run. +`LOOM_KNOWLEDGE_SOURCE_MIRROR_DOCUMENTS_PER_PASS`, the refresh interval of the +`selected_refresh` sources, the upstream and credential latencies, the worker's read +limits and the faults (resources whose upstream denies the read, returns an empty +document, stalls past the read deadline, answers 503 or answers slowly; each applies once +setup is done). The defaults shorten the stale window and the pass bound so a run reaches +both within its time limit. The measuring step has 75 minutes, 15 of them kept for setup, +so the driver refuses a run whose passes times the time between passes exceeds 3,600 +seconds; a pass that runs past its interval extends the run. The workflow also sets +`LOOM_KNOWLEDGE_SOURCE_SYNC_INTERVAL_SECONDS` to 60, its least value: the server's own sync +is off, but a turn reads the setting to decide when a copy that keeps answering +`unsupported` is retired. The run uploads `source-worker-copies.json` (schema `loom.bench.source_worker_copies.v1`) -with the server and fixture logs. The driver rewrites the file whole after every pass, so -a run stopped by the step's limit keeps the passes it finished. Per pass, and in total: +with the server, fixture and ClickHouse logs. The driver writes the file before setup, +after setup and after every pass, each time replacing it whole, so a run stopped by the +step's limit keeps what it finished. Per pass, and in total: - `copies` and `checks`: the worker requests the sync made, each timed in Loom from its authority read to the check after the reply, with latency percentiles over the - confirmed ones and a count per outcome (`confirmed`, `denied_upstream`, `denied`, - `unsupported`, `timeout`, `overloaded`, `unavailable`, `reconnect`). + confirmed ones and a count per outcome: `confirmed`, `denied_upstream`, `denied`, + `unsupported`, `timeout`, `overloaded`, `unavailable`, `reconnect`, or + `raised:` for a request that raised. - `confirmed`: copies written or rechecked and checks that confirmed access. - `written` and `retired`: copies stored and removed. -- `turn_seconds`: percentiles of the time each source's turn took. -- `pass_bound_marks`: turns the pass bound stopped. `sources_not_reached`: sources with no +- `turn_seconds`: percentiles of the time each source's turn took. A turn that raised + counts with the status `raised:` in `turn_statuses`. +- `pass_bound_marks`: turns that reached a pass bound. A turn is marked when the pass's + time is spent, and stops there, or when the pass's document bound is spent while a copy + is due, and goes on checking its stored copies. `sources_not_reached`: sources with no turn in the pass, which the mirrored phase's time ran out before. `cut` (`passes_cut` in - total): a pass with a source not reached or a turn the bound stopped. + total): a pass with a source not reached or a marked turn. - `listing`: sources whose recorded listing is younger than the stale window at the end of the pass (`served`), older (`unserved`) or never recorded (`never`); `lapses` counts sources served at the previous pass and not at this one. - `overloaded` and `worker.status_429`: refusals for lack of a slot, as Loom saw them and - as the worker answered them, with the worker's own request counts and durations by route. + as the worker answered them, with the worker's own request counts and durations by + route. The driver exits 1 only for a harness error, which `harness_errors` names; the figures never fail the run. Unit tests for the driver's configuration, layout, percentiles and diff --git a/tests/unit/test_bench_source_worker_copies.py b/tests/unit/test_bench_source_worker_copies.py index 1a6ef64720..00bdb5fef1 100644 --- a/tests/unit/test_bench_source_worker_copies.py +++ b/tests/unit/test_bench_source_worker_copies.py @@ -8,6 +8,7 @@ import json from datetime import UTC, datetime, timedelta from pathlib import Path +from types import SimpleNamespace import httpx import pytest @@ -410,6 +411,93 @@ async def passes(_config, _harness, plans, _client, records, on_pass): assert json.loads((tmp_path / "faults.json").read_text()) == {} +def test_a_turn_that_raises_is_recorded_and_reached(): + recorder = swc._Recorder() + recorder.current = record = PassRecord(index=0, started_s=0.0, seconds=0.0, sources=2) + + async def failing(src, state, run): + raise RuntimeError("turn failed") + + async def passing(src, state, run): + return SimpleNamespace( + kind_state={"listed": "2030-01-01T00:00:00+00:00"}, + status="ok", + cut=True, + changed=2, + removed=1, + ) + + with pytest.raises(RuntimeError): + asyncio.run(recorder.timed_turn(failing, "listed")(SimpleNamespace(name="a"), {}, None)) + asyncio.run(recorder.timed_turn(passing, "listed")(SimpleNamespace(name="b"), {}, None)) + failed, done = record.turns + assert (failed.source, failed.status, failed.cut, failed.changed) == ( + "a", + "raised:RuntimeError", + False, + 0, + ) + assert (done.status, done.cut, done.changed, done.removed) == ("ok", True, 2, 1) + assert recorder.listed == {"b": "2030-01-01T00:00:00+00:00"} + assert not_reached(record) == 0 + record.turns = [failed] + assert not_reached(record) == 1 and pass_cut(record) + record.turns = [failed, TurnRecord("b", "ok", False, 0, 0, 1.0)] + assert not pass_cut(record) # a raised turn alone never cuts the pass + + +def _document(path: Path) -> dict: + return json.loads(path.read_text()) + + +def _stub_setup(seen: list, out: Path): + class _Done: + def report(self, *_args): + return {"seconds": 0.0} + + async def setup(*_args): + seen.append(("setup", _document(out))) + return _Done() + + return setup + + +def test_an_unexpected_error_keeps_the_finished_passes(tmp_path, monkeypatch): + _harness(tmp_path) + config = parse_config(_paths(tmp_path)) + + async def passes(_config, _harness, _plans, _client, records, on_pass): + records.append(PassRecord(index=0, started_s=0.0, seconds=1.0, sources=2)) + on_pass() + raise RuntimeError("unexpected") + + monkeypatch.setattr(swc, "_environment", _copies_on) + monkeypatch.setattr(swc, "run_setup", _stub_setup([], config.out)) + monkeypatch.setattr(swc, "run_passes", passes) + metrics = asyncio.run(swc._run(config)) + assert len(metrics["passes"]) == 1 + assert metrics["harness_errors"] == ["RuntimeError: unexpected"] + assert validate_metrics(metrics) == [] + + +def test_the_document_is_written_before_and_after_setup(tmp_path, monkeypatch): + _harness(tmp_path) + config = parse_config(_paths(tmp_path)) + seen: list = [] + + async def passes(*_args): + seen.append(("passes", _document(config.out))) + + monkeypatch.setattr(swc, "_environment", _copies_on) + monkeypatch.setattr(swc, "run_setup", _stub_setup(seen, config.out)) + monkeypatch.setattr(swc, "run_passes", passes) + asyncio.run(swc._run(config)) + (before_name, before), (after_name, after) = seen + assert (before_name, before["setup"], before["passes"]) == ("setup", {}, []) + assert (after_name, after["setup"]) == ("passes", {"seconds": 0.0}) + assert validate_metrics(before) == [] and validate_metrics(after) == [] + + def test_setup_ops_are_served(): from server.operations.registry import OPERATIONS_BY_NAME From d42f250111551d7cd113d83475b1fad5da3649fe Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sat, 5 Dec 2026 02:48:49 +0000 Subject: [PATCH 4/4] The capacity driver faults stored copies and bounds every pass and setup by the step's time The fault table now goes on after the first pass at whose end every faulted resource holds a stored copy, as the turns' copy state shows, so the upstream's denial retires a copy and an unsupported copy lapses; the document names that pass or says the faults never went on. Each pass is cancelled at the sync's own pass bound and recorded as timed out, no pass starts when one more bound would end past the step, and setup past its allowance stops the run, each recorded in a new run section with the passes run. A failure after the run returned adds its error to the last document instead of replacing it. The running guide describes the per-pass errors, timeouts and fault state. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- bench/source_worker_copies.py | 291 +++++++++++++----- docs/benchmarks/running.md | 21 +- tests/unit/test_bench_source_worker_copies.py | 209 ++++++++++++- 3 files changed, 441 insertions(+), 80 deletions(-) diff --git a/bench/source_worker_copies.py b/bench/source_worker_copies.py index cb48593ca0..05eaee7016 100644 --- a/bench/source_worker_copies.py +++ b/bench/source_worker_copies.py @@ -20,15 +20,22 @@ profile when `i // 2` is even and the mapped-tool profile otherwise; each selects `--resources` resources. -After setup the driver writes the fixture's fault table (`--faults`, at most one fault per -resource: the first resource of sources 1, 2, ... in turn, then of source 0, then each -source's second resource, so source 0's first resource is the last first resource to take -one) and runs `--passes` sync passes in this process, each the pass the +After setup the driver runs `--passes` sync passes in this process, each the pass the `knowledge_source_sync` worker runs (`run_sync()` over every source), `--pass-interval` seconds apart from start to start or back to back when a pass overruns. The server runs -with that worker off, so these are the only passes. `passes * pass_interval` may be at -most `PASS_BUDGET_SECONDS`, the workflow step's time less `SETUP_ALLOWANCE_SECONDS` for -setup; a pass that runs past its interval extends the run. Per pass it records: +with that worker off, so these are the only passes. It writes the fixture's fault table +(`--faults`, at most one fault per resource: the first resource of sources 1, 2, ... in +turn, then of source 0, then each source's second resource, so source 0's first resource +is the last first resource to take one) after the first pass at whose end every faulted +resource holds a stored copy, so each fault reaches a copy the sync keeps: the upstream's +denial retires it, and an `unsupported` copy lapses. The document names that pass, or that +the faults never went on. + +`passes * pass_interval` may be at most `PASS_BUDGET_SECONDS`, the workflow step's time +less `SETUP_ALLOWANCE_SECONDS` for setup. Setup that runs past its allowance stops the run. +A pass that runs past `knowledge_source_sync_max_pass_seconds` is cancelled and recorded as +timed out, and no pass starts when one more such bound would end past the step, less +`END_MARGIN_SECONDS`; the document says why the run stopped early. Per pass it records: - every worker request a turn makes, timed from its authority read to its last check (`copy` reads content, `check` confirms access), and its answer: confirmed, or the @@ -95,6 +102,8 @@ STEP_BUDGET_SECONDS = 75 * 60 SETUP_ALLOWANCE_SECONDS = 15 * 60 PASS_BUDGET_SECONDS = STEP_BUDGET_SECONDS - SETUP_ALLOWANCE_SECONDS +# Kept back from the step for the final document and the process's exit. +END_MARGIN_SECONDS = 60 # --- pure parts ------------------------------------------------------------------------ @@ -322,6 +331,34 @@ class PassRecord: lapsed: list[str] = field(default_factory=list) worker_counts: dict[str, dict[str, int]] = field(default_factory=dict) worker_ms: dict[str, list[float]] = field(default_factory=dict) + # The pass ran past `knowledge_source_sync_max_pass_seconds` and was cancelled. + timed_out: bool = False + # The fixture's faults applied during the pass. + faults_on: bool = False + + +@dataclass +class RunState: + """How the run went as a whole: why it stopped early, if it did, and when faults began.""" + + stopped: str = "" # "", "setup_time" or "step_time" + faults_planned: int = 0 + # The pass after which the faults were switched on; None while they never were. + faults_on_after_pass: int | None = None + + +def faults_ready( + faults: dict[str, str], + owner: dict[str, str], + stored: dict[str, set[str]], + digest: Callable[[str], str], +) -> bool: + """Whether every faulted resource holds a stored copy, so each fault reaches a copy the + sync already keeps rather than a resource it has yet to read. `owner` maps a resource to + its source's name, and `stored` a source to the digests of its stored copies.""" + return bool(faults) and all( + digest(resource) in stored.get(owner[resource], set()) for resource in faults + ) def _exchange_summary(exchanges: list[Exchange], operation: str) -> dict[str, Any]: @@ -358,6 +395,8 @@ def pass_metrics(record: PassRecord) -> dict[str, Any]: "seconds": round(record.seconds, 3), "cut": pass_cut(record), "sources_not_reached": not_reached(record), + "timed_out": record.timed_out, + "faults_on": record.faults_on, "errors": record.errors, "turns": len(record.turns), "turn_seconds": summarize(t.seconds for t in record.turns), @@ -393,7 +432,9 @@ def build_metrics( setup: dict[str, Any], passes: list[PassRecord], errors: list[str], + state: RunState | None = None, ) -> dict[str, Any]: + state = state or RunState() exchanges = [e for p in passes for e in p.exchanges] worker_ms: dict[str, list[float]] = {} for p in passes: @@ -406,6 +447,13 @@ def build_metrics( "config": settings, "environment": environment, "setup": setup, + "run": { + "passes_run": len(passes), + "stopped": state.stopped, + "timed_out_passes": sum(p.timed_out for p in passes), + "faults_planned": state.faults_planned, + "faults_on_after_pass": state.faults_on_after_pass, + }, "passes": [pass_metrics(p) for p in passes], "totals": { "passes": len(passes), @@ -437,6 +485,7 @@ def build_metrics( "config": dict, "environment": dict, "setup": dict, + "run": dict, "passes": list, "totals": dict, "harness_errors": list, @@ -447,6 +496,8 @@ def build_metrics( "seconds": float, "cut": bool, "sources_not_reached": int, + "timed_out": bool, + "faults_on": bool, "errors": int, "turns": int, "turn_seconds": dict, @@ -478,7 +529,16 @@ def build_metrics( } -def _check_fields(where: str, value: Any, fields: dict[str, type]) -> list[str]: +_RUN: dict[str, type | tuple[type, ...]] = { + "passes_run": int, + "stopped": str, + "timed_out_passes": int, + "faults_planned": int, + "faults_on_after_pass": (int, type(None)), +} + + +def _check_fields(where: str, value: Any, fields: dict[str, Any]) -> list[str]: if not isinstance(value, dict): return [f"{where}: not an object"] problems = ( @@ -488,14 +548,17 @@ def _check_fields(where: str, value: Any, fields: dict[str, type]) -> list[str]: if name not in value: continue item = value[name] + kinds = kind if isinstance(kind, tuple) else (kind,) # A whole number is a valid float; a bool is never an int here. - ok = ( + ok = any( isinstance(item, (int, float)) and not isinstance(item, bool) - if kind is float - else isinstance(item, kind) and not (kind is int and isinstance(item, bool)) + if one is float + else isinstance(item, one) and not (one is int and isinstance(item, bool)) + for one in kinds ) if not ok: - problems.append(f"{where}.{name}: expected {kind.__name__}") + names = " or ".join(one.__name__ for one in kinds) + problems.append(f"{where}.{name}: expected {names}") return problems @@ -512,6 +575,7 @@ def validate_metrics(doc: Any) -> list[str]: return problems if doc["schema"] != SCHEMA: problems.append(f"schema: expected {SCHEMA}") + problems += _check_fields("run", doc["run"], _RUN) for i, entry in enumerate(doc["passes"]): where = f"passes[{i}]" found = _check_fields(where, entry, _PASS) @@ -716,18 +780,20 @@ async def run_setup( class _Recorder: - """Times each worker request and each turn the sync makes in this process.""" + """Times each worker request and each turn the sync makes in this process, and keeps + each source's last listing and stored copies as its turns report them.""" def __init__(self) -> None: self.current: PassRecord | None = None self.listed: dict[str, str] = {} + # Per source, the resource digests whose copy its last finished turn holds. + self.stored: dict[str, set[str]] = {} def timed_turn( - self, turn: Callable[..., Awaitable[Any]], listed_key: str + self, turn: Callable[..., Awaitable[Any]], listed_key: str, copies_key: str ) -> Callable[..., Awaitable[Any]]: """`turn`, recording each call in the current pass. A turn that raises (the sync records it as the source's failed turn) is still a turn the pass reached.""" - recorder = self async def timed(src: Any, state: Any, run: Any) -> Any: started = time.perf_counter() @@ -737,14 +803,21 @@ async def timed(src: Any, state: Any, run: Any) -> Any: result = await turn(src, state, run) listed = str(result.kind_state.get(listed_key) or "") if listed: - recorder.listed[src.name] = listed + self.listed[src.name] = listed + copies = result.kind_state.get(copies_key) or {} + # A stored copy's entry carries its digest; one with no copy has none. + self.stored[src.name] = { + resource + for resource, entry in copies.items() + if isinstance(entry, dict) and "sha" in entry + } return result except BaseException as error: raised = f"raised:{type(error).__name__}" raise finally: - if recorder.current is not None: - recorder.current.turns.append( + if self.current is not None: + self.current.turns.append( TurnRecord( src.name, raised or result.status, @@ -787,7 +860,7 @@ async def timed_exchange(self: Any, item: Any, *, content: bool) -> Any: ) worker._Turn._exchange = timed_exchange - worker.turn = self.timed_turn(turn, worker._LISTED) + worker.turn = self.timed_turn(turn, worker._LISTED, worker._COPIES) def restore() -> None: worker._Turn._exchange = exchange @@ -802,67 +875,125 @@ async def _worker_stats(client: Any, url: str) -> dict[str, Any]: return response.json() +@dataclass +class PassLoop: + """What the pass loop runs against: the sync, the worker's stats, the clock's limits and + the fault table it switches on. Tests stand in for the sync and the stats.""" + + sync: Callable[[], Awaitable[Any]] + stats: Callable[[], Awaitable[dict[str, Any]]] + recorder: _Recorder + digest: Callable[[str], str] + max_pass_seconds: float + stale_seconds: int + # Monotonic time by which the last pass must have ended. + deadline: float + faults: dict[str, str] + faults_file: Path + + +async def drive_passes( + config: Config, + plans: list[SourcePlan], + loop: PassLoop, + state: RunState, + passes: list[PassRecord], + on_pass: Callable[[], None], +) -> None: + """Run the passes, appending each to `passes` and calling `on_pass` after it. + + A pass that runs past the sync's own pass bound is cancelled and recorded as timed out. + No pass starts when one more could end past `loop.deadline`. The faults go on after the + first pass at whose end every faulted resource holds a stored copy.""" + recorder, names = loop.recorder, [plan.name for plan in plans] + owner = {resource: plan.name for plan in plans for resource in plan.resources} + state.faults_planned = len(loop.faults) + served_before: set[str] = set() + counts = (await loop.stats())["counts"] + origin = time.monotonic() + for index in range(config.passes): + start_at = max(time.monotonic(), origin + index * config.pass_interval) + if start_at + loop.max_pass_seconds > loop.deadline: + state.stopped = "step_time" + return + await asyncio.sleep(start_at - time.monotonic()) + record = PassRecord( + index=index, + started_s=time.monotonic() - origin, + seconds=0, + sources=len(plans), + faults_on=state.faults_on_after_pass is not None, + ) + recorder.current = record + started = time.monotonic() + limit = asyncio.timeout(loop.max_pass_seconds) + try: + async with limit: + result = await loop.sync() + record.errors = len(result.errors) + except TimeoutError as error: + if not limit.expired(): # a timeout inside the pass, not the pass's own bound + raise HarnessError(f"pass {index} raised TimeoutError: {error}") from error + record.timed_out = True + except Exception as error: # any other failure of a pass is the harness's error + raise HarnessError(f"pass {index} raised {type(error).__name__}: {error}") from error + finally: + recorder.current = None + record.seconds = time.monotonic() - started + record.listing = listing_state( + recorder.listed, names, datetime.now(UTC), loop.stale_seconds + ) + served = set(record.listing["served"]) + record.lapsed = sorted(served_before - served) + served_before = served + stats = await loop.stats() + record.worker_counts = count_diff(stats["counts"], counts) + record.worker_ms = stats["duration_ms"] + counts = stats["counts"] + if state.faults_on_after_pass is None and faults_ready( + loop.faults, owner, recorder.stored, loop.digest + ): + loop.faults_file.write_text(json.dumps(loop.faults, indent=2)) + state.faults_on_after_pass = index + passes.append(record) + on_pass() + print(json.dumps(pass_metrics(record)["listing"] | {"pass": index}), flush=True) + + async def run_passes( config: Config, harness: dict[str, Any], plans: list[SourcePlan], client: Any, + state: RunState, passes: list[PassRecord], on_pass: Callable[[], None], + deadline: float, ) -> None: - """Run the passes, appending each to `passes` and calling `on_pass` after it.""" + """The passes against this process's sync and the fixture's worker.""" from server.core.ch import set_query_tag from server.knowledge.app.mcp_worker_runtime import source_worker_runtime from server.knowledge.app.source_sync import run_sync + from server.knowledge.domain.mcp_identity import resource_digest from server.settings import settings set_query_tag("bench.source_worker_copies.passes") recorder = _Recorder() restore = recorder.install() - names = [plan.name for plan in plans] - served_before: set[str] = set() - counts = (await _worker_stats(client, harness["stats_url"]))["counts"] + loop = PassLoop( + sync=run_sync, + stats=lambda: _worker_stats(client, harness["stats_url"]), + recorder=recorder, + digest=resource_digest, + max_pass_seconds=float(settings.knowledge_source_sync_max_pass_seconds), + stale_seconds=int(settings.knowledge_source_acl_stale_seconds), + deadline=deadline, + faults=plan_faults(plans, config.faults), + faults_file=Path(harness["faults_file"]), + ) try: async with source_worker_runtime(settings.knowledge_source_worker_routes_file): - origin = time.monotonic() - for index in range(config.passes): - wait = origin + index * config.pass_interval - time.monotonic() - if wait > 0: - await asyncio.sleep(wait) - record = PassRecord( - index=index, - started_s=time.monotonic() - origin, - seconds=0, - sources=len(plans), - ) - recorder.current = record - started = time.monotonic() - try: - result = await run_sync() - except Exception as error: # any failure of a pass is the harness's error - raise HarnessError( - f"pass {index} raised {type(error).__name__}: {error}" - ) from error - finally: - recorder.current = None - record.seconds = time.monotonic() - started - record.errors = len(result.errors) - record.listing = listing_state( - recorder.listed, - names, - datetime.now(UTC), - int(settings.knowledge_source_acl_stale_seconds), - ) - served = set(record.listing["served"]) - record.lapsed = sorted(served_before - served) - served_before = served - stats = await _worker_stats(client, harness["stats_url"]) - record.worker_counts = count_diff(stats["counts"], counts) - record.worker_ms = stats["duration_ms"] - counts = stats["counts"] - passes.append(record) - on_pass() - print(json.dumps(pass_metrics(record)["listing"] | {"pass": index}), flush=True) + await drive_passes(config, plans, loop, state, passes, on_pass) finally: restore() @@ -894,10 +1025,12 @@ def write_metrics(path: Path, doc: dict[str, Any]) -> None: async def _run(config: Config) -> dict[str, Any]: + deadline = time.monotonic() + STEP_BUDGET_SECONDS - END_MARGIN_SECONDS errors: list[str] = [] environment: dict[str, Any] = {} setup_report: dict[str, Any] = {} passes: list[PassRecord] = [] + state = RunState() def snapshot() -> dict[str, Any]: return build_metrics( @@ -906,6 +1039,7 @@ def snapshot() -> dict[str, Any]: setup=setup_report, passes=passes, errors=errors, + state=state, ) try: @@ -917,21 +1051,28 @@ def snapshot() -> dict[str, Any]: write_metrics(config.out, snapshot()) # a run stopped in setup still leaves a document async with httpx.AsyncClient(base_url=config.base_url, timeout=120) as client: started = time.monotonic() - setup = await run_setup(config, harness, plans, client) + try: + async with asyncio.timeout(SETUP_ALLOWANCE_SECONDS): + setup = await run_setup(config, harness, plans, client) + except TimeoutError: + # No pass can run without every source, so the run measured nothing. + state.stopped = "setup_time" + raise HarnessError( + f"setup ran past its {SETUP_ALLOWANCE_SECONDS} s allowance" + ) from None setup_report = setup.report( time.monotonic() - started, len(plans), len(plans) * config.resources ) write_metrics(config.out, snapshot()) # a run stopped before a pass keeps setup - Path(harness["faults_file"]).write_text( - json.dumps(plan_faults(plans, config.faults), indent=2) - ) await run_passes( config, harness, plans, client, + state, passes, lambda: write_metrics(config.out, snapshot()), + deadline, ) except Exception as error: # noqa: BLE001 — any failure is recorded beside the passes kept errors.append(f"{type(error).__name__}: {error}") @@ -949,6 +1090,19 @@ def finish(config: Config, metrics: dict[str, Any]) -> int: return 1 if metrics["harness_errors"] else 0 +def _after_failure(config: Config, failed: str) -> dict[str, Any]: + """The document the run last wrote with `failed` added to its harness errors, or an empty + one when it wrote none: a failure after `_run` returned leaves its passes in place.""" + try: + metrics = json.loads(config.out.read_text()) + if not validate_metrics(metrics): + metrics["harness_errors"].append(failed) + return metrics + except (OSError, ValueError): + pass + return build_metrics(config=config, environment={}, setup={}, passes=[], errors=[failed]) + + def main(argv: list[str] | None = None) -> int: config = parse_config(argv) try: @@ -961,9 +1115,8 @@ def main(argv: list[str] | None = None) -> int: try: metrics = run_connected(lambda _ch: _run(config), orgs=(org,)) - except Exception as error: # noqa: BLE001 — `_run` records its own; this is the connect - failed = f"connection: {type(error).__name__}: {error}" - metrics = build_metrics(config=config, environment={}, setup={}, passes=[], errors=[failed]) + except Exception as error: # noqa: BLE001 — `_run` records its own; this is the connection + metrics = _after_failure(config, f"connection: {type(error).__name__}: {error}") return finish(config, metrics) diff --git a/docs/benchmarks/running.md b/docs/benchmarks/running.md index 7a696b3832..ebd74c72b1 100644 --- a/docs/benchmarks/running.md +++ b/docs/benchmarks/running.md @@ -373,11 +373,17 @@ between passes, `LOOM_KNOWLEDGE_SOURCE_SYNC_MAX_PASS_SECONDS`, `LOOM_KNOWLEDGE_SOURCE_MIRROR_DOCUMENTS_PER_PASS`, the refresh interval of the `selected_refresh` sources, the upstream and credential latencies, the worker's read limits and the faults (resources whose upstream denies the read, returns an empty -document, stalls past the read deadline, answers 503 or answers slowly; each applies once -setup is done). The defaults shorten the stale window and the pass bound so a run reaches -both within its time limit. The measuring step has 75 minutes, 15 of them kept for setup, -so the driver refuses a run whose passes times the time between passes exceeds 3,600 -seconds; a pass that runs past its interval extends the run. The workflow also sets +document, stalls past the read deadline, answers 503 or answers slowly). The faults go on +after the first pass at whose end every faulted resource holds a stored copy, so each one +reaches a copy the sync keeps; `run.faults_on_after_pass` names that pass, or is `null` +when they never went on. The defaults shorten the stale window and the pass bound so a +run reaches both within its time limit. The measuring step has 75 minutes, 15 of them kept +for setup, so the driver refuses a run whose passes times the time between passes exceeds +3,600 seconds. Setup that runs past its 15 minutes stops the run as a harness error. A pass +that runs past `LOOM_KNOWLEDGE_SOURCE_SYNC_MAX_PASS_SECONDS` is cancelled and recorded as +timed out, and no pass starts when one more such bound would end past the step, less a +minute for the last write; `run.stopped` reads `setup_time` or `step_time` when the run +stopped early and `run.passes_run` how many passes ran. The workflow also sets `LOOM_KNOWLEDGE_SOURCE_SYNC_INTERVAL_SECONDS` to 60, its least value: the server's own sync is off, but a turn reads the setting to decide when a copy that keeps answering `unsupported` is retired. @@ -387,6 +393,11 @@ with the server, fixture and ClickHouse logs. The driver writes the file before after setup and after every pass, each time replacing it whole, so a run stopped by the step's limit keeps what it finished. Per pass, and in total: +- `errors`: the pass's failed source turns, which a fault can cause and the pass records + in its own result. They are figures, not harness errors. +- `timed_out` (`run.timed_out_passes` in total): the pass ran past its bound and was + cancelled. `faults_on`: the faults applied during the pass. + - `copies` and `checks`: the worker requests the sync made, each timed in Loom from its authority read to the check after the reply, with latency percentiles over the confirmed ones and a count per outcome: `confirmed`, `denied_upstream`, `denied`, diff --git a/tests/unit/test_bench_source_worker_copies.py b/tests/unit/test_bench_source_worker_copies.py index 00bdb5fef1..aea539a276 100644 --- a/tests/unit/test_bench_source_worker_copies.py +++ b/tests/unit/test_bench_source_worker_copies.py @@ -6,6 +6,7 @@ import asyncio import inspect import json +import time from datetime import UTC, datetime, timedelta from pathlib import Path from types import SimpleNamespace @@ -28,6 +29,7 @@ TurnRecord, build_metrics, count_diff, + faults_ready, listing_state, main, not_reached, @@ -394,7 +396,7 @@ def report(self, *_args): async def setup(*_args): return _Done() - async def passes(_config, _harness, plans, _client, records, on_pass): + async def passes(_config, _harness, plans, _client, _state, records, on_pass, _deadline): for index in range(2): records.append(PassRecord(index=index, started_s=0.0, seconds=1.0, sources=2)) on_pass() @@ -408,7 +410,7 @@ async def passes(_config, _harness, plans, _client, records, on_pass): assert seen == [1, 2] assert len(metrics["passes"]) == 2 assert metrics["harness_errors"] == ["HarnessError: stopped after two passes"] - assert json.loads((tmp_path / "faults.json").read_text()) == {} + assert not (tmp_path / "faults.json").exists() # the stubbed passes switched none on def test_a_turn_that_raises_is_recorded_and_reached(): @@ -420,7 +422,10 @@ async def failing(src, state, run): async def passing(src, state, run): return SimpleNamespace( - kind_state={"listed": "2030-01-01T00:00:00+00:00"}, + kind_state={ + "listed": "2030-01-01T00:00:00+00:00", + "copies": {"d1": {"sha": "x", "copied_at": "t"}, "d2": {"retry_at": "t"}}, + }, status="ok", cut=True, changed=2, @@ -428,8 +433,12 @@ async def passing(src, state, run): ) with pytest.raises(RuntimeError): - asyncio.run(recorder.timed_turn(failing, "listed")(SimpleNamespace(name="a"), {}, None)) - asyncio.run(recorder.timed_turn(passing, "listed")(SimpleNamespace(name="b"), {}, None)) + asyncio.run( + recorder.timed_turn(failing, "listed", "copies")(SimpleNamespace(name="a"), {}, None) + ) + asyncio.run( + recorder.timed_turn(passing, "listed", "copies")(SimpleNamespace(name="b"), {}, None) + ) failed, done = record.turns assert (failed.source, failed.status, failed.cut, failed.changed) == ( "a", @@ -439,6 +448,7 @@ async def passing(src, state, run): ) assert (done.status, done.cut, done.changed, done.removed) == ("ok", True, 2, 1) assert recorder.listed == {"b": "2030-01-01T00:00:00+00:00"} + assert recorder.stored == {"b": {"d1"}} # only an entry with a digest holds a copy assert not_reached(record) == 0 record.turns = [failed] assert not_reached(record) == 1 and pass_cut(record) @@ -466,7 +476,7 @@ def test_an_unexpected_error_keeps_the_finished_passes(tmp_path, monkeypatch): _harness(tmp_path) config = parse_config(_paths(tmp_path)) - async def passes(_config, _harness, _plans, _client, records, on_pass): + async def passes(_config, _harness, _plans, _client, _state, records, on_pass, _end): records.append(PassRecord(index=0, started_s=0.0, seconds=1.0, sources=2)) on_pass() raise RuntimeError("unexpected") @@ -502,3 +512,190 @@ def test_setup_ops_are_served(): from server.operations.registry import OPERATIONS_BY_NAME assert set(SETUP_OPS) <= set(OPERATIONS_BY_NAME) + + +def test_faults_are_ready_once_every_faulted_resource_is_stored(): + owner = {"r1": "a", "r2": "b"} + faults = {"r1": "denied", "r2": "unsupported"} + assert not faults_ready({}, owner, {"a": {"r1"}}, str) + assert not faults_ready(faults, owner, {"a": {"r1"}}, str) + assert not faults_ready(faults, owner, {"a": {"r1"}, "b": {"r1"}}, str) + assert faults_ready(faults, owner, {"a": {"r1"}, "b": {"r2", "r9"}}, str) + assert faults_ready(faults, owner, {"a": {"#r1"}, "b": {"#r2"}}, lambda r: "#" + r) + + +def _stats(): + async def stats(): + return {"counts": {}, "duration_ms": {}} + + return stats + + +def _loop(tmp_path, recorder, sync, plans, *, max_pass=5.0, deadline_in=600.0, faults=None): + return swc.PassLoop( + sync=sync, + stats=_stats(), + recorder=recorder, + digest=lambda resource: resource, + max_pass_seconds=max_pass, + stale_seconds=60, + deadline=time.monotonic() + deadline_in, + faults=plan_faults(plans, faults or {}), + faults_file=tmp_path / "faults.json", + ) + + +def _drive(tmp_path, passes, loop, plans): + config = parse_config([*_paths(tmp_path), "--passes", str(passes), "--pass-interval", "0"]) + state, records = swc.RunState(), [] + asyncio.run(swc.drive_passes(config, plans, loop, state, records, lambda: None)) + return state, records + + +def test_faults_switch_on_only_after_every_faulted_resource_is_stored(tmp_path): + plans = plan_sources(2, 2, 1) + recorder = swc._Recorder() + faulted = plans[1].resources[0] # plan_faults gives the one fault to source 1 + faults_file = tmp_path / "faults.json" + seen: list[bool] = [] + + async def sync(): + seen.append(faults_file.exists()) + # Source 1's first resource is stored only in the second pass. + stored = {plans[0].resources[0]} | ({faulted} if len(seen) >= 2 else set()) + for plan in plans: + recorder.current.turns.append(TurnRecord(plan.name, "ok", False, 0, 0, 0.1)) + recorder.stored[plan.name] = {r for r in plan.resources if r in stored} + return SimpleNamespace(errors=[]) + + loop = _loop(tmp_path, recorder, sync, plans, faults={"denied": 1}) + state, records = _drive(tmp_path, 3, loop, plans) + assert seen == [False, False, True] + assert state.faults_on_after_pass == 1 and state.faults_planned == 1 + assert [r.faults_on for r in records] == [False, False, True] + assert json.loads(faults_file.read_text()) == {faulted: "denied"} + metrics = build_metrics( + config=_config(), environment={}, setup={}, passes=records, errors=[], state=state + ) + assert validate_metrics(metrics) == [] + assert metrics["run"]["faults_on_after_pass"] == 1 + assert [p["faults_on"] for p in metrics["passes"]] == [False, False, True] + + +def test_faults_that_never_reach_a_stored_copy_are_never_switched_on(tmp_path): + plans = plan_sources(2, 1, 1) + recorder = swc._Recorder() + + async def sync(): + return SimpleNamespace(errors=[]) + + loop = _loop(tmp_path, recorder, sync, plans, faults={"timeout": 1}) + state, records = _drive(tmp_path, 2, loop, plans) + assert state.faults_on_after_pass is None and len(records) == 2 + assert not (tmp_path / "faults.json").exists() + metrics = build_metrics( + config=_config(), environment={}, setup={}, passes=records, errors=[], state=state + ) + assert metrics["run"]["faults_on_after_pass"] is None and validate_metrics(metrics) == [] + + +def test_a_pass_past_its_bound_is_recorded_as_timed_out(tmp_path): + plans = plan_sources(1, 1, 1) + + async def slow(): + await asyncio.sleep(5) + + loop = _loop(tmp_path, swc._Recorder(), slow, plans, max_pass=0.05) + state, records = _drive(tmp_path, 2, loop, plans) + assert [r.timed_out for r in records] == [True, True] and state.stopped == "" + metrics = build_metrics( + config=_config(), environment={}, setup={}, passes=records, errors=[], state=state + ) + assert metrics["run"]["timed_out_passes"] == 2 and metrics["harness_errors"] == [] + + +def test_a_timeout_inside_a_pass_is_a_harness_error(tmp_path): + plans = plan_sources(1, 1, 1) + + async def failing(): + raise TimeoutError("a read inside the pass") + + loop = _loop(tmp_path, swc._Recorder(), failing, plans) + with pytest.raises(swc.HarnessError, match="pass 0 raised TimeoutError"): + _drive(tmp_path, 1, loop, plans) + + +def test_no_pass_starts_that_could_end_past_the_step(tmp_path): + plans = plan_sources(1, 1, 1) + + async def quick(): + return SimpleNamespace(errors=[]) + + loop = _loop(tmp_path, swc._Recorder(), quick, plans, max_pass=1.0, deadline_in=0.5) + state, records = _drive(tmp_path, 3, loop, plans) + assert records == [] and state.stopped == "step_time" + + async def steady(): + await asyncio.sleep(0.6) + return SimpleNamespace(errors=[]) + + # The first pass fits; after its 0.6 s, one more bound of 1 s would end past 1.5 s. + loop = _loop(tmp_path, swc._Recorder(), steady, plans, max_pass=1.0, deadline_in=1.5) + state, records = _drive(tmp_path, 3, loop, plans) + assert len(records) == 1 and state.stopped == "step_time" + metrics = build_metrics( + config=_config(), environment={}, setup={}, passes=records, errors=[], state=state + ) + assert metrics["run"] == { + "passes_run": 1, + "stopped": "step_time", + "timed_out_passes": 0, + "faults_planned": 0, + "faults_on_after_pass": None, + } + + +def test_setup_past_its_allowance_stops_the_run_with_a_record(tmp_path, monkeypatch): + _harness(tmp_path) + config = parse_config(_paths(tmp_path)) + ran: list[str] = [] + + async def slow_setup(*_args): + await asyncio.sleep(5) + + async def passes(*_args): + ran.append("passes") + + monkeypatch.setattr(swc, "SETUP_ALLOWANCE_SECONDS", 0.05) + monkeypatch.setattr(swc, "_environment", _copies_on) + monkeypatch.setattr(swc, "run_setup", slow_setup) + monkeypatch.setattr(swc, "run_passes", passes) + metrics = asyncio.run(swc._run(config)) + assert ran == [] + assert metrics["run"]["stopped"] == "setup_time" + assert metrics["harness_errors"] == ["HarnessError: setup ran past its 0.05 s allowance"] + assert validate_metrics(metrics) == [] + + +def test_a_failure_after_the_run_keeps_its_document(tmp_path, monkeypatch): + import server.cli._ch as ch + + _harness(tmp_path) + argv = _paths(tmp_path) + config = parse_config(argv) + write_metrics( + config.out, + build_metrics(config=config, environment={}, setup={}, passes=[_record()], errors=[]), + ) + + def disconnect_fails(*_args, **_kwargs): + raise RuntimeError("disconnect") + + monkeypatch.setattr(ch, "run_connected", disconnect_fails) + assert main(argv) == 1 + kept = _document(config.out) + assert len(kept["passes"]) == 1 + assert kept["harness_errors"] == ["connection: RuntimeError: disconnect"] + config.out.unlink() + assert main(argv) == 1 + assert _document(config.out)["passes"] == []