Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions docs/MAP.md

Large diffs are not rendered by default.

114 changes: 114 additions & 0 deletions docs/plans/2026-11-29-hub-stage1-speed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# Plan: Hub & core read-path speed (Stage 1 — no projection bump)

Date: 2026-11-29 · Status: implemented (pending review, branch `hub-stage1-speed`) · Follows: `docs/plans/2026-11-18-hub-on-demand.md`, `docs/plans/2026-11-18-hub-summary-tables.md`

**Scope boundary:** Stage 1 requires **no `PROJECTION_VERSION` bump**, **no schema changes**, and **no write-path or validation changes**. JSONL under `events/` remains the sole source of truth; `factory.sqlite` remains the single rebuildable projection. Stage 2 (projector summary tables + live query-on-request API) is deferred to a follow-up plan after active worktrees settle.

## Goal & measured baseline (2026-11-28, `agentic-science` pilot)

Make hub rebuilds fast and proportional to what changed while speeding up the core factory read services that both the CLI/MCP tools and the hub depend on.

- **Pilot scale (`agentic-science`):** `134,845` events (`423 MB` across `3,330` JSONL files), `85,576` works, `13,258` extraction rows, `5,810` decisions, `448 MB` `factory.sqlite`; `11` projects total under `data/projects/`.
- **Observed full rebuild wall-clock on `agentic-science`:** **~20 min** (`22:58` → `23:18`, from payload file mtimes):
- `pipeline.json`: ~223 s · `overview.json`: ~178 s · `grids` (12 files): ~145 s · `levels.json` (13 KB): ~123 s · `sources.json`: ~106 s · `shell.json`: ~90 s · `learn.json` (43 KB): ~51 s · `explore.json` + `lenses.json`: ~89 s · `mining.json`: ~57 s.
- **Raw SQLite baseline on `agentic-science` (`factory.sqlite`):** `COUNT(*) FROM works` = `2.4 ms`, live `extraction_rows` = `32.6 ms`, scanning all `85,576` `works` JSON rows = `168.9 ms`, `type_counts` (`GROUP BY type` without index) = `474.7 ms`.
- **Four root causes:**
1. **Global & misaligned code hash:** `hub_serve.code_hash()` hashes `hub_ui.asset_version()` and every `hub_*.py` module globally. Any UI CSS/JS edit invalidates all payloads across all 11 projects (~440 payloads), while edits to core `services/*.py` modules go undetected.
2. **Startup storm & throwaway `HubContext`:** `MainHub.prepare_all()` opens and prewarms all 11 projects concurrently at startup, and `BATCH_MAX = 4` short-lived child processes discard `HubContext` (`flow_data`, `mining_data`, `graph`, `corpus_raw`) 5–6 times per project.
3. **Incomplete `PAYLOAD_INPUTS`:** ~14 payloads (`protocol`, `levels`, `pipeline`, `sources`, `method`, `write`, `platform`, `learn`, `living`, `contradictions`, `chat`, etc.) have no entry in `hub_build.PAYLOAD_INPUTS`, defaulting to `("*",)` and restaling on `runner.`, `task.`, `feed.`, or `watch.` events.
4. **JSONL scans & full-corpus Pydantic hydration:** Core read services scan 423 MB of raw JSONL (`read_all`/`read_typed`) or validate `85,576` full Pydantic `Work` models in Python when SQL queries over `factory.sqlite` suffice.

## Tasks

### Task 1 — Core service read-path fixes (benefits CLI, MCP, conductor, and Hub equally)

Every function below preserves its exact public signature, return type, semantics, and `project.index.sync()`-before-read invariant.

1. **`platform/src/factory/services/level_statement.py`:**
- `_person_reviewed(project)`: replace `read_typed(events_dir, ...)` with a synced SQL existence check `SELECT 1 FROM events WHERE actor_kind = 'human' AND type IN (...) LIMIT 1`.
- `_validation_lines(project, tier, level)`: query `events` counts for audit/calibration event types and distinct `pass_label` from `decisions`, `extraction_rows`, and `extraction_claims` instead of `read_typed`.
2. **`platform/src/factory/services/conductor.py`:**
- `_load(project)`: add a synced SQL fast-path guard `SELECT 1 FROM events WHERE type = 'conductor.started' AND actor_kind = 'system' LIMIT 1` before reading JSONL (returns `None` in milliseconds when no conductor run exists).
- `default_gate_closed(project, stage_id, gate_id)`: replace `read_all(...)` with `SELECT 1 FROM events WHERE id > :after AND actor_kind = 'human' AND type IN (...) LIMIT 1` (since `gate_act_closes` inspects only `type` and `actor_kind`).
3. **`platform/src/factory/services/gate_trust.py`:**
- `agent_labels(project, gate_id)`: return `{}` immediately when `sampled` is empty or when `SELECT 1 FROM events WHERE type = 'gate.audit_labelled' AND actor_kind = 'agent' LIMIT 1` has no row; when agent labels exist, memoise the single `read_typed` pass within `call_memo` so `trust_ledger()` does not rescan JSONL per gate (~20× per call).
4. **`platform/src/factory/services/gates.py`:**
- `_miner_resolutions(project)`: guard with `SELECT 1 FROM events WHERE type = 'extraction.resolved' LIMIT 1`; if present, replace `read_all` with `read_typed(..., ("extraction.resolved",))` and decorate with `@memoised`.
5. **`platform/src/factory/services/flow_ledger.py` & `platform/src/factory/services/prisma.py`:**
- Add a lightweight internal SQL loader (in `search.py` or `dedup.py`, e.g., `work_stubs` / `canonical_work_stubs`) reading only `work_id`, `title`, `year`, and non-probe `provenance` `(source, method, query_id, run_id)` directly from SQLite without validating `85,576` full Pydantic `Work` models (abstracts, authors, identifiers, venues).
- Switch `prisma_flow()` and `flow_ledger()` to the lightweight stubs while keeping `list_works()` / `canonical_works()` unchanged for callers requiring full `Work` models.
- Pass `ctx.graph` into `hub_payloads.overview_payload` (via `hub_build.build_overview`) so `overview` reuses the cached citation graph on `HubContext`.
6. **`platform/src/factory/services/site_search.py`:**
- `_revert_times(project)`: query `SELECT json_extract(refs, '$[0]'), MIN(ts) FROM events WHERE type = 'dedup.reverted' GROUP BY 1` formatted to `%Y-%m-%d %H:%M` instead of `read_all()`.
- `_merges(project)`: read `{work_id: title}` via `SELECT work_id, json_extract(data, '$.title') FROM works` instead of `list_works(project)`.
7. **`platform/src/factory/services/hub_build.py` event read scope:**
- Enter `reader.event_read_scope()` alongside `ctx.project.index.frozen_sync()` and `call_memo.entering()` inside `build_static` so any remaining fallback `read_typed` call scans disk at most once per build.

### Task 2 — True per-payload dependency hashing & complete `PAYLOAD_INPUTS`

1. **Decouple UI assets from payload fingerprints (`platform/src/factory/services/hub_serve.py`):**
- Remove `hub_ui.asset_version()` from `code_hash()` and payload fingerprints (assets are already cache-busted via `?v=<asset_version>` in HTML; CSS/JS edits trigger `0` payload rebuilds).
2. **Per-payload reachable Python module hash (`hub_serve.py`, mirroring `site.py`'s `product_code_hash`):**
- Walk AST imports reachable from each payload's builder function in `hub_build.BUILDERS` across `platform/src/factory/` (excluding `hub_ui/` static assets), cached by `(mtime_ns, size)` of scanned files.
- Consequence: editing a core factory service (e.g., `services/prisma.py` or `services/gates.py`) invalidates only the payloads that depend on it, and editing `hub_costs.py` invalidates only `costs`.
- Align `hub_landscape.code_stamp()` cleanly with this mechanism.
3. **Complete `PAYLOAD_INPUTS` (`platform/src/factory/services/hub_build.py`):**
- Declare conservative, accurate event-prefix tuples for every builder currently missing from `PAYLOAD_INPUTS` (`protocol`, `levels`, `pipeline`, `sources`, `method`, `write`, `platform`, `learn`, `living`, `contradictions`, `chat`, and `leaderboard` if registered), ensuring background `runner.`, `task.`, `feed.`, `watch.`, `xrun.`, `file.`, and `notice.` events only invalidate the specific operational payloads that read them (`pipeline`, `costs`, `living`).

### Task 3 — Warm persistent worker, multi-project concurrency control, and lazy classic hub

1. **Persistent warm child worker (`platform/src/factory/cli/hub.py`, `hub_build.py`, `hub_serve.py`):**
- Add an internal CLI subcommand (`factory hub worker <slug> --out <dir>`) running at `nice -n 10` that reads single-payload build requests (JSON lines on stdin), keeps one `HubContext` warm in memory across requests (auto-clearing `HubContext` whenever `last_event_id` changes), writes `<name>.json.gz` and `<name>.json` atomically, and emits a status JSON line on stdout.
- Exits after `LINGER` idle seconds or when `PayloadService` detects that the worker's code hash changed (so code edits load fresh code without restarting the server).
- Preserve the `spawn_builder` test hook/seam so `test_hub_ui_routes.py` tests (including priority queue jumping and `max(peak) == 1`) remain green.
2. **Multi-project startup & concurrency cap (`platform/src/factory/services/site_server.py`, `hub_serve.py`):**
- Add a hub-wide build semaphore (configurable, defaulting to `1` or `2` concurrent child workers across all projects in `MainHub`) so multiple projects never stampede CPU/disk simultaneously.
- Change `MainHub.prepare_all()` so listing/opening projects at startup does not trigger eager prewarming of every project under `data/projects/`; instead, prewarm starts lazily when a project is opened (or strictly on-demand per requested page), while single-project `PayloadService.prewarm()` and `FACTORY_HUB_PREWARM=1|0` keep their documented contract.
3. **Lazy classic hub (`site.py` / `site_server.py`):**
- Stop rendering `site_service.render_hub` eagerly for every project at startup; render classic hub pages lazily when classic hub routes are requested.

## Expected impact

| Operation | Current (`agentic-science`) | After Stage 1 |
|---|---|---|
| UI / CSS / JS edit | ~20 min (all ~440 payloads across 11 projects) | **0 s** (instant) |
| Single hub builder or core service edit | ~20 min | **1–15 s** (affected payloads only) |
| Full cold rebuild of `agentic-science` | ~20 min | **~30–60 s** (one warm `HubContext`, no JSONL scans, no 85k Pydantic hydration) |
| `factory site serve --all` startup (11 projects) | 11 simultaneous build storms | **< 2 s** idle startup |
| Core CLI/MCP (`prisma`, `flow`, `check`, `conductor`, `human_queue`) | 10–120+ s | **5–30× faster**, identical outputs |

## Verification & rollout (TDD + equivalence)

- **TDD (mandatory per `CLAUDE.md`):** Write failing unit/regression tests before implementing each task.
- **Touched test suites:** `test_hub_build.py`, `test_hub_ui_routes.py`, `test_hub_ui_pages.py`, `test_hub_ui_assets.py`, `test_hub_levels.py`, `test_hub_pipeline.py`, `test_hub_sources.py`, `test_hub_learn.py`, `test_hub_payloads_overview.py`, `test_hub_payloads_flow.py`, `test_prisma*.py`, `test_flow*.py`, `test_gate*.py`, `test_conductor*.py`, `test_level_statement*.py`, `test_site_main_hub*.py`.
- **Static checks:** `uv run --project platform ruff check` and `uv run --project platform mypy --strict` on all touched files.
- **Reflink pilot equivalence & benchmark** (never against live `data/`):
- Copy the pilot with `cp -a --reflink=always data <copy>` (on `/home`, outside live `data/`).
- Snapshot `prisma_flow`, `flow_ledger`, `level_statement`, `trust_ledger`, `human_queue`, `conductor_status`, and all `factory hub build` JSON payloads (ignoring only generation timestamps) before vs. after Stage 1 → require **exact data equality** and record before/after wall-clock timings.
- **Map regeneration:** Run `uv run --project platform python scripts/gen_map.py` if any CLI command or module signature changes.

## Stage 2 preview (deferred follow-up plan)

Once active worktrees finish and a `PROJECTION_VERSION` bump can be coordinated cleanly, Stage 2 builds on Stage 1 by:
1. Adding the `events(type, id)` index plus projector-maintained summary tables (`event_type_counts`, `corpus_membership`, `work_mining_state`, `work_conversion`) in `factory.sqlite` (`OMITTED_WHEN_EMPTY` + equivalence property tests).
2. Serving fast SQL-backed `/ui/data/<name>.json` payloads live on request (using a read-only WAL connection/snapshot and an in-memory watermark cache), eliminating pre-built disk JSONs and `503 Building` waits for ~25 of the 28 pages while retaining `factory hub build` as an explicit static export.

## Confirmed decisions

1. **Default prewarm mode on `factory site serve --all`:** Strictly on-demand when a page is opened (no eager prewarm of all projects at startup; single-project `PayloadService.prewarm()` and `FACTORY_HUB_PREWARM` keep their contract).
2. **Global worker concurrency cap:** `1` concurrent child build worker across all projects in `MainHub`.
3. **Classic hub (`site.py`):** Strictly lazy-on-visit rather than pre-rendered at startup.

## Measured verification results (2026-11-29, reflink copy of `agentic-science`)

- **Equivalence:** `prisma_flow`, `flow_ledger` (count + sample), `level_statement`, `trust_ledger`, `human_queue`, `conductor_status`, and hub payloads (`shell`, `overview`, `levels`, `sources`, `learn`) produced **zero non-timestamp differences** before vs. after Stage 1.
- **Hub build subset (`shell`, `overview`, `levels`, `sources`, `learn` with `frozen_sync()`):**
- Total: **401.08 s → 128.23 s (3.1× faster)**
- `levels`: **130.67 s → 5.16 s (25.3× faster)**
- `overview`: **97.75 s → 21.84 s (4.5× faster)**
- `sources`: **109.74 s → 47.94 s (2.3× faster)**
- `learn`: **52.86 s → 42.52 s**
- `shell`: **10.05 s → 10.76 s** (once per project; reused in `WarmBuilder`)
- **Standalone service calls (outside `frozen_sync()`):**
- `level_statement`: **97.40 s → 47.41 s**, `trust_ledger`: **85.75 s → 47.50 s**, `conductor_status`: **1.84 s → 0.70 s**, `prisma_flow`: **36.70 s → 39.63 s**, `flow_ledger`: **45.29 s → 47.66 s**, `human_queue`: **47.06 s → 51.25 s**.
- **Profiler finding (`cProfile` on `trust_ledger`):** `88.3 s` of `90.0 s` (98%) outside `frozen_sync()` is spent in `947` repeated `Index.sync()` calls (mostly `gates.protocol_at` calling `sync()` inside loops at ~93 ms each across `3,330` JSONL files). That explains why `levels` inside `hub_build` (`frozen_sync()`) dropped to **5.16 s**, and highlights wrapping top-level read paths in `frozen_sync()` / `call_memo` (and Stage 2's summary tables) as the next big CLI win.
56 changes: 56 additions & 0 deletions platform/src/factory/cli/hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@

from __future__ import annotations

import json
import os
import select
import sys
from pathlib import Path
from typing import Annotated

Expand Down Expand Up @@ -117,3 +121,55 @@ def hub_build_cmd(
typer.echo(f"out: {out}")
if report.errors:
raise typer.Exit(1)


@hub_app.command("worker", hidden=True)
def hub_worker_cmd(
ctx: typer.Context,
slug: Annotated[str, typer.Argument(help="Project slug.")],
out: Annotated[Path, typer.Option("--out", help="Directory to write built payloads into.")],
idle: Annotated[
float, typer.Option("--idle", help="Exit after this many idle seconds (0 waits for EOF).")
] = 10.0,
) -> None:
"""Warm payload worker: reads JSON-line requests from stdin and writes status lines."""
from factory.cli.main import _reporting_errors, _resolve_project, _state

state = _state(ctx)
state.project = slug
with _reporting_errors():
project = _resolve_project(state)
worker = hub_build.WarmBuilder(project)
while True:
if os.name != "nt" and idle > 0:
try:
sys.stdin.fileno()
except (OSError, ValueError, AttributeError):
pass
else:
ready, _, _ = select.select([sys.stdin], [], [], idle)
if not ready:
break
line = sys.stdin.readline()
if line == "":
break
if not line.strip():
continue
req = json.loads(line)
names = req.get("names") or []
target_out = Path(req["out"]) if req.get("out") else out
try:
report = worker.build_into(names, target_out)
reply: dict[str, object] = {
"ok": not report.errors,
"payloads": list(report.payloads),
"errors": report.errors,
}
except Exception as exc:
reply = {
"ok": False,
"payloads": [],
"errors": {"_request": f"{type(exc).__name__}: {exc}"},
}
sys.stdout.write(json.dumps(reply) + "\n")
sys.stdout.flush()
4 changes: 2 additions & 2 deletions platform/src/factory/services/agreement.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@

from factory.errors import FactoryValidationError, ValidationIssue
from factory.events.envelope import Actor
from factory.events.reader import read_all
from factory.events.reader import read_typed
from factory.model.base import StrictModel
from factory.model.protocol import CriterionKind, ScreeningPlan, ScreeningStage
from factory.model.screening import (
Expand Down Expand Up @@ -756,7 +756,7 @@ def _refuse_shared(project: Project, stage: ScreeningStage = TA) -> None:
ignored counts for nothing, and a malformed or human line in the log is passed over for the
same reason: a human's session is one row of the projection."""
joins: dict[PassLabel, set[str]] = {label: set() for label in PassLabel}
for event in read_all(project.paths.events_dir, project.catalog):
for event in read_typed(project.paths.events_dir, project.catalog, ("screening.pass_joined",)):
if event.type == "screening.pass_joined":
try:
payload = PassJoined.model_validate(event.payload)
Expand Down
Loading
Loading