From 357a1cc3ede84de5f5b483ef22d990ea9938144c Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 29 Nov 2026 21:31:44 +0200 Subject: [PATCH] perf(hub,core): Stage 1 & 1.5 read-path speed, per-payload invalidation, and warm worker - Replace full JSONL scans in level_statement, conductor, gate_trust, gates, site_search, agreement, and extraction_agreement with synced SQLite queries or targeted read_typed + call_memo - Add lightweight WorkStub/canonical_work_stubs for prisma_flow and flow_ledger; reuse HubContext graph in build_overview - Batch protocol lookup in gate_acts and wrap top-level read entrypoints (trust_ledger, level_statement, prisma_flow, flow_ledger, human_queue) in frozen_sync + call_memo - Decouple hub_ui.asset_version() from payload fingerprints, add AST-based per-payload payload_code_hash, and complete PAYLOAD_INPUTS - Add WarmBuilder + hidden 'factory hub worker' CLI, cap MainHub builds to 1 concurrent worker, make '--all' strictly on-demand, and render classic site.py hub lazily on visit --- docs/MAP.md | 15 +- docs/plans/2026-11-29-hub-stage1-speed.md | 114 ++++ platform/src/factory/cli/hub.py | 56 ++ platform/src/factory/services/agreement.py | 4 +- platform/src/factory/services/conductor.py | 46 +- platform/src/factory/services/dedup.py | 38 +- .../factory/services/extraction_agreement.py | 8 +- platform/src/factory/services/flow_ledger.py | 139 ++--- platform/src/factory/services/gate_trust.py | 45 +- platform/src/factory/services/gates.py | 35 +- platform/src/factory/services/hub_build.py | 151 ++++- platform/src/factory/services/hub_payloads.py | 9 +- platform/src/factory/services/hub_serve.py | 548 ++++++++++++++++-- platform/src/factory/services/human_queue.py | 190 +++--- .../src/factory/services/level_statement.py | 150 ++--- platform/src/factory/services/prisma.py | 149 ++--- platform/src/factory/services/search.py | 85 +++ platform/src/factory/services/site_search.py | 30 +- platform/src/factory/services/site_server.py | 32 +- platform/tests/test_agreement.py | 24 + platform/tests/test_conductor.py | 47 ++ platform/tests/test_flow_ledger.py | 91 ++- platform/tests/test_gate_audit.py | 65 +++ platform/tests/test_gates_service.py | 113 ++++ platform/tests/test_hub_build.py | 67 +++ platform/tests/test_hub_payloads_overview.py | 25 + platform/tests/test_hub_ui_routes.py | 140 +++++ platform/tests/test_level_statement.py | 131 +++++ platform/tests/test_site_main_hub.py | 37 ++ platform/tests/test_site_search.py | 33 ++ 30 files changed, 2199 insertions(+), 418 deletions(-) create mode 100644 docs/plans/2026-11-29-hub-stage1-speed.md diff --git a/docs/MAP.md b/docs/MAP.md index eab1d3ce..ac284faa 100644 --- a/docs/MAP.md +++ b/docs/MAP.md @@ -2,7 +2,7 @@ -Generated at commit `27d1825a` · projection version `96` · 52 stage modules · 237 event types · 235 index tables · 350 service modules · 219 MCP tools · 414 CLI commands · 38 skills. +Generated at commit `045176c9` · projection version `96` · 52 stage modules · 237 event types · 235 index tables · 350 service modules · 219 MCP tools · 415 CLI commands · 38 skills. Read [ARCHITECTURE.md](ARCHITECTURE.md) first. This file answers *where*: for each stage module, the events, models, index files, tables, task kinds, gates and checks it owns, and the services that name its events; then every MCP tool, CLI command, service and skill with what it reaches. Links are found by name (see the script's docstring), so a missing link means the code does not name the thing, not that no relation exists. Paths are relative to `platform/src/factory/` unless they start with `plugin/`. @@ -165,7 +165,7 @@ Declaration: `services/modules/dedup.py` · kind `transform` - **Tables:** `blocked_pairs` (dedup.py), `dedup_pair_decisions` (dedup.py), `merge_members` (dedup.py), `merges` (dedup.py) - **Gates:** `dedup.version_pair` (decision, floor human) - **Check codes:** `merge-verdict-conflict` -- **Services naming its events:** `services/briefing_served.py`, `services/dedup.py`, `services/site_search.py`, `services/trace.py`, `services/version_pairs.py` +- **Services naming its events:** `services/briefing_served.py`, `services/dedup.py`, `services/trace.py`, `services/version_pairs.py` ### Module: screening @@ -1281,6 +1281,7 @@ Defined in `cli/main.py` (typer); rendering in `cli/render.py` and siblings. | `factory hub build` | `access`, `access_log`, `hub_build`, `human_pass` | Write the static pages, assets and payloads to `--out` (opens from file://). | | `factory hub facets set` | `access`, `access_log`, `hub_facets`, `human_pass` | Record the hub's facets (the researcher's act); the latest list replaces the earlier. | | `factory hub facets show` | `access`, `access_log`, `hub_facets`, `human_pass` | The facets the hub shows now: key, label, miner and field, in order. | +| `factory hub worker` | `access`, `access_log`, `hub_build`, `human_pass` | Warm payload worker: reads JSON-line requests from stdin and writes status lines. | | `factory hypotheses abandon` | `access`, `access_log`, `human_pass`, `hypotheses` | Abandon a hypothesis with a reason (a human act); it stays in the log. | | `factory hypotheses conclude` | `access`, `access_log`, `human_pass`, `hypotheses` | Add a conclusion, labelled as interpretation, to an evaluated hypothesis (a human act). | | `factory hypotheses evaluate` | `access`, `access_log`, `evaluation`, `evaluation_view`, `human_pass` | Evaluate a registered hypothesis: the platform computes the outcome from the recorded runs (or the later literature) by the rule fixed at r… | @@ -1538,8 +1539,8 @@ Defined in `cli/main.py` (typer); rendering in `cli/render.py` and siblings. | Service | Purpose | Modules | MCP tools | CLI commands | | --- | --- | --- | --- | --- | -| `access` | Who may do what (slice 5 rulings 9 and 10; the spec's permissions table). | core | — | `factory activity`, `factory answers export`, `factory answers list`, `factory answers rate`, `factory answers show`, `factory appraisal agreement`, `factory appraisal audit-label`, `factory appraisal audit-report`, `factory appraisal audit-sample`, `factory appraisal judge`, `factory appraisal resolve`, `factory appraisal sheet`, `factory appraisal status`, `factory audit label`, `factory audit report`, `factory audit sample`, `factory bench level`, `factory benchmark-ledger`, `factory briefing`, `factory budget set`, `factory calibrate draw`, `factory calibrate label`, `factory cards assert`, `factory cards confirm`, `factory cards import`, `factory cards list`, `factory cards reject`, `factory cards show`, `factory chat advance`, `factory chat precision`, `factory chat request ask`, `factory chat request spar`, `factory chat requests`, `factory check`, `factory concept-links confirm`, `factory concept-links list`, `factory concept-links reject`, `factory concepts approve`, `factory concepts define`, `factory concepts history`, `factory concepts list`, `factory concepts merge`, `factory concepts reject-source`, `factory concepts review`, `factory concepts show`, `factory concepts source`, `factory concepts unmerge`, `factory conclusions diff`, `factory conclusions register`, `factory conclusions retire`, `factory conclusions status`, `factory conductor advance`, `factory conductor start`, `factory conductor status`, `factory contradictions confirm`, `factory contradictions list`, `factory contradictions reject`, `factory contributions agreement`, `factory contributions audit label`, `factory contributions audit report`, `factory contributions audit sample`, `factory contributions list`, `factory contributions pairs`, `factory contributions resolve`, `factory contributions status`, `factory curation decide`, `factory curation lessons`, `factory curation list`, `factory dashboard export`, `factory dashboard serve`, `factory decide list`, `factory decide select`, `factory decide show`, `factory dedup list`, `factory dedup pair`, `factory dedup pairs`, `factory dedup revert`, `factory dedup run`, `factory develop render`, `factory digest`, `factory directions close`, `factory document convert`, `factory document coverage`, `factory document read`, `factory document reanchor`, `factory document status`, `factory draft audit`, `factory draft create`, `factory draft label`, `factory draft list`, `factory draft release`, `factory draft render`, `factory draft reorder`, `factory draft repin`, `factory draft show`, `factory draft status`, `factory draft verify`, `factory draft withdraw`, `factory draft write`, `factory experiments accept-baseline`, `factory experiments amend`, `factory experiments deviation`, `factory experiments evaluate-baselines`, `factory experiments freeze`, `factory experiments list`, `factory experiments show`, `factory experiments unlock`, `factory export bibtex`, `factory export crate`, `factory export csl`, `factory export nanopub`, `factory export prisma`, `factory export works`, `factory extract agreement`, `factory extract audit-label`, `factory extract audit-report`, `factory extract audit-sample`, `factory extract resolve`, `factory extract status`, `factory feed run`, `factory files list`, `factory files register`, `factory files status`, `factory finders conflicts`, `factory finders gaps`, `factory fulltext fetch`, `factory fulltext import`, `factory fulltext resolve`, `factory fulltext restore`, `factory fulltext status`, `factory gate audit label`, `factory gate audit report`, `factory gate audit sample`, `factory gates`, `factory graph build`, `factory graph export`, `factory graph query`, `factory graph status`, `factory grey capture`, `factory grey contact`, `factory hub build`, `factory hub facets set`, `factory hub facets show`, `factory hypotheses abandon`, `factory hypotheses conclude`, `factory hypotheses evaluate`, `factory hypotheses list`, `factory hypotheses register`, `factory hypotheses show`, `factory ideas candidates`, `factory ideas confirm`, `factory ideas define`, `factory ideas list`, `factory ideas merge`, `factory ideas reject`, `factory ideas unmerge`, `factory import admit`, `factory import attach`, `factory import bib`, `factory import confirm`, `factory import coverage`, `factory import csl`, `factory import describe`, `factory import list`, `factory import pdfs`, `factory import reject`, `factory import resolve`, `factory import ris`, `factory import show`, `factory inbox add`, `factory inbox list`, `factory inbox prioritise`, `factory inbox resolve`, `factory inbox withdraw`, `factory interpretations history`, `factory interpretations list`, `factory interpretations review`, `factory interpretations show`, `factory interpretations supersede`, `factory interpretations write`, `factory layers move`, `factory leads candidates`, `factory leads discard`, `factory leads list`, `factory leads park`, `factory leads promote`, `factory leads queue`, `factory leads stats`, `factory ledger`, `factory library adopt`, `factory library confirm-source`, `factory library consolidate`, `factory library push`, `factory living prisma-update`, `factory living snapshot`, `factory manuscript add`, `factory manuscript audit`, `factory manuscript report`, `factory manuscript resolve`, `factory manuscript status`, `factory match`, `factory member grant`, `factory member list`, `factory member revoke`, `factory mine agreement`, `factory mine audit label`, `factory mine audit report`, `factory mine audit sample`, `factory mine import`, `factory mine request`, `factory mine resolve`, `factory mine status`, `factory miner add`, `factory miner admit`, `factory miner adopt`, `factory miner calibrate draw`, `factory miner calibrate label`, `factory miner calibrate report`, `factory miner list`, `factory miner register`, `factory miner reopen`, `factory miner retire`, `factory models cutoff`, `factory notices assess`, `factory notices check`, `factory notices list`, `factory outline`, `factory pack`, `factory pages brief`, `factory pages list`, `factory pages record`, `factory pages show`, `factory passages embed`, `factory passages status`, `factory performance`, `factory project host`, `factory project visibility`, `factory protocol confirm-press`, `factory protocol show`, `factory question show`, `factory rank compute`, `factory rank show`, `factory rebuild`, `factory references decide`, `factory references extract`, `factory references layers label`, `factory references layers sample`, `factory references layers status`, `factory references list`, `factory references re-resolve`, `factory references scheme record`, `factory references status`, `factory regions add`, `factory regions adopt`, `factory regions define`, `factory regions diff`, `factory regions export`, `factory regions link`, `factory regions links`, `factory regions list`, `factory regions proposals`, `factory regions reject`, `factory regions remove`, `factory regions review`, `factory regions revise`, `factory regions show`, `factory regions snapshot`, `factory registry`, `factory relations confirm`, `factory relations list`, `factory relations reject`, `factory report discovery`, `factory report evidence`, `factory report flow`, `factory report flow-skipped`, `factory report flow-trail`, `factory report flow-works`, `factory report methods`, `factory report prisma`, `factory report search`, `factory resume`, `factory review list`, `factory review show`, `factory runs adopt`, `factory runs list`, `factory runs record`, `factory screen disagreements`, `factory screen join`, `factory screen next`, `factory screen record`, `factory screen resolve`, `factory screen-check band`, `factory screen-check example`, `factory screen-check label`, `factory screen-check list`, `factory screen-check measure`, `factory screen-check report`, `factory screen-check tuning`, `factory search chase`, `factory search slice`, `factory seeds admit`, `factory seeds explain`, `factory seeds split`, `factory sheets balance`, `factory sheets diff`, `factory sheets export`, `factory sheets list`, `factory sheets rate`, `factory sheets show`, `factory site build`, `factory site serve`, `factory site status`, `factory snowball compare`, `factory snowball core list`, `factory snowball core mark`, `factory snowball core unmark`, `factory snowball plan`, `factory snowball run`, `factory status`, `factory suggest`, `factory taxonomy agreement`, `factory taxonomy coverage`, `factory taxonomy derive`, `factory taxonomy diff`, `factory taxonomy list`, `factory taxonomy proposals`, `factory taxonomy register`, `factory taxonomy view`, `factory technique candidates`, `factory technique challenges`, `factory technique combinations`, `factory technique gaps`, `factory technique landscape`, `factory technique neighbors`, `factory technique show`, `factory token issue`, `factory token list`, `factory token revoke`, `factory tour`, `factory trace`, `factory user add`, `factory user deactivate`, `factory user link`, `factory user list`, `factory user reactivate`, `factory versions list`, `factory versions prefer`, `factory view coverage`, `factory view horizon`, `factory view onion`, `factory view timeline`, `factory vocabulary approve`, `factory vocabulary list`, `factory vocabulary merge`, `factory vocabulary reject`, `factory vocabulary unmerge`, `factory watch plan`, `factory watch run`, `factory watch status`, `factory workspace` | -| `access_log` | The server access log (slice 5 ruling 12; plan ruling 5). | — | — | `factory activity`, `factory answers export`, `factory answers list`, `factory answers rate`, `factory answers show`, `factory appraisal agreement`, `factory appraisal audit-label`, `factory appraisal audit-report`, `factory appraisal audit-sample`, `factory appraisal judge`, `factory appraisal resolve`, `factory appraisal sheet`, `factory appraisal status`, `factory audit label`, `factory audit report`, `factory audit sample`, `factory bench level`, `factory benchmark-ledger`, `factory briefing`, `factory budget set`, `factory calibrate draw`, `factory calibrate label`, `factory cards assert`, `factory cards confirm`, `factory cards import`, `factory cards list`, `factory cards reject`, `factory cards show`, `factory chat advance`, `factory chat precision`, `factory chat request ask`, `factory chat request spar`, `factory chat requests`, `factory check`, `factory concept-links confirm`, `factory concept-links list`, `factory concept-links reject`, `factory concepts approve`, `factory concepts define`, `factory concepts history`, `factory concepts list`, `factory concepts merge`, `factory concepts reject-source`, `factory concepts review`, `factory concepts show`, `factory concepts source`, `factory concepts unmerge`, `factory conclusions diff`, `factory conclusions register`, `factory conclusions retire`, `factory conclusions status`, `factory conductor advance`, `factory conductor start`, `factory conductor status`, `factory contradictions confirm`, `factory contradictions list`, `factory contradictions reject`, `factory contributions agreement`, `factory contributions audit label`, `factory contributions audit report`, `factory contributions audit sample`, `factory contributions list`, `factory contributions pairs`, `factory contributions resolve`, `factory contributions status`, `factory curation decide`, `factory curation lessons`, `factory curation list`, `factory dashboard export`, `factory dashboard serve`, `factory decide list`, `factory decide select`, `factory decide show`, `factory dedup list`, `factory dedup pair`, `factory dedup pairs`, `factory dedup revert`, `factory dedup run`, `factory develop render`, `factory digest`, `factory directions close`, `factory document convert`, `factory document coverage`, `factory document read`, `factory document reanchor`, `factory document status`, `factory draft audit`, `factory draft create`, `factory draft label`, `factory draft list`, `factory draft release`, `factory draft render`, `factory draft reorder`, `factory draft repin`, `factory draft show`, `factory draft status`, `factory draft verify`, `factory draft withdraw`, `factory draft write`, `factory experiments accept-baseline`, `factory experiments amend`, `factory experiments deviation`, `factory experiments evaluate-baselines`, `factory experiments freeze`, `factory experiments list`, `factory experiments show`, `factory experiments unlock`, `factory export bibtex`, `factory export crate`, `factory export csl`, `factory export nanopub`, `factory export prisma`, `factory export works`, `factory extract agreement`, `factory extract audit-label`, `factory extract audit-report`, `factory extract audit-sample`, `factory extract resolve`, `factory extract status`, `factory files list`, `factory files register`, `factory files status`, `factory finders conflicts`, `factory finders gaps`, `factory fulltext fetch`, `factory fulltext import`, `factory fulltext resolve`, `factory fulltext restore`, `factory fulltext status`, `factory gate audit label`, `factory gate audit report`, `factory gate audit sample`, `factory gates`, `factory graph build`, `factory graph export`, `factory graph query`, `factory graph status`, `factory grey capture`, `factory grey contact`, `factory hub build`, `factory hub facets set`, `factory hub facets show`, `factory hypotheses abandon`, `factory hypotheses conclude`, `factory hypotheses evaluate`, `factory hypotheses list`, `factory hypotheses register`, `factory hypotheses show`, `factory ideas candidates`, `factory ideas confirm`, `factory ideas define`, `factory ideas list`, `factory ideas merge`, `factory ideas reject`, `factory ideas unmerge`, `factory import admit`, `factory import attach`, `factory import bib`, `factory import confirm`, `factory import coverage`, `factory import csl`, `factory import describe`, `factory import list`, `factory import pdfs`, `factory import reject`, `factory import resolve`, `factory import ris`, `factory import show`, `factory inbox add`, `factory inbox list`, `factory inbox prioritise`, `factory inbox resolve`, `factory inbox withdraw`, `factory interpretations history`, `factory interpretations list`, `factory interpretations review`, `factory interpretations show`, `factory interpretations supersede`, `factory interpretations write`, `factory layers move`, `factory leads candidates`, `factory leads discard`, `factory leads list`, `factory leads park`, `factory leads promote`, `factory leads queue`, `factory leads stats`, `factory ledger`, `factory library adopt`, `factory library confirm-source`, `factory library consolidate`, `factory library push`, `factory living prisma-update`, `factory living snapshot`, `factory manuscript add`, `factory manuscript audit`, `factory manuscript report`, `factory manuscript resolve`, `factory manuscript status`, `factory match`, `factory member grant`, `factory member list`, `factory member revoke`, `factory mine agreement`, `factory mine audit label`, `factory mine audit report`, `factory mine audit sample`, `factory mine import`, `factory mine request`, `factory mine resolve`, `factory mine status`, `factory miner add`, `factory miner admit`, `factory miner adopt`, `factory miner calibrate draw`, `factory miner calibrate label`, `factory miner calibrate report`, `factory miner list`, `factory miner register`, `factory miner reopen`, `factory miner retire`, `factory models cutoff`, `factory notices assess`, `factory notices check`, `factory notices list`, `factory outline`, `factory pack`, `factory pages brief`, `factory pages list`, `factory pages record`, `factory pages show`, `factory passages embed`, `factory passages status`, `factory performance`, `factory project host`, `factory protocol confirm-press`, `factory protocol show`, `factory question show`, `factory rank compute`, `factory rank show`, `factory rebuild`, `factory references decide`, `factory references extract`, `factory references layers label`, `factory references layers sample`, `factory references layers status`, `factory references list`, `factory references re-resolve`, `factory references scheme record`, `factory references status`, `factory regions add`, `factory regions adopt`, `factory regions define`, `factory regions diff`, `factory regions export`, `factory regions link`, `factory regions links`, `factory regions list`, `factory regions proposals`, `factory regions reject`, `factory regions remove`, `factory regions review`, `factory regions revise`, `factory regions show`, `factory regions snapshot`, `factory registry`, `factory relations confirm`, `factory relations list`, `factory relations reject`, `factory report discovery`, `factory report evidence`, `factory report flow`, `factory report flow-skipped`, `factory report flow-trail`, `factory report flow-works`, `factory report methods`, `factory report prisma`, `factory report search`, `factory resume`, `factory runs adopt`, `factory runs list`, `factory runs record`, `factory screen disagreements`, `factory screen join`, `factory screen next`, `factory screen record`, `factory screen resolve`, `factory screen-check band`, `factory screen-check example`, `factory screen-check label`, `factory screen-check list`, `factory screen-check measure`, `factory screen-check report`, `factory screen-check tuning`, `factory search chase`, `factory search slice`, `factory seeds admit`, `factory seeds explain`, `factory seeds split`, `factory server init`, `factory sheets balance`, `factory sheets diff`, `factory sheets export`, `factory sheets list`, `factory sheets rate`, `factory sheets show`, `factory site build`, `factory site serve`, `factory site status`, `factory snowball compare`, `factory snowball core list`, `factory snowball core mark`, `factory snowball core unmark`, `factory snowball plan`, `factory snowball run`, `factory status`, `factory suggest`, `factory taxonomy agreement`, `factory taxonomy coverage`, `factory taxonomy derive`, `factory taxonomy diff`, `factory taxonomy list`, `factory taxonomy proposals`, `factory taxonomy register`, `factory taxonomy view`, `factory technique candidates`, `factory technique challenges`, `factory technique combinations`, `factory technique gaps`, `factory technique landscape`, `factory technique neighbors`, `factory technique show`, `factory token issue`, `factory token list`, `factory token revoke`, `factory tour`, `factory trace`, `factory user add`, `factory user deactivate`, `factory user link`, `factory user list`, `factory user reactivate`, `factory versions list`, `factory versions prefer`, `factory view coverage`, `factory view horizon`, `factory view onion`, `factory view timeline`, `factory vocabulary approve`, `factory vocabulary list`, `factory vocabulary merge`, `factory vocabulary reject`, `factory vocabulary unmerge`, `factory watch plan`, `factory watch run`, `factory watch status` | +| `access` | Who may do what (slice 5 rulings 9 and 10; the spec's permissions table). | core | — | `factory activity`, `factory answers export`, `factory answers list`, `factory answers rate`, `factory answers show`, `factory appraisal agreement`, `factory appraisal audit-label`, `factory appraisal audit-report`, `factory appraisal audit-sample`, `factory appraisal judge`, `factory appraisal resolve`, `factory appraisal sheet`, `factory appraisal status`, `factory audit label`, `factory audit report`, `factory audit sample`, `factory bench level`, `factory benchmark-ledger`, `factory briefing`, `factory budget set`, `factory calibrate draw`, `factory calibrate label`, `factory cards assert`, `factory cards confirm`, `factory cards import`, `factory cards list`, `factory cards reject`, `factory cards show`, `factory chat advance`, `factory chat precision`, `factory chat request ask`, `factory chat request spar`, `factory chat requests`, `factory check`, `factory concept-links confirm`, `factory concept-links list`, `factory concept-links reject`, `factory concepts approve`, `factory concepts define`, `factory concepts history`, `factory concepts list`, `factory concepts merge`, `factory concepts reject-source`, `factory concepts review`, `factory concepts show`, `factory concepts source`, `factory concepts unmerge`, `factory conclusions diff`, `factory conclusions register`, `factory conclusions retire`, `factory conclusions status`, `factory conductor advance`, `factory conductor start`, `factory conductor status`, `factory contradictions confirm`, `factory contradictions list`, `factory contradictions reject`, `factory contributions agreement`, `factory contributions audit label`, `factory contributions audit report`, `factory contributions audit sample`, `factory contributions list`, `factory contributions pairs`, `factory contributions resolve`, `factory contributions status`, `factory curation decide`, `factory curation lessons`, `factory curation list`, `factory dashboard export`, `factory dashboard serve`, `factory decide list`, `factory decide select`, `factory decide show`, `factory dedup list`, `factory dedup pair`, `factory dedup pairs`, `factory dedup revert`, `factory dedup run`, `factory develop render`, `factory digest`, `factory directions close`, `factory document convert`, `factory document coverage`, `factory document read`, `factory document reanchor`, `factory document status`, `factory draft audit`, `factory draft create`, `factory draft label`, `factory draft list`, `factory draft release`, `factory draft render`, `factory draft reorder`, `factory draft repin`, `factory draft show`, `factory draft status`, `factory draft verify`, `factory draft withdraw`, `factory draft write`, `factory experiments accept-baseline`, `factory experiments amend`, `factory experiments deviation`, `factory experiments evaluate-baselines`, `factory experiments freeze`, `factory experiments list`, `factory experiments show`, `factory experiments unlock`, `factory export bibtex`, `factory export crate`, `factory export csl`, `factory export nanopub`, `factory export prisma`, `factory export works`, `factory extract agreement`, `factory extract audit-label`, `factory extract audit-report`, `factory extract audit-sample`, `factory extract resolve`, `factory extract status`, `factory feed run`, `factory files list`, `factory files register`, `factory files status`, `factory finders conflicts`, `factory finders gaps`, `factory fulltext fetch`, `factory fulltext import`, `factory fulltext resolve`, `factory fulltext restore`, `factory fulltext status`, `factory gate audit label`, `factory gate audit report`, `factory gate audit sample`, `factory gates`, `factory graph build`, `factory graph export`, `factory graph query`, `factory graph status`, `factory grey capture`, `factory grey contact`, `factory hub build`, `factory hub facets set`, `factory hub facets show`, `factory hub worker`, `factory hypotheses abandon`, `factory hypotheses conclude`, `factory hypotheses evaluate`, `factory hypotheses list`, `factory hypotheses register`, `factory hypotheses show`, `factory ideas candidates`, `factory ideas confirm`, `factory ideas define`, `factory ideas list`, `factory ideas merge`, `factory ideas reject`, `factory ideas unmerge`, `factory import admit`, `factory import attach`, `factory import bib`, `factory import confirm`, `factory import coverage`, `factory import csl`, `factory import describe`, `factory import list`, `factory import pdfs`, `factory import reject`, `factory import resolve`, `factory import ris`, `factory import show`, `factory inbox add`, `factory inbox list`, `factory inbox prioritise`, `factory inbox resolve`, `factory inbox withdraw`, `factory interpretations history`, `factory interpretations list`, `factory interpretations review`, `factory interpretations show`, `factory interpretations supersede`, `factory interpretations write`, `factory layers move`, `factory leads candidates`, `factory leads discard`, `factory leads list`, `factory leads park`, `factory leads promote`, `factory leads queue`, `factory leads stats`, `factory ledger`, `factory library adopt`, `factory library confirm-source`, `factory library consolidate`, `factory library push`, `factory living prisma-update`, `factory living snapshot`, `factory manuscript add`, `factory manuscript audit`, `factory manuscript report`, `factory manuscript resolve`, `factory manuscript status`, `factory match`, `factory member grant`, `factory member list`, `factory member revoke`, `factory mine agreement`, `factory mine audit label`, `factory mine audit report`, `factory mine audit sample`, `factory mine import`, `factory mine request`, `factory mine resolve`, `factory mine status`, `factory miner add`, `factory miner admit`, `factory miner adopt`, `factory miner calibrate draw`, `factory miner calibrate label`, `factory miner calibrate report`, `factory miner list`, `factory miner register`, `factory miner reopen`, `factory miner retire`, `factory models cutoff`, `factory notices assess`, `factory notices check`, `factory notices list`, `factory outline`, `factory pack`, `factory pages brief`, `factory pages list`, `factory pages record`, `factory pages show`, `factory passages embed`, `factory passages status`, `factory performance`, `factory project host`, `factory project visibility`, `factory protocol confirm-press`, `factory protocol show`, `factory question show`, `factory rank compute`, `factory rank show`, `factory rebuild`, `factory references decide`, `factory references extract`, `factory references layers label`, `factory references layers sample`, `factory references layers status`, `factory references list`, `factory references re-resolve`, `factory references scheme record`, `factory references status`, `factory regions add`, `factory regions adopt`, `factory regions define`, `factory regions diff`, `factory regions export`, `factory regions link`, `factory regions links`, `factory regions list`, `factory regions proposals`, `factory regions reject`, `factory regions remove`, `factory regions review`, `factory regions revise`, `factory regions show`, `factory regions snapshot`, `factory registry`, `factory relations confirm`, `factory relations list`, `factory relations reject`, `factory report discovery`, `factory report evidence`, `factory report flow`, `factory report flow-skipped`, `factory report flow-trail`, `factory report flow-works`, `factory report methods`, `factory report prisma`, `factory report search`, `factory resume`, `factory review list`, `factory review show`, `factory runs adopt`, `factory runs list`, `factory runs record`, `factory screen disagreements`, `factory screen join`, `factory screen next`, `factory screen record`, `factory screen resolve`, `factory screen-check band`, `factory screen-check example`, `factory screen-check label`, `factory screen-check list`, `factory screen-check measure`, `factory screen-check report`, `factory screen-check tuning`, `factory search chase`, `factory search slice`, `factory seeds admit`, `factory seeds explain`, `factory seeds split`, `factory sheets balance`, `factory sheets diff`, `factory sheets export`, `factory sheets list`, `factory sheets rate`, `factory sheets show`, `factory site build`, `factory site serve`, `factory site status`, `factory snowball compare`, `factory snowball core list`, `factory snowball core mark`, `factory snowball core unmark`, `factory snowball plan`, `factory snowball run`, `factory status`, `factory suggest`, `factory taxonomy agreement`, `factory taxonomy coverage`, `factory taxonomy derive`, `factory taxonomy diff`, `factory taxonomy list`, `factory taxonomy proposals`, `factory taxonomy register`, `factory taxonomy view`, `factory technique candidates`, `factory technique challenges`, `factory technique combinations`, `factory technique gaps`, `factory technique landscape`, `factory technique neighbors`, `factory technique show`, `factory token issue`, `factory token list`, `factory token revoke`, `factory tour`, `factory trace`, `factory user add`, `factory user deactivate`, `factory user link`, `factory user list`, `factory user reactivate`, `factory versions list`, `factory versions prefer`, `factory view coverage`, `factory view horizon`, `factory view onion`, `factory view timeline`, `factory vocabulary approve`, `factory vocabulary list`, `factory vocabulary merge`, `factory vocabulary reject`, `factory vocabulary unmerge`, `factory watch plan`, `factory watch run`, `factory watch status`, `factory workspace` | +| `access_log` | The server access log (slice 5 ruling 12; plan ruling 5). | — | — | `factory activity`, `factory answers export`, `factory answers list`, `factory answers rate`, `factory answers show`, `factory appraisal agreement`, `factory appraisal audit-label`, `factory appraisal audit-report`, `factory appraisal audit-sample`, `factory appraisal judge`, `factory appraisal resolve`, `factory appraisal sheet`, `factory appraisal status`, `factory audit label`, `factory audit report`, `factory audit sample`, `factory bench level`, `factory benchmark-ledger`, `factory briefing`, `factory budget set`, `factory calibrate draw`, `factory calibrate label`, `factory cards assert`, `factory cards confirm`, `factory cards import`, `factory cards list`, `factory cards reject`, `factory cards show`, `factory chat advance`, `factory chat precision`, `factory chat request ask`, `factory chat request spar`, `factory chat requests`, `factory check`, `factory concept-links confirm`, `factory concept-links list`, `factory concept-links reject`, `factory concepts approve`, `factory concepts define`, `factory concepts history`, `factory concepts list`, `factory concepts merge`, `factory concepts reject-source`, `factory concepts review`, `factory concepts show`, `factory concepts source`, `factory concepts unmerge`, `factory conclusions diff`, `factory conclusions register`, `factory conclusions retire`, `factory conclusions status`, `factory conductor advance`, `factory conductor start`, `factory conductor status`, `factory contradictions confirm`, `factory contradictions list`, `factory contradictions reject`, `factory contributions agreement`, `factory contributions audit label`, `factory contributions audit report`, `factory contributions audit sample`, `factory contributions list`, `factory contributions pairs`, `factory contributions resolve`, `factory contributions status`, `factory curation decide`, `factory curation lessons`, `factory curation list`, `factory dashboard export`, `factory dashboard serve`, `factory decide list`, `factory decide select`, `factory decide show`, `factory dedup list`, `factory dedup pair`, `factory dedup pairs`, `factory dedup revert`, `factory dedup run`, `factory develop render`, `factory digest`, `factory directions close`, `factory document convert`, `factory document coverage`, `factory document read`, `factory document reanchor`, `factory document status`, `factory draft audit`, `factory draft create`, `factory draft label`, `factory draft list`, `factory draft release`, `factory draft render`, `factory draft reorder`, `factory draft repin`, `factory draft show`, `factory draft status`, `factory draft verify`, `factory draft withdraw`, `factory draft write`, `factory experiments accept-baseline`, `factory experiments amend`, `factory experiments deviation`, `factory experiments evaluate-baselines`, `factory experiments freeze`, `factory experiments list`, `factory experiments show`, `factory experiments unlock`, `factory export bibtex`, `factory export crate`, `factory export csl`, `factory export nanopub`, `factory export prisma`, `factory export works`, `factory extract agreement`, `factory extract audit-label`, `factory extract audit-report`, `factory extract audit-sample`, `factory extract resolve`, `factory extract status`, `factory files list`, `factory files register`, `factory files status`, `factory finders conflicts`, `factory finders gaps`, `factory fulltext fetch`, `factory fulltext import`, `factory fulltext resolve`, `factory fulltext restore`, `factory fulltext status`, `factory gate audit label`, `factory gate audit report`, `factory gate audit sample`, `factory gates`, `factory graph build`, `factory graph export`, `factory graph query`, `factory graph status`, `factory grey capture`, `factory grey contact`, `factory hub build`, `factory hub facets set`, `factory hub facets show`, `factory hub worker`, `factory hypotheses abandon`, `factory hypotheses conclude`, `factory hypotheses evaluate`, `factory hypotheses list`, `factory hypotheses register`, `factory hypotheses show`, `factory ideas candidates`, `factory ideas confirm`, `factory ideas define`, `factory ideas list`, `factory ideas merge`, `factory ideas reject`, `factory ideas unmerge`, `factory import admit`, `factory import attach`, `factory import bib`, `factory import confirm`, `factory import coverage`, `factory import csl`, `factory import describe`, `factory import list`, `factory import pdfs`, `factory import reject`, `factory import resolve`, `factory import ris`, `factory import show`, `factory inbox add`, `factory inbox list`, `factory inbox prioritise`, `factory inbox resolve`, `factory inbox withdraw`, `factory interpretations history`, `factory interpretations list`, `factory interpretations review`, `factory interpretations show`, `factory interpretations supersede`, `factory interpretations write`, `factory layers move`, `factory leads candidates`, `factory leads discard`, `factory leads list`, `factory leads park`, `factory leads promote`, `factory leads queue`, `factory leads stats`, `factory ledger`, `factory library adopt`, `factory library confirm-source`, `factory library consolidate`, `factory library push`, `factory living prisma-update`, `factory living snapshot`, `factory manuscript add`, `factory manuscript audit`, `factory manuscript report`, `factory manuscript resolve`, `factory manuscript status`, `factory match`, `factory member grant`, `factory member list`, `factory member revoke`, `factory mine agreement`, `factory mine audit label`, `factory mine audit report`, `factory mine audit sample`, `factory mine import`, `factory mine request`, `factory mine resolve`, `factory mine status`, `factory miner add`, `factory miner admit`, `factory miner adopt`, `factory miner calibrate draw`, `factory miner calibrate label`, `factory miner calibrate report`, `factory miner list`, `factory miner register`, `factory miner reopen`, `factory miner retire`, `factory models cutoff`, `factory notices assess`, `factory notices check`, `factory notices list`, `factory outline`, `factory pack`, `factory pages brief`, `factory pages list`, `factory pages record`, `factory pages show`, `factory passages embed`, `factory passages status`, `factory performance`, `factory project host`, `factory protocol confirm-press`, `factory protocol show`, `factory question show`, `factory rank compute`, `factory rank show`, `factory rebuild`, `factory references decide`, `factory references extract`, `factory references layers label`, `factory references layers sample`, `factory references layers status`, `factory references list`, `factory references re-resolve`, `factory references scheme record`, `factory references status`, `factory regions add`, `factory regions adopt`, `factory regions define`, `factory regions diff`, `factory regions export`, `factory regions link`, `factory regions links`, `factory regions list`, `factory regions proposals`, `factory regions reject`, `factory regions remove`, `factory regions review`, `factory regions revise`, `factory regions show`, `factory regions snapshot`, `factory registry`, `factory relations confirm`, `factory relations list`, `factory relations reject`, `factory report discovery`, `factory report evidence`, `factory report flow`, `factory report flow-skipped`, `factory report flow-trail`, `factory report flow-works`, `factory report methods`, `factory report prisma`, `factory report search`, `factory resume`, `factory runs adopt`, `factory runs list`, `factory runs record`, `factory screen disagreements`, `factory screen join`, `factory screen next`, `factory screen record`, `factory screen resolve`, `factory screen-check band`, `factory screen-check example`, `factory screen-check label`, `factory screen-check list`, `factory screen-check measure`, `factory screen-check report`, `factory screen-check tuning`, `factory search chase`, `factory search slice`, `factory seeds admit`, `factory seeds explain`, `factory seeds split`, `factory server init`, `factory sheets balance`, `factory sheets diff`, `factory sheets export`, `factory sheets list`, `factory sheets rate`, `factory sheets show`, `factory site build`, `factory site serve`, `factory site status`, `factory snowball compare`, `factory snowball core list`, `factory snowball core mark`, `factory snowball core unmark`, `factory snowball plan`, `factory snowball run`, `factory status`, `factory suggest`, `factory taxonomy agreement`, `factory taxonomy coverage`, `factory taxonomy derive`, `factory taxonomy diff`, `factory taxonomy list`, `factory taxonomy proposals`, `factory taxonomy register`, `factory taxonomy view`, `factory technique candidates`, `factory technique challenges`, `factory technique combinations`, `factory technique gaps`, `factory technique landscape`, `factory technique neighbors`, `factory technique show`, `factory token issue`, `factory token list`, `factory token revoke`, `factory tour`, `factory trace`, `factory user add`, `factory user deactivate`, `factory user link`, `factory user list`, `factory user reactivate`, `factory versions list`, `factory versions prefer`, `factory view coverage`, `factory view horizon`, `factory view onion`, `factory view timeline`, `factory vocabulary approve`, `factory vocabulary list`, `factory vocabulary merge`, `factory vocabulary reject`, `factory vocabulary unmerge`, `factory watch plan`, `factory watch run`, `factory watch status` | | `activity` | What the agents are working on now (IDEA-98): one reading of the claimed tasks, the open passes, the platform's long op… | — | — | `factory activity` | | `agent_view` | The agent view of the report surfaces, shared by MCP and by the CLI of a person without the full view (slice 5 ruling 2… | experiments | `benchmark_ledger_view`, `card_assert`, `card_create`, `card_view`, `check`, `concept_link`, `concept_propose`, `consolidation_next`, `consolidation_propose`, `contradiction_propose`, `draft_create`, `draft_next`, `draft_release`, `draft_render`, `draft_reorder`, `draft_repin`, `draft_status`, `draft_verify_next`, `draft_verify_record`, `draft_write`, `experiment_design`, `experiment_view`, `finder_contradictions`, `finder_gaps`, `flow_skipped`, `flow_trail`, `flow_works`, `graph_export`, `graph_query`, `graph_status`, `hypothesis_draft`, `hypothesis_register`, `hypothesis_review`, `hypothesis_review_next`, `hypothesis_view`, `interpretation_list`, `interpretation_record`, `intuition_next`, `label_apply`, `lead_decide`, `lead_record`, `manuscript_read`, `manuscript_verify_next`, `manuscript_verify_record`, `match_query`, `mine_disagreements`, `mine_next`, `mine_resolve`, `project_status`, `region_propose`, `region_propose_member`, `region_query`, `region_snapshot`, `region_status`, `registry_query`, `report_discovery`, `report_evidence`, `report_methods`, `report_prisma`, `report_search`, `term_list`, `trace`, `view_coverage`, `view_horizon`, `view_onion`, `view_timeline`, `writing_outline`, `xrun_list`, `xrun_register` | `factory check`, `factory decide list`, `factory decide show`, `factory develop render`, `factory report discovery`, `factory report evidence`, `factory report flow`, `factory report flow-skipped`, `factory report flow-trail`, `factory report flow-works`, `factory report methods`, `factory report prisma`, `factory report search`, `factory review list`, `factory review show`, `factory screen next`, `factory screen record`, `factory status`, `factory trace`, `factory workspace` | | `agreement` | Agreement between the two screening passes, κ per criterion, human resolution, final outcomes (R-36, R-38, ruling 1). | screening | `audit_sample`, `screen_agreement` | `factory audit sample`, `factory screen disagreements`, `factory screen resolve` | @@ -1647,7 +1648,7 @@ Defined in `cli/main.py` (typer); rendering in `cli/render.py` and siblings. | `hint_input` | A human's capture hints as typed, resolved into the recorded `CaptureHints` (IDEA-81). | — | `inbox_add` | `factory feed add`, `factory feed send`, `factory inbox add` | | `horizon` | Time-oriented views: the record timeline of one comparability group and the horizon activity series (slice 7b, plan V-B… | — | `view_horizon`, `view_timeline` | `factory view horizon`, `factory view timeline` | | `hosting` | Hosting: one writer per hosted project (slice 5 rulings 2 and 19). | core | — | `factory project host` | -| `hub_build` | Static build of the hub v2 pages (plan hub-ui): payload registry, pages and a build report. | — | — | `factory hub build` | +| `hub_build` | Static build of the hub v2 pages (plan hub-ui): payload registry, pages and a build report. | — | — | `factory hub build`, `factory hub worker` | | `hub_chat` | Payload and researcher acts of the hub Chat page (night feature N5; ruling 8: an agent proposes, the researcher rates a… | — | — | — | | `hub_contradictions` | Payload of the hub Contradictions page: pairs of claims that conflict, grouped by topic (night feature N10; ruling 8: t… | contradictions | — | — | | `hub_costs` | The `costs` hub payload (plan hub-ui, page "Costs & runs"): run costs, budgets and run files. | — | — | — | @@ -1678,7 +1679,7 @@ Defined in `cli/main.py` (typer); rendering in `cli/render.py` and siblings. | `hub_ui` | Hub UI assets, colour tokens, glossary and labels. | — | — | — | | `hub_write` | The `write` hub payload: synthesis pages, bibliography, PRISMA diagram and wiki vault pointer. | — | — | — | | `human_channel` | Human acts by channel: what is refused, and what is counted (slice 5 ruling 11, R-111). | core, decisions, extraction, living, mining, screening | — | — | -| `human_pass` | What a person may see and run while they screen a pass (slice 5 rulings 15 and 20, R-110). | — | — | `factory activity`, `factory answers export`, `factory answers list`, `factory answers rate`, `factory answers show`, `factory appraisal agreement`, `factory appraisal audit-label`, `factory appraisal audit-report`, `factory appraisal audit-sample`, `factory appraisal judge`, `factory appraisal resolve`, `factory appraisal sheet`, `factory appraisal status`, `factory audit label`, `factory audit report`, `factory audit sample`, `factory bench level`, `factory benchmark-ledger`, `factory briefing`, `factory calibrate draw`, `factory calibrate label`, `factory cards assert`, `factory cards confirm`, `factory cards import`, `factory cards list`, `factory cards reject`, `factory cards show`, `factory chat advance`, `factory chat precision`, `factory chat request ask`, `factory chat request spar`, `factory chat requests`, `factory check`, `factory concept-links confirm`, `factory concept-links list`, `factory concept-links reject`, `factory concepts approve`, `factory concepts define`, `factory concepts history`, `factory concepts list`, `factory concepts merge`, `factory concepts reject-source`, `factory concepts review`, `factory concepts show`, `factory concepts source`, `factory concepts unmerge`, `factory conclusions diff`, `factory conclusions register`, `factory conclusions retire`, `factory conclusions status`, `factory conductor advance`, `factory conductor start`, `factory conductor status`, `factory contradictions confirm`, `factory contradictions list`, `factory contradictions reject`, `factory contributions agreement`, `factory contributions audit label`, `factory contributions audit report`, `factory contributions audit sample`, `factory contributions list`, `factory contributions pairs`, `factory contributions resolve`, `factory contributions status`, `factory curation decide`, `factory curation lessons`, `factory curation list`, `factory dashboard export`, `factory dashboard serve`, `factory decide list`, `factory decide select`, `factory decide show`, `factory dedup list`, `factory dedup pair`, `factory dedup pairs`, `factory dedup revert`, `factory dedup run`, `factory develop render`, `factory digest`, `factory directions close`, `factory document convert`, `factory document coverage`, `factory document read`, `factory document reanchor`, `factory document status`, `factory draft audit`, `factory draft create`, `factory draft label`, `factory draft list`, `factory draft release`, `factory draft render`, `factory draft reorder`, `factory draft repin`, `factory draft show`, `factory draft status`, `factory draft verify`, `factory draft withdraw`, `factory draft write`, `factory experiments accept-baseline`, `factory experiments amend`, `factory experiments deviation`, `factory experiments evaluate-baselines`, `factory experiments freeze`, `factory experiments list`, `factory experiments show`, `factory experiments unlock`, `factory export bibtex`, `factory export crate`, `factory export csl`, `factory export nanopub`, `factory export prisma`, `factory export works`, `factory extract agreement`, `factory extract audit-label`, `factory extract audit-report`, `factory extract audit-sample`, `factory extract resolve`, `factory extract status`, `factory files list`, `factory files register`, `factory files status`, `factory finders conflicts`, `factory finders gaps`, `factory fulltext fetch`, `factory fulltext import`, `factory fulltext resolve`, `factory fulltext restore`, `factory fulltext status`, `factory gate audit label`, `factory gate audit report`, `factory gate audit sample`, `factory gates`, `factory graph build`, `factory graph export`, `factory graph query`, `factory graph status`, `factory grey capture`, `factory grey contact`, `factory hub build`, `factory hub facets set`, `factory hub facets show`, `factory hypotheses abandon`, `factory hypotheses conclude`, `factory hypotheses evaluate`, `factory hypotheses list`, `factory hypotheses register`, `factory hypotheses show`, `factory ideas candidates`, `factory ideas confirm`, `factory ideas define`, `factory ideas list`, `factory ideas merge`, `factory ideas reject`, `factory ideas unmerge`, `factory import admit`, `factory import attach`, `factory import bib`, `factory import confirm`, `factory import coverage`, `factory import csl`, `factory import describe`, `factory import list`, `factory import pdfs`, `factory import reject`, `factory import resolve`, `factory import ris`, `factory import show`, `factory inbox add`, `factory inbox list`, `factory inbox prioritise`, `factory inbox resolve`, `factory inbox withdraw`, `factory interpretations history`, `factory interpretations list`, `factory interpretations review`, `factory interpretations show`, `factory interpretations supersede`, `factory interpretations write`, `factory layers move`, `factory leads candidates`, `factory leads discard`, `factory leads list`, `factory leads park`, `factory leads promote`, `factory leads queue`, `factory leads stats`, `factory living prisma-update`, `factory living snapshot`, `factory manuscript add`, `factory manuscript audit`, `factory manuscript report`, `factory manuscript resolve`, `factory manuscript status`, `factory match`, `factory mine agreement`, `factory mine audit label`, `factory mine audit report`, `factory mine audit sample`, `factory mine import`, `factory mine request`, `factory mine resolve`, `factory mine status`, `factory miner add`, `factory miner admit`, `factory miner adopt`, `factory miner calibrate draw`, `factory miner calibrate label`, `factory miner calibrate report`, `factory miner list`, `factory miner register`, `factory miner reopen`, `factory miner retire`, `factory models cutoff`, `factory notices assess`, `factory notices check`, `factory notices list`, `factory outline`, `factory pack`, `factory pages brief`, `factory pages list`, `factory pages record`, `factory pages show`, `factory passages embed`, `factory passages status`, `factory performance`, `factory protocol confirm-press`, `factory protocol show`, `factory question show`, `factory rank compute`, `factory rank show`, `factory rebuild`, `factory references decide`, `factory references extract`, `factory references layers label`, `factory references layers sample`, `factory references layers status`, `factory references list`, `factory references re-resolve`, `factory references scheme record`, `factory references status`, `factory regions add`, `factory regions adopt`, `factory regions define`, `factory regions diff`, `factory regions export`, `factory regions link`, `factory regions links`, `factory regions list`, `factory regions proposals`, `factory regions reject`, `factory regions remove`, `factory regions review`, `factory regions revise`, `factory regions show`, `factory regions snapshot`, `factory registry`, `factory relations confirm`, `factory relations list`, `factory relations reject`, `factory report discovery`, `factory report evidence`, `factory report flow`, `factory report flow-skipped`, `factory report flow-trail`, `factory report flow-works`, `factory report methods`, `factory report prisma`, `factory report search`, `factory runs adopt`, `factory runs list`, `factory runs record`, `factory screen disagreements`, `factory screen join`, `factory screen next`, `factory screen record`, `factory screen resolve`, `factory screen-check band`, `factory screen-check example`, `factory screen-check label`, `factory screen-check list`, `factory screen-check measure`, `factory screen-check report`, `factory screen-check tuning`, `factory search chase`, `factory search slice`, `factory seeds admit`, `factory seeds explain`, `factory seeds split`, `factory sheets balance`, `factory sheets diff`, `factory sheets export`, `factory sheets list`, `factory sheets rate`, `factory sheets show`, `factory site build`, `factory site serve`, `factory site status`, `factory snowball compare`, `factory snowball core list`, `factory snowball core mark`, `factory snowball core unmark`, `factory snowball plan`, `factory snowball run`, `factory status`, `factory suggest`, `factory taxonomy agreement`, `factory taxonomy coverage`, `factory taxonomy derive`, `factory taxonomy diff`, `factory taxonomy list`, `factory taxonomy proposals`, `factory taxonomy register`, `factory taxonomy view`, `factory technique candidates`, `factory technique challenges`, `factory technique combinations`, `factory technique gaps`, `factory technique landscape`, `factory technique neighbors`, `factory technique show`, `factory tour`, `factory trace`, `factory versions list`, `factory versions prefer`, `factory view coverage`, `factory view horizon`, `factory view onion`, `factory view timeline`, `factory vocabulary approve`, `factory vocabulary list`, `factory vocabulary merge`, `factory vocabulary reject`, `factory vocabulary unmerge`, `factory watch plan`, `factory watch run`, `factory watch status` | +| `human_pass` | What a person may see and run while they screen a pass (slice 5 rulings 15 and 20, R-110). | — | — | `factory activity`, `factory answers export`, `factory answers list`, `factory answers rate`, `factory answers show`, `factory appraisal agreement`, `factory appraisal audit-label`, `factory appraisal audit-report`, `factory appraisal audit-sample`, `factory appraisal judge`, `factory appraisal resolve`, `factory appraisal sheet`, `factory appraisal status`, `factory audit label`, `factory audit report`, `factory audit sample`, `factory bench level`, `factory benchmark-ledger`, `factory briefing`, `factory calibrate draw`, `factory calibrate label`, `factory cards assert`, `factory cards confirm`, `factory cards import`, `factory cards list`, `factory cards reject`, `factory cards show`, `factory chat advance`, `factory chat precision`, `factory chat request ask`, `factory chat request spar`, `factory chat requests`, `factory check`, `factory concept-links confirm`, `factory concept-links list`, `factory concept-links reject`, `factory concepts approve`, `factory concepts define`, `factory concepts history`, `factory concepts list`, `factory concepts merge`, `factory concepts reject-source`, `factory concepts review`, `factory concepts show`, `factory concepts source`, `factory concepts unmerge`, `factory conclusions diff`, `factory conclusions register`, `factory conclusions retire`, `factory conclusions status`, `factory conductor advance`, `factory conductor start`, `factory conductor status`, `factory contradictions confirm`, `factory contradictions list`, `factory contradictions reject`, `factory contributions agreement`, `factory contributions audit label`, `factory contributions audit report`, `factory contributions audit sample`, `factory contributions list`, `factory contributions pairs`, `factory contributions resolve`, `factory contributions status`, `factory curation decide`, `factory curation lessons`, `factory curation list`, `factory dashboard export`, `factory dashboard serve`, `factory decide list`, `factory decide select`, `factory decide show`, `factory dedup list`, `factory dedup pair`, `factory dedup pairs`, `factory dedup revert`, `factory dedup run`, `factory develop render`, `factory digest`, `factory directions close`, `factory document convert`, `factory document coverage`, `factory document read`, `factory document reanchor`, `factory document status`, `factory draft audit`, `factory draft create`, `factory draft label`, `factory draft list`, `factory draft release`, `factory draft render`, `factory draft reorder`, `factory draft repin`, `factory draft show`, `factory draft status`, `factory draft verify`, `factory draft withdraw`, `factory draft write`, `factory experiments accept-baseline`, `factory experiments amend`, `factory experiments deviation`, `factory experiments evaluate-baselines`, `factory experiments freeze`, `factory experiments list`, `factory experiments show`, `factory experiments unlock`, `factory export bibtex`, `factory export crate`, `factory export csl`, `factory export nanopub`, `factory export prisma`, `factory export works`, `factory extract agreement`, `factory extract audit-label`, `factory extract audit-report`, `factory extract audit-sample`, `factory extract resolve`, `factory extract status`, `factory files list`, `factory files register`, `factory files status`, `factory finders conflicts`, `factory finders gaps`, `factory fulltext fetch`, `factory fulltext import`, `factory fulltext resolve`, `factory fulltext restore`, `factory fulltext status`, `factory gate audit label`, `factory gate audit report`, `factory gate audit sample`, `factory gates`, `factory graph build`, `factory graph export`, `factory graph query`, `factory graph status`, `factory grey capture`, `factory grey contact`, `factory hub build`, `factory hub facets set`, `factory hub facets show`, `factory hub worker`, `factory hypotheses abandon`, `factory hypotheses conclude`, `factory hypotheses evaluate`, `factory hypotheses list`, `factory hypotheses register`, `factory hypotheses show`, `factory ideas candidates`, `factory ideas confirm`, `factory ideas define`, `factory ideas list`, `factory ideas merge`, `factory ideas reject`, `factory ideas unmerge`, `factory import admit`, `factory import attach`, `factory import bib`, `factory import confirm`, `factory import coverage`, `factory import csl`, `factory import describe`, `factory import list`, `factory import pdfs`, `factory import reject`, `factory import resolve`, `factory import ris`, `factory import show`, `factory inbox add`, `factory inbox list`, `factory inbox prioritise`, `factory inbox resolve`, `factory inbox withdraw`, `factory interpretations history`, `factory interpretations list`, `factory interpretations review`, `factory interpretations show`, `factory interpretations supersede`, `factory interpretations write`, `factory layers move`, `factory leads candidates`, `factory leads discard`, `factory leads list`, `factory leads park`, `factory leads promote`, `factory leads queue`, `factory leads stats`, `factory living prisma-update`, `factory living snapshot`, `factory manuscript add`, `factory manuscript audit`, `factory manuscript report`, `factory manuscript resolve`, `factory manuscript status`, `factory match`, `factory mine agreement`, `factory mine audit label`, `factory mine audit report`, `factory mine audit sample`, `factory mine import`, `factory mine request`, `factory mine resolve`, `factory mine status`, `factory miner add`, `factory miner admit`, `factory miner adopt`, `factory miner calibrate draw`, `factory miner calibrate label`, `factory miner calibrate report`, `factory miner list`, `factory miner register`, `factory miner reopen`, `factory miner retire`, `factory models cutoff`, `factory notices assess`, `factory notices check`, `factory notices list`, `factory outline`, `factory pack`, `factory pages brief`, `factory pages list`, `factory pages record`, `factory pages show`, `factory passages embed`, `factory passages status`, `factory performance`, `factory protocol confirm-press`, `factory protocol show`, `factory question show`, `factory rank compute`, `factory rank show`, `factory rebuild`, `factory references decide`, `factory references extract`, `factory references layers label`, `factory references layers sample`, `factory references layers status`, `factory references list`, `factory references re-resolve`, `factory references scheme record`, `factory references status`, `factory regions add`, `factory regions adopt`, `factory regions define`, `factory regions diff`, `factory regions export`, `factory regions link`, `factory regions links`, `factory regions list`, `factory regions proposals`, `factory regions reject`, `factory regions remove`, `factory regions review`, `factory regions revise`, `factory regions show`, `factory regions snapshot`, `factory registry`, `factory relations confirm`, `factory relations list`, `factory relations reject`, `factory report discovery`, `factory report evidence`, `factory report flow`, `factory report flow-skipped`, `factory report flow-trail`, `factory report flow-works`, `factory report methods`, `factory report prisma`, `factory report search`, `factory runs adopt`, `factory runs list`, `factory runs record`, `factory screen disagreements`, `factory screen join`, `factory screen next`, `factory screen record`, `factory screen resolve`, `factory screen-check band`, `factory screen-check example`, `factory screen-check label`, `factory screen-check list`, `factory screen-check measure`, `factory screen-check report`, `factory screen-check tuning`, `factory search chase`, `factory search slice`, `factory seeds admit`, `factory seeds explain`, `factory seeds split`, `factory sheets balance`, `factory sheets diff`, `factory sheets export`, `factory sheets list`, `factory sheets rate`, `factory sheets show`, `factory site build`, `factory site serve`, `factory site status`, `factory snowball compare`, `factory snowball core list`, `factory snowball core mark`, `factory snowball core unmark`, `factory snowball plan`, `factory snowball run`, `factory status`, `factory suggest`, `factory taxonomy agreement`, `factory taxonomy coverage`, `factory taxonomy derive`, `factory taxonomy diff`, `factory taxonomy list`, `factory taxonomy proposals`, `factory taxonomy register`, `factory taxonomy view`, `factory technique candidates`, `factory technique challenges`, `factory technique combinations`, `factory technique gaps`, `factory technique landscape`, `factory technique neighbors`, `factory technique show`, `factory tour`, `factory trace`, `factory versions list`, `factory versions prefer`, `factory view coverage`, `factory view horizon`, `factory view onion`, `factory view timeline`, `factory vocabulary approve`, `factory vocabulary list`, `factory vocabulary merge`, `factory vocabulary reject`, `factory vocabulary unmerge`, `factory watch plan`, `factory watch run`, `factory watch status` | | `human_queue` | The human queue of one project: where a human is blocking, one count per gate kind. | — | — | — | | `hypotheses` | Hypotheses: drafting, states, the revision rule and abandonment (slice 6, plan H-C; rulings 3, 5, 6 and 12). | hypotheses | `hypothesis_draft`, `hypothesis_list`, `hypothesis_register`, `hypothesis_view` | `factory hypotheses abandon`, `factory hypotheses conclude`, `factory hypotheses list`, `factory hypotheses register`, `factory hypotheses show`, `factory models cutoff` | | `hypothesis_gates` | Who may pass the hypothesis gates (slice 6, plan H-C; slice M ruling 2). | — | — | — | @@ -1831,7 +1832,7 @@ Defined in `cli/main.py` (typer); rendering in `cli/render.py` and siblings. | `site_queue` | The Work queue product: the papers added from the feed, each with the stage it stands at, and the open units of work pe… | — | — | — | | `site_results` | The results product: what the miners found across the corpus (plan site-hub, step 3). | — | — | — | | `site_runs` | The hub product "Runs": the agent-run files under `ops/`, grouped (plan flow-transparency, R3). | — | — | — | -| `site_search` | The Search and deduplication product: every registered query with its runs and the gap between what a source reported a… | dedup | — | — | +| `site_search` | The Search and deduplication product: every registered query with its runs and the gap between what a source reported a… | — | — | — | | `site_search_page` | The Search and deduplication page: one HTML string, inline CSS and JS, no external resource. | — | — | — | | `site_server` | Serve the project site on 127.0.0.1 and keep it current (plan site-hub, step 6). | — | — | `factory site serve` | | `site_settings` | The project Settings page `/p//settings/` (plan 2026-11-13-hub-feed, part 5). | — | — | — | diff --git a/docs/plans/2026-11-29-hub-stage1-speed.md b/docs/plans/2026-11-29-hub-stage1-speed.md new file mode 100644 index 00000000..7a7d6399 --- /dev/null +++ b/docs/plans/2026-11-29-hub-stage1-speed.md @@ -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=` 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 --out `) 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 `.json.gz` and `.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 ` (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/.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. diff --git a/platform/src/factory/cli/hub.py b/platform/src/factory/cli/hub.py index d04ca5d8..5f047508 100644 --- a/platform/src/factory/cli/hub.py +++ b/platform/src/factory/cli/hub.py @@ -6,6 +6,10 @@ from __future__ import annotations +import json +import os +import select +import sys from pathlib import Path from typing import Annotated @@ -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() diff --git a/platform/src/factory/services/agreement.py b/platform/src/factory/services/agreement.py index 800c4096..1ab5d401 100644 --- a/platform/src/factory/services/agreement.py +++ b/platform/src/factory/services/agreement.py @@ -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 ( @@ -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) diff --git a/platform/src/factory/services/conductor.py b/platform/src/factory/services/conductor.py index db0ef44c..b0df0601 100644 --- a/platform/src/factory/services/conductor.py +++ b/platform/src/factory/services/conductor.py @@ -29,11 +29,12 @@ from typing import Any, Final, Literal, Protocol, cast from pydantic import JsonValue +from sqlalchemy import bindparam, text from factory.canonical import canonical_json from factory.errors import FactoryValidationError, ValidationIssue from factory.events.envelope import Event -from factory.events.reader import read_all, read_typed +from factory.events.reader import read_typed from factory.model.base import StrictModel from factory.model.conductor import ( ConductorFinished, @@ -239,6 +240,16 @@ def payloads(self, kind: str) -> list[Event]: def _load(project: Project) -> _Trail | None: """The latest conductor run that is not finished. System events only.""" + project.index.sync() + with project.index.connect() as conn: + has_started = conn.execute( + text( + "SELECT 1 FROM events WHERE type = 'conductor.started' " + "AND actor_kind = 'system' LIMIT 1" + ) + ).first() + if has_started is None: + return None events = [ e for e in read_typed(project.paths.events_dir, project.catalog, EVENT_TYPES) @@ -402,17 +413,22 @@ def _trust_pauses(project: Project) -> list[str]: it.""" -def gate_act_closes(gate_id: str, event_type: str, actor_kind: str) -> bool: - """Whether an event closes `gate_id`: a human actor and one of the gate's own act events - (`GateSpec.act_events`, the module declarations). A gate the registry does not know is never - closed here: it stays human (decision 84.6) and waits.""" +def _gate_act_events(gate_id: str) -> frozenset[str]: + """The act event types of `gate_id`, or its check acts when not a declared gate.""" from factory.services.modules.default import default_modules try: acts = default_modules().gate(gate_id).act_events except KeyError: acts = _CHECK_ACTS.get(gate_id, ()) - return actor_kind == "human" and event_type in acts + return frozenset(acts) + + +def gate_act_closes(gate_id: str, event_type: str, actor_kind: str) -> bool: + """Whether an event closes `gate_id`: a human actor and one of the gate's own act events + (`GateSpec.act_events`, the module declarations). A gate the registry does not know is never + closed here: it stays human (decision 84.6) and waits.""" + return actor_kind == "human" and event_type in _gate_act_events(gate_id) def default_gate_closed(project: Project, stage_id: str, gate_id: str) -> bool: @@ -431,11 +447,19 @@ def default_gate_closed(project: Project, stage_id: str, gate_id: str) -> bool: ) if after is None: return False - return any( - gate_act_closes(gate_id, e.type, e.actor.kind) - for e in read_all(project.paths.events_dir, project.catalog) - if e.id > after - ) + acts = _gate_act_events(gate_id) + if not acts: + return False + project.index.sync() + with project.index.connect() as conn: + row = conn.execute( + text( + "SELECT 1 FROM events WHERE id > :after AND actor_kind = 'human' " + "AND type IN :types LIMIT 1" + ).bindparams(bindparam("types", expanding=True)), + {"after": after, "types": sorted(acts)}, + ).first() + return row is not None @dataclass(frozen=True) diff --git a/platform/src/factory/services/dedup.py b/platform/src/factory/services/dedup.py index bb3ca030..dcf18f2a 100644 --- a/platform/src/factory/services/dedup.py +++ b/platform/src/factory/services/dedup.py @@ -21,7 +21,14 @@ from factory.services.context import Project from factory.services.dedup_cascade import CascadeMerge, dedup, merge_works from factory.services.progress import track -from factory.services.search import corpus_size, list_works +from factory.services.search import ( + ProvenanceStub, + WorkStub, + corpus_size, + list_work_stubs, + list_works, + works_by_ids, +) class DedupSummary(StrictModel): @@ -280,6 +287,35 @@ def canonical_works(project: Project) -> list[Work]: return sorted([*merged, *rest], key=lambda work: work.id) +@memoised +def canonical_work_stubs(project: Project) -> list[WorkStub]: + """Lightweight canonical corpus stubs, hydrating full `Work` models only for merged works.""" + stubs = {w.id: w for w in list_work_stubs(project)} + merges = active_merges(project) + members = [(merge.primary, *merge.absorbed) for merge in merges] + covered = {wid for ids in members for wid in ids} + merged_inputs = {w.id: w for w in works_by_ids(project, sorted(covered))} if covered else {} + merged_stubs: list[WorkStub] = [] + for ids in members: + group = [merged_inputs[wid] for wid in ids if wid in merged_inputs] + if not group: + continue + merged = merge_works(group) + merged_stubs.append( + WorkStub( + id=merged.id, + title=merged.title, + year=merged.dates.year, + provenance=tuple( + ProvenanceStub(p.source, p.run_id, p.query_id, p.method) + for p in merged.provenance + ), + ) + ) + rest_stubs = [stub for wid, stub in stubs.items() if wid not in covered] + return sorted([*merged_stubs, *rest_stubs], key=lambda w: w.id) + + def alias_keys(project: Project, work_ids: Sequence[str]) -> dict[str, list[tuple[str, str]]]: """The published identifiers linked to each of `work_ids` (version links), as exact-match keys. diff --git a/platform/src/factory/services/extraction_agreement.py b/platform/src/factory/services/extraction_agreement.py index 7456492e..5af1cad9 100644 --- a/platform/src/factory/services/extraction_agreement.py +++ b/platform/src/factory/services/extraction_agreement.py @@ -45,7 +45,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.extraction.numbers import normalise_for, normalise_text from factory.index.extraction import WHOLE_ROW from factory.model.base import StrictModel @@ -1077,7 +1077,11 @@ def _refuse_shared( models: dict[PassLabel, set[str]] = {label: set() for label in PassLabel} apart = calibration_sessions_of(project, scope) apart_tasks = calibration_task_ids(project, scope) - for event in read_all(project.paths.events_dir, project.catalog): + for event in read_typed( + project.paths.events_dir, + project.catalog, + ("extraction.pass_joined", "extraction.recorded"), + ): if event.type == "extraction.pass_joined": payload = ExtractionPassJoined.model_validate(event.payload) if scope_of_pack(payload.pack) != scope or payload.session in apart: diff --git a/platform/src/factory/services/flow_ledger.py b/platform/src/factory/services/flow_ledger.py index 792a1b18..ce4eea7f 100644 --- a/platform/src/factory/services/flow_ledger.py +++ b/platform/src/factory/services/flow_ledger.py @@ -17,6 +17,7 @@ from factory.model.base import StrictModel from factory.model.protocol import ScreeningStage from factory.model.work import ProvenanceMethod, Work +from factory.services import call_memo from factory.services.agreement import ( Outcome, cannot_assess_open, @@ -24,11 +25,11 @@ final_outcomes, ) from factory.services.context import Project -from factory.services.dedup import active_merges, canonical_works +from factory.services.dedup import active_merges, canonical_work_stubs from factory.services.fulltext_screening import fulltext_queue from factory.services.fulltext_status import fulltext_status from factory.services.prisma import UNCONVERTED, UNSPECIFIED, full_text_boxes, prisma_flow -from factory.services.search import list_works +from factory.services.search import WorkStub, list_work_stubs OTHER_GROUP = "other" TOTAL = "total" @@ -117,7 +118,7 @@ def source_group(database_sources: Collection[str]) -> str: return "+".join(sources) -def _group_of(work: Work) -> str: +def _group_of(work: Work | WorkStub) -> str: return source_group( {p.source for p in work.provenance if p.method is ProvenanceMethod.DATABASE} ) @@ -125,76 +126,76 @@ def _group_of(work: Work) -> str: def flow_ledger(project: Project) -> list[LedgerRow]: """One row per canonical work and per absorbed duplicate, sorted by work id.""" - project.index.sync() - raw = {work.id: work for work in list_works(project)} - canonical = {work.id: work for work in canonical_works(project)} - merges = active_merges(project) - absorbed_by = {a: (m.primary, m.rule) for m in merges for a in m.absorbed} - ta = final_outcomes(project) - ta_criteria = exclusion_criteria(project) + with project.index.frozen_sync(), call_memo.entering(): + raw = {work.id: work for work in list_work_stubs(project)} + canonical = {work.id: work for work in canonical_work_stubs(project)} + merges = active_merges(project) + absorbed_by = {a: (m.primary, m.rule) for m in merges for a in m.absorbed} + ta = final_outcomes(project) + ta_criteria = exclusion_criteria(project) - boxes = full_text_boxes(project) - queue = fulltext_queue(project) - eligible = {e.work_id for e in queue.eligible} - promoted = eligible | set(queue.not_retrieved) - states = {entry.work_id: entry for entry in fulltext_status(project).works} - ft = ScreeningStage.FULL_TEXT - ft_outcomes = final_outcomes(project, stage=ft) if boxes.stage_run else {} - ft_criteria = exclusion_criteria(project, stage=ft) if boxes.stage_run else {} - unresolved = set(cannot_assess_open(project, stage=ft)) if boxes.stage_run else set() + boxes = full_text_boxes(project) + queue = fulltext_queue(project) + eligible = {e.work_id for e in queue.eligible} + promoted = eligible | set(queue.not_retrieved) + states = {entry.work_id: entry for entry in fulltext_status(project).works} + ft = ScreeningStage.FULL_TEXT + ft_outcomes = final_outcomes(project, stage=ft) if boxes.stage_run else {} + ft_criteria = exclusion_criteria(project, stage=ft) if boxes.stage_run else {} + unresolved = set(cannot_assess_open(project, stage=ft)) if boxes.stage_run else set() - rows: list[LedgerRow] = [] - for work_id in sorted(set(canonical) | set(absorbed_by) | promoted): - work = canonical.get(work_id) or raw.get(work_id) - if work is None: - raise LookupError(f"work {work_id} is merged or promoted but has no work record") - primary, rule = absorbed_by.get(work_id, (None, None)) - outcome = ta.get(work_id) - ft_state: FtState | None = None - reasons: list[str] = [] - ft_outcome: Literal["included", "excluded", "pending", "awaiting"] | None = None - if work_id in promoted: - entry = states.get(work_id) - if work_id in eligible: - ft_state = "retrieved" - elif entry is None or entry.state == "unsought": - ft_state = "not-sought" - else: - ft_state = "attempted-failed" - if entry.state == "retrieved": # a live document with no conversion - reasons = [UNCONVERTED] - else: - reasons = sorted(f"{r.value}: {why}" for r, why in entry.reasons.items()) - if work_id in eligible and boxes.stage_run: - if work_id in unresolved: - ft_outcome = "awaiting" + rows: list[LedgerRow] = [] + for work_id in sorted(set(canonical) | set(absorbed_by) | promoted): + work = canonical.get(work_id) or raw.get(work_id) + if work is None: + raise LookupError(f"work {work_id} is merged or promoted but has no work record") + primary, rule = absorbed_by.get(work_id, (None, None)) + outcome = ta.get(work_id) + ft_state: FtState | None = None + reasons: list[str] = [] + ft_outcome: Literal["included", "excluded", "pending", "awaiting"] | None = None + if work_id in promoted: + entry = states.get(work_id) + if work_id in eligible: + ft_state = "retrieved" + elif entry is None or entry.state == "unsought": + ft_state = "not-sought" else: - got = ft_outcomes.get(work_id, Outcome.PENDING) - ft_outcome = got.value - rows.append( - LedgerRow( - work_id=work_id, - title=work.title, - year=work.dates.year, - source_group=_group_of(work), - sources=sorted({p.source for p in work.provenance}), - query_ids=sorted({p.query_id for p in work.provenance}), - run_ids=sorted({p.run_id for p in work.provenance}), - canonical_id=primary, - merge_rule=rule, - ta_outcome=outcome, - ta_criterion=(ta_criteria.get(work_id) or UNSPECIFIED) - if outcome is Outcome.EXCLUDED - else None, - ft_state=ft_state, - ft_reasons=reasons, - ft_outcome=ft_outcome, - ft_criterion=(ft_criteria.get(work_id) or UNSPECIFIED) - if ft_outcome == "excluded" - else None, + ft_state = "attempted-failed" + if entry.state == "retrieved": # a live document with no conversion + reasons = [UNCONVERTED] + else: + reasons = sorted(f"{r.value}: {why}" for r, why in entry.reasons.items()) + if work_id in eligible and boxes.stage_run: + if work_id in unresolved: + ft_outcome = "awaiting" + else: + got = ft_outcomes.get(work_id, Outcome.PENDING) + ft_outcome = got.value + rows.append( + LedgerRow( + work_id=work_id, + title=work.title, + year=work.year, + source_group=_group_of(work), + sources=sorted({p.source for p in work.provenance}), + query_ids=sorted({p.query_id for p in work.provenance}), + run_ids=sorted({p.run_id for p in work.provenance}), + canonical_id=primary, + merge_rule=rule, + ta_outcome=outcome, + ta_criterion=(ta_criteria.get(work_id) or UNSPECIFIED) + if outcome is Outcome.EXCLUDED + else None, + ft_state=ft_state, + ft_reasons=reasons, + ft_outcome=ft_outcome, + ft_criterion=(ft_criteria.get(work_id) or UNSPECIFIED) + if ft_outcome == "excluded" + else None, + ) ) - ) - return rows + return rows def _bump(counts: dict[str, int], key: str) -> None: diff --git a/platform/src/factory/services/gate_trust.py b/platform/src/factory/services/gate_trust.py index df06cbf3..5ae1b70f 100644 --- a/platform/src/factory/services/gate_trust.py +++ b/platform/src/factory/services/gate_trust.py @@ -27,6 +27,8 @@ from sqlalchemy import text from factory.modules.contract import GateKind, PolicyKind +from factory.services import call_memo +from factory.services.call_memo import memoised from factory.services.context import Project from factory.services.gates import gate_acts @@ -91,20 +93,36 @@ def labels_of(project: Project, gate_id: str) -> dict[str, bool | None]: return found -def agent_labels(project: Project, gate_id: str) -> dict[str, bool]: - """Agent labels at `gate_id` (latest per act), read from the log: the fold keeps human - labels only.""" +@memoised +def _all_agent_gate_labels(project: Project) -> dict[str, bool]: + """Latest agent label per `act_event_id` across all gates, read from the log.""" from factory.events.reader import read_typed - sampled = set(labels_of(project, gate_id)) found: dict[str, bool] = {} for event in read_typed(project.paths.events_dir, project.catalog, ["gate.audit_labelled"]): - act = str(event.payload.get("act_event_id")) - if event.actor.kind == "agent" and act in sampled: - found[act] = bool(event.payload.get("correct")) + if event.actor.kind == "agent": + found[str(event.payload.get("act_event_id"))] = bool(event.payload.get("correct")) return found +def agent_labels(project: Project, gate_id: str) -> dict[str, bool]: + """Agent labels at `gate_id` (latest per act), read from the log: the fold keeps human + labels only.""" + sampled = set(labels_of(project, gate_id)) + if not sampled: + return {} + with project.index.connect() as conn: + has_agent_labels = conn.execute( + text( + "SELECT 1 FROM events WHERE type = 'gate.audit_labelled' " + "AND actor_kind = 'agent' LIMIT 1" + ) + ).first() + if has_agent_labels is None: + return {} + return {act: v for act, v in _all_agent_gate_labels(project).items() if act in sampled} + + def gate_trust(project: Project, gate_id: str) -> GateTrust: agent = { a.event_id @@ -174,9 +192,10 @@ def trust_ledger(project: Project) -> tuple[GateTrust, ...]: """One row per decision gate with at least one agent act, in registry order.""" from factory.services.modules.default import default_modules # the registry imports services - rows = ( - gate_trust(project, g.gate_id) - for g in default_modules().gates() - if g.kind is GateKind.DECISION - ) - return tuple(r for r in rows if r.closed_by_agent > 0) + with project.index.frozen_sync(), call_memo.entering(): + rows = ( + gate_trust(project, g.gate_id) + for g in default_modules().gates() + if g.kind is GateKind.DECISION + ) + return tuple(r for r in rows if r.closed_by_agent > 0) diff --git a/platform/src/factory/services/gates.py b/platform/src/factory/services/gates.py index eba937a4..9dd13444 100644 --- a/platform/src/factory/services/gates.py +++ b/platform/src/factory/services/gates.py @@ -22,6 +22,7 @@ import hashlib import re +from bisect import bisect_left from collections.abc import Iterator from dataclasses import dataclass @@ -49,6 +50,7 @@ from factory.quality.stats import audit_size, draw_uniform from factory.services import audit_core, passes from factory.services.access import gate_role_issues +from factory.services.call_memo import memoised from factory.services.context import Project from factory.services.validation_profile import enforcement_for @@ -69,23 +71,29 @@ miner's (its `pack` is in the miner namespace). A gate sees only its own acts.""" +@memoised def _miner_resolutions(project: Project) -> set[str]: """The ids of the `extraction.resolved` events of registered miners, read from the log (the projection keeps the latest resolution per row, not every act). Empty, without reading the log, while no miner pass has opened: no miner resolution can exist then.""" - from factory.events.reader import read_all # the reader imports the catalog + from factory.events.reader import read_typed # the reader imports the catalog + project.index.sync() with project.index.connect() as conn: opened = conn.execute( text("SELECT 1 FROM extraction_passes WHERE scope LIKE 'm-%' LIMIT 1") ).first() - if opened is None: + if opened is None: + return set() + has_resolved = conn.execute( + text("SELECT 1 FROM events WHERE type = 'extraction.resolved' LIMIT 1") + ).first() + if has_resolved is None: return set() return { event.id - for event in read_all(project.paths.events_dir, project.catalog) - if event.type == "extraction.resolved" - and isinstance(event.payload.get("pack"), str) + for event in read_typed(project.paths.events_dir, project.catalog, ("extraction.resolved",)) + if isinstance(event.payload.get("pack"), str) and re.fullmatch(MINER_NAME_RE, str(event.payload["pack"])) is not None } @@ -279,16 +287,19 @@ def gate_acts(project: Project, gate_id: str) -> Iterator[GateAct]: ), {f"t{i}": t for i, t in enumerate(types)}, ).all() + proto_rows = conn.execute( + text("SELECT event_id, protocol_id FROM protocols ORDER BY event_id") + ).all() + proto_events = [str(r[0]) for r in proto_rows] + proto_ids = [str(r[1]) for r in proto_rows] miner_acts = _miner_resolutions(project) if gate_id in _RESOLUTION_GATES else set() for event_id, kind, session in rows: - if ( - gate_id in _RESOLUTION_GATES - and (str(event_id) in miner_acts) != _RESOLUTION_GATES[gate_id] - ): + eid = str(event_id) + if gate_id in _RESOLUTION_GATES and (eid in miner_acts) != _RESOLUTION_GATES[gate_id]: continue - yield GateAct( - gate_id, str(event_id), str(kind), str(session), protocol_at(project, str(event_id)) - ) + pos = bisect_left(proto_events, eid) + proto = None if pos == 0 else proto_ids[pos - 1] + yield GateAct(gate_id, eid, str(kind), str(session), proto) def as_autonomy_acts(project: Project, gate_ids: tuple[str, ...]) -> Iterator[AutonomyAct]: diff --git a/platform/src/factory/services/hub_build.py b/platform/src/factory/services/hub_build.py index c655f6bd..6b9dbccf 100644 --- a/platform/src/factory/services/hub_build.py +++ b/platform/src/factory/services/hub_build.py @@ -20,7 +20,7 @@ import json import re import time -from collections.abc import Callable, Collection, Mapping +from collections.abc import Callable, Collection, Mapping, Sequence from dataclasses import dataclass, field from datetime import UTC, datetime from pathlib import Path @@ -28,6 +28,7 @@ from sqlalchemy import text as sql_text +from factory.events.reader import cached_reads as event_read_scope from factory.services import ( call_memo, citations, @@ -354,7 +355,7 @@ def facet_shell(project: Project) -> dict[str, Any]: def build_overview(ctx: HubContext) -> dict[str, Any]: - return hp.overview_payload(ctx.project, ctx.flow_data) + return hp.overview_payload(ctx.project, ctx.flow_data, graph=ctx.graph) def build_flow(ctx: HubContext) -> dict[str, Any]: @@ -854,6 +855,64 @@ def _grid_builder(name: str) -> Callable[[HubContext], dict[str, Any]]: "taxonomy.", "vocabulary.", ), + "platform": (), + "protocol": ( + "protocol.", + "question.", + "screening.", + "calibration.", + "press.", + "deviation.", + "seed.", + "project.", + "decision.", + "fulltext.", + "gate.", + ), + "levels": ( + "project.", + "protocol.", + "gate.", + "conductor.", + "screening.", + "extraction.", + "calibration.", + "audit.", + "miner.", + "decision.", + ), + "pipeline": ("*",), + "sources": ("*", "-runner.", "-task.", "-feed.", "-watch.", "-xrun.", "-notice."), + "method": ("*", *_QUIET), + "write": ("*", *_QUIET), + "learn": ("*", "-runner.", "-task.", "-watch.", "-xrun.", "-file.", "-notice."), + "living": ("*", "-runner.", "-task.", "-xrun.", "-file."), + "contradictions": ( + "contradiction.", + "extraction.", + "miner.", + "mine.", + "document.", + "search.", + "dedup.", + "screening.", + "protocol.", + ), + "chat": ( + "chat.", + "sheet.", + "answer.", + "spar.", + "runner.", + "extraction.", + "miner.", + "document.", + "search.", + "dedup.", + "screening.", + "protocol.", + "work.", + ), } @@ -865,6 +924,8 @@ def reads(name: str, event_type: str) -> bool: if name.startswith(hub_mining.GRID_PREFIX): name = "mining" spec = PAYLOAD_INPUTS.get(name, ("*",)) + if not spec: + return False if spec[0] == "*": return not any(event_type.startswith(p[1:]) for p in spec[1:]) return event_type.startswith(spec) @@ -945,7 +1006,8 @@ def build_static( specific = sorted(n for n in (only_set or ()) if n.startswith(hub_mining.GRID_PREFIX)) if wanted_grids or specific: try: - grids = ctx.grids + with ctx.project.index.frozen_sync(), call_memo.entering(), event_read_scope(): + grids = ctx.grids except Exception as exc: report.errors[GRID_FAMILY] = f"{type(exc).__name__}: {exc}" grids = {} @@ -962,7 +1024,7 @@ def build_static( started = time.perf_counter() try: # one reading of each shared derivation per payload, and one index sync - with ctx.project.index.frozen_sync(), call_memo.entering(): + with ctx.project.index.frozen_sync(), call_memo.entering(), event_read_scope(): text = dumps(builders[name](ctx)) except Exception as exc: report.errors[name] = f"{type(exc).__name__}: {exc}" @@ -1011,6 +1073,87 @@ def build_static( return report +class WarmBuilder: + """Persistent payload builder that keeps one ``HubContext`` warm across requests until the + project's ``last_event_id`` changes.""" + + def __init__(self, project: Project) -> None: + self._project = project + self._ctx: HubContext | None = None + self._last_event_id: str | None = None + + def build_into(self, names: Sequence[str], out_dir: Path) -> BuildReport: + """Build `names` into `out_dir/data/`, reusing `self._ctx` while the log is unchanged.""" + self._project.index.sync() + current = self._project.index.last_event_id() + if self._ctx is None or current != self._last_event_id: + self._ctx = HubContext(self._project) + self._last_event_id = current + ctx = self._ctx + unknown = sorted( + n + for n in names + if n not in BUILDERS and n != GRID_FAMILY and not n.startswith(hub_mining.GRID_PREFIX) + ) + if unknown: + raise ValueError( + f"unknown payload(s): {', '.join(unknown)}; known: {', '.join(BUILDERS)}, " + f"{GRID_FAMILY}, {hub_mining.GRID_PREFIX}" + ) + report = BuildReport() + wanted: list[str] = [] + seen: set[str] = set() + want_all_grids = False + specific: list[str] = [] + for n in names: + if n == GRID_FAMILY: + want_all_grids = True + elif n.startswith(hub_mining.GRID_PREFIX): + if n not in specific: + specific.append(n) + elif n not in seen: + seen.add(n) + wanted.append(n) + builders: dict[str, Callable[[HubContext], dict[str, Any]]] = { + n: BUILDERS[n] for n in wanted + } + if want_all_grids or specific: + try: + with ctx.project.index.frozen_sync(), call_memo.entering(), event_read_scope(): + grids = ctx.grids + except Exception as exc: + report.errors[GRID_FAMILY] = f"{type(exc).__name__}: {exc}" + grids = {} + missing_grids = [n for n in specific if n not in grids] + if missing_grids and not report.errors: + raise ValueError(f"unknown grid payload(s): {', '.join(missing_grids)}") + for gname in grids: + if want_all_grids or gname in specific: + builders[gname] = _grid_builder(gname) + if gname not in seen: + seen.add(gname) + wanted.append(gname) + data_dir = out_dir / "data" + data_dir.mkdir(parents=True, exist_ok=True) + for name in wanted: + started = time.perf_counter() + try: + with ctx.project.index.frozen_sync(), call_memo.entering(), event_read_scope(): + text = dumps(builders[name](ctx)) + except Exception as exc: + report.errors[name] = f"{type(exc).__name__}: {exc}" + for stale in (data_dir / f"{name}.json", data_dir / f"{name}.json.gz"): + if stale.is_file(): + stale.unlink() + report.removed.append(f"data/{stale.name}") + continue + _write_payload(data_dir, name, text) + report.payloads[name] = PayloadReport( + round(time.perf_counter() - started, 2), len(text.encode("utf-8")) + 1 + ) + return report + + def format_report(report: BuildReport) -> list[str]: """One line per payload, page and error, for the CLI.""" lines = [f"{n}: {r.seconds:.2f} s, {r.bytes} bytes" for n, r in report.payloads.items()] diff --git a/platform/src/factory/services/hub_payloads.py b/platform/src/factory/services/hub_payloads.py index eb8ff295..3ff05794 100644 --- a/platform/src/factory/services/hub_payloads.py +++ b/platform/src/factory/services/hub_payloads.py @@ -729,14 +729,19 @@ def _load_year_external( return out -def overview_payload(project: Project, data: FlowData | None = None) -> dict[str, Any]: +def overview_payload( + project: Project, + data: FlowData | None = None, + *, + graph: CitationGraph | None = None, +) -> dict[str, Any]: """Lead facts, pipeline strip, papers per month, composition, most cited and next actions.""" d = data or load_flow_data(project) inc = list(d.sets.included) source_of = {w: d.sets.miner_source(w) for w in inc} human_values = _load_role_field(project, source_of, "human") humans = human_share(human_values) - cites = cited_here(project, inc) + cites = cited_here(project, inc, graph) pub = _load_publication(project, inc) layers = layers_of(project) diff --git a/platform/src/factory/services/hub_serve.py b/platform/src/factory/services/hub_serve.py index f4eefdae..033540dd 100644 --- a/platform/src/factory/services/hub_serve.py +++ b/platform/src/factory/services/hub_serve.py @@ -33,16 +33,21 @@ from __future__ import annotations +import ast +import contextlib import gzip import hashlib +import inspect import json import logging import os import re +import select import shutil import subprocess import sys import tempfile +import textwrap import threading import time import zipfile @@ -182,18 +187,296 @@ def asset(name: str, version: str | None) -> Asset | None: @lru_cache(maxsize=1) def code_hash() -> str: - """Hash of the hub services and the served assets; read once per process.""" - digest = hashlib.sha256(hub_ui.asset_version().encode()) + """Hash of the hub services; read once per process.""" + digest = hashlib.sha256() here = Path(__file__).parent for path in sorted(here.glob("hub_*.py")): digest.update(path.name.encode() + b"\0" + path.read_bytes() + b"\0") return digest.hexdigest()[:16] +_PKG_ROOT: Final = Path(__file__).resolve().parent.parent +_HUB_BUILD_MOD: Final = "factory.services.hub_build" +_PAYLOAD_CODE_LOCK = threading.Lock() +_FILE_IMPORTS_CACHE: dict[tuple[Path, str, bool], tuple[int, int, tuple[str, ...]]] = {} +_FILE_DIGEST_CACHE: dict[Path, tuple[int, int, bytes]] = {} +_PAYLOAD_CODE_CACHE: dict[tuple[str, object], tuple[tuple[tuple[Path, int, int], ...], str]] = {} + + +def _module_path(mod_name: str) -> Path | None: + """Path to a `factory.*` Python source file under `_PKG_ROOT` (excluding `hub_ui/` assets).""" + parts = mod_name.split(".") + if not parts or parts[0] != "factory": + return None + if len(parts) >= 2 and parts[1] == "hub_ui": + return None + if len(parts) == 1: + cand = _PKG_ROOT / "__init__.py" + return cand if cand.is_file() else None + file_cand = _PKG_ROOT.joinpath(*parts[1:]).with_suffix(".py") + if file_cand.is_file(): + return file_cand + pkg_cand = _PKG_ROOT.joinpath(*parts[1:], "__init__.py") + return pkg_cand if pkg_cand.is_file() else None + + +def _is_type_checking_if(node: ast.AST) -> bool: + if not isinstance(node, ast.If): + return False + test = node.test + if isinstance(test, ast.Name) and test.id == "TYPE_CHECKING": + return True + return ( + isinstance(test, ast.Attribute) + and isinstance(test.value, ast.Name) + and test.value.id == "typing" + and test.attr == "TYPE_CHECKING" + ) + + +def _iter_runtime_nodes(root: ast.AST) -> list[ast.AST]: + """AST nodes under `root`, skipping `if TYPE_CHECKING:` branches.""" + out: list[ast.AST] = [] + stack: list[ast.AST] = [root] + while stack: + node = stack.pop() + out.append(node) + if _is_type_checking_if(node): + assert isinstance(node, ast.If) + stack.extend(node.orelse) + continue + stack.extend(ast.iter_child_nodes(node)) + return out + + +def _resolve_import_from(node: ast.ImportFrom, cur_mod: str, is_pkg: bool) -> list[str]: + if node.level > 0: + parts = cur_mod.split(".") + pkg_parts = parts if is_pkg else parts[:-1] + up = node.level - 1 + if up > len(pkg_parts): + return [] + base_parts = pkg_parts[: len(pkg_parts) - up] + mod_parts = node.module.split(".") if node.module else [] + target = ".".join([*base_parts, *mod_parts]) + else: + target = node.module or "" + if target != "factory" and not target.startswith("factory."): + return [] + found: list[str] = [] + if _module_path(target) is not None: + found.append(target) + for alias in node.names: + if alias.name != "*": + sub = f"{target}.{alias.name}" + if _module_path(sub) is not None: + found.append(sub) + return found + + +def _extract_factory_imports(tree: ast.AST, cur_mod: str, is_pkg: bool) -> set[str]: + out: set[str] = set() + for node in _iter_runtime_nodes(tree): + if isinstance(node, ast.Import): + for alias in node.names: + if (alias.name == "factory" or alias.name.startswith("factory.")) and _module_path( + alias.name + ) is not None: + out.add(alias.name) + elif isinstance(node, ast.ImportFrom): + out.update(_resolve_import_from(node, cur_mod, is_pkg)) + return out + + +def _hub_build_seeds(fn_name: str, hub_build_path: Path) -> set[str]: + """`factory.*` modules reachable from `hub_build.` without pulling in unrelated + `hub_*` builders imported at the top of `hub_build.py`.""" + tree = ast.parse(hub_build_path.read_text(encoding="utf-8")) + aliases: dict[str, set[str]] = {} + top_defs: dict[str, ast.FunctionDef] = {} + ctx_defs: dict[str, ast.FunctionDef] = {} + for stmt in tree.body: + if isinstance(stmt, ast.Import): + for alias in stmt.names: + if alias.name == "factory" or alias.name.startswith("factory."): + key = alias.asname or alias.name.split(".")[0] + aliases.setdefault(key, set()).add(alias.name) + elif isinstance(stmt, ast.ImportFrom): + resolved = _resolve_import_from(stmt, _HUB_BUILD_MOD, False) + mod = stmt.module or "" + if mod == "factory" or mod.startswith("factory."): + for alias in stmt.names: + key = alias.asname or alias.name + sub = f"{mod}.{alias.name}" + if _module_path(sub) is not None: + aliases.setdefault(key, set()).add(sub) + elif _module_path(mod) is not None: + aliases.setdefault(key, set()).add(mod) + else: + for m in resolved: + aliases.setdefault(m.rsplit(".", 1)[-1], set()).add(m) + elif isinstance(stmt, ast.FunctionDef): + top_defs[stmt.name] = stmt + elif isinstance(stmt, ast.ClassDef) and stmt.name == "HubContext": + for item in stmt.body: + if isinstance(item, ast.FunctionDef): + ctx_defs[item.name] = item + + seeds: set[str] = set() + visited_defs: set[tuple[str, str]] = set() + todo_defs: list[tuple[str, str]] = [("top", fn_name)] + while todo_defs: + kind, name = todo_defs.pop() + if (kind, name) in visited_defs: + continue + visited_defs.add((kind, name)) + node = top_defs.get(name) if kind == "top" else ctx_defs.get(name) + if node is None: + continue + seeds.update(_extract_factory_imports(node, _HUB_BUILD_MOD, False)) + for child in _iter_runtime_nodes(node): + if isinstance(child, ast.Name): + if child.id in aliases: + seeds.update(aliases[child.id]) + if child.id in top_defs and ("top", child.id) not in visited_defs: + todo_defs.append(("top", child.id)) + elif isinstance(child, ast.Attribute) and child.attr in ctx_defs: + if ("ctx", child.attr) not in visited_defs: + todo_defs.append(("ctx", child.attr)) + elif ( + isinstance(child, ast.Constant) + and isinstance(child.value, str) + and child.value.startswith("factory.") + and _module_path(child.value) is not None + ): + seeds.add(child.value) + return seeds + + +def _file_imports(path: Path, cur_mod: str, is_pkg: bool) -> tuple[str, ...]: + """Direct `factory.*` imports of `path`, cached by `(mtime_ns, size)`.""" + try: + st = path.stat() + except OSError: + return () + key = (path, cur_mod, is_pkg) + with _PAYLOAD_CODE_LOCK: + cached = _FILE_IMPORTS_CACHE.get(key) + if cached is not None and cached[0] == st.st_mtime_ns and cached[1] == st.st_size: + return cached[2] + try: + tree = ast.parse(path.read_text(encoding="utf-8")) + deps = tuple(sorted(_extract_factory_imports(tree, cur_mod, is_pkg))) + except (OSError, SyntaxError): + return () + with _PAYLOAD_CODE_LOCK: + _FILE_IMPORTS_CACHE[key] = (st.st_mtime_ns, st.st_size, deps) + return deps + + +def _file_stamp_and_digest(path: Path) -> tuple[int, int, bytes] | None: + """`(mtime_ns, size, sha256_digest)` of `path`, cached by `(mtime_ns, size)`.""" + try: + st = path.stat() + except OSError: + return None + with _PAYLOAD_CODE_LOCK: + cached = _FILE_DIGEST_CACHE.get(path) + if cached is not None and cached[0] == st.st_mtime_ns and cached[1] == st.st_size: + return cached + try: + raw = path.read_bytes() + except OSError: + return None + entry = (st.st_mtime_ns, st.st_size, hashlib.sha256(raw).digest()) + with _PAYLOAD_CODE_LOCK: + _FILE_DIGEST_CACHE[path] = entry + return entry + + +def _reachable_files(fn: Callable[..., Any]) -> set[Path]: + """Every `factory.*` Python file reachable from `fn`, plus `hub_build.py` itself.""" + hub_build_path = _module_path(_HUB_BUILD_MOD) + if hub_build_path is None: + return set() + home = getattr(fn, "__module__", "") or "" + if home == _HUB_BUILD_MOD: + todo = _hub_build_seeds(getattr(fn, "__name__", ""), hub_build_path) + else: + todo = {home} + try: + src_tree = ast.parse(textwrap.dedent(inspect.getsource(fn))) + todo.update(_extract_factory_imports(src_tree, home, False)) + except (OSError, TypeError, SyntaxError): + pass + + visited_mods: set[str] = {_HUB_BUILD_MOD} + visited_paths: set[Path] = {hub_build_path} + while todo: + mod = todo.pop() + if mod in visited_mods: + continue + path = _module_path(mod) + if path is None: + continue + visited_mods.add(mod) + visited_paths.add(path) + is_pkg = path.name == "__init__.py" + todo.update(_file_imports(path, mod, is_pkg)) + return visited_paths + + +def _stamps_match(stamps: tuple[tuple[Path, int, int], ...]) -> bool: + for path, mtime_ns, size in stamps: + try: + st = path.stat() + except OSError: + return False + if st.st_mtime_ns != mtime_ns or st.st_size != size: + return False + return True + + +def payload_code_hash(name: str) -> str: + """Hash of `hub_build.py` and the `factory.*` Python modules reachable from payload `name`'s + builder (excluding `hub_ui/` static assets). Cached by `(mtime_ns, size)` of visited files.""" + target = "mining" if name == GRIDS or name.startswith(hub_mining.GRID_PREFIX) else name + fn = hub_build.BUILDERS.get(target) + if fn is None: + return code_hash() + home = getattr(fn, "__module__", "") or "" + if not home.startswith("factory."): + return code_hash() + key: tuple[str, object] = (target, fn) + with _PAYLOAD_CODE_LOCK: + cached = _PAYLOAD_CODE_CACHE.get(key) + if cached is not None: + stamps, digest = cached + if _stamps_match(stamps): + return digest + visited_paths = _reachable_files(fn) + if not visited_paths: + return code_hash() + stamps_list: list[tuple[Path, int, int]] = [] + hasher = hashlib.sha256() + for path in sorted(visited_paths): + entry = _file_stamp_and_digest(path) + if entry is None: + return code_hash() + mtime_ns, size, file_digest = entry + stamps_list.append((path, mtime_ns, size)) + rel = path.relative_to(_PKG_ROOT).as_posix() + hasher.update(rel.encode() + b"\0" + file_digest + b"\0") + digest = hasher.hexdigest()[:16] + with _PAYLOAD_CODE_LOCK: + _PAYLOAD_CODE_CACHE[key] = (tuple(stamps_list), digest) + return digest + + def fingerprint(project: Project, name: str | None = None) -> str: """The version of payload `name`: the head of the event types it reads (`hub_build.reads`) and - the hub code; for a payload in `hub_build.PAYLOAD_EVENTS` the technique code too. `None` is - every event. + its reachable hub/service code; for a payload in `hub_build.PAYLOAD_EVENTS` the technique code + too. `None` is every event. Reads the projected index (`type_counts`), not the log files: every writer projects on write, so the index is current whenever an event has landed.""" @@ -202,16 +485,17 @@ def fingerprint(project: Project, name: str | None = None) -> str: def _fingerprint_of(counts: TypeCounts, name: str | None) -> str: """`fingerprint` from event type counts already read.""" + code = code_hash() if name is None else payload_code_hash(name) if name in hub_build.PAYLOAD_EVENTS: raw = ( - f"events:{hub_landscape.event_key(counts)}|code:{code_hash()}" + f"events:{hub_landscape.event_key(counts)}|code:{code}" f"|technique:{hub_landscape.code_stamp()}" ) return hashlib.sha256(raw.encode()).hexdigest()[:16] hits = [v for t, v in counts.items() if name is None or hub_build.reads(name, t)] total = sum(n for n, _ in hits) last = max((m for _, m in hits), default="") - raw = f"events:{total}:{last}|code:{code_hash()}" + raw = f"events:{total}:{last}|code:{code}" return hashlib.sha256(raw.encode()).hexdigest()[:16] @@ -335,10 +619,167 @@ def _spawn_subprocess( return code, "\n".join(lines[-12:]) +def worker_command(project: Project, cache_dir: Path, idle: float) -> list[str]: + """The persistent warm worker child command (`factory hub worker`).""" + return [ + "nice", + "-n", + str(BUILD_NICE), + sys.executable, + "-c", + "from factory.cli.main import app; app()", + "--root", + str(project.settings.root), + "hub", + "worker", + project.paths.slug, + "--out", + str(cache_dir), + "--idle", + f"{idle:.1f}", + ] + + +def _spawn_default_worker( + project: Project, names: Sequence[str], out: Path, poll: Callable[[], None] +) -> tuple[int, str]: + """Default `spawn_builder`; `PayloadService` uses `_WarmWorker` when this is active.""" + return _spawn_subprocess(project, names, out, poll) + + spawn_builder: Callable[[Project, Sequence[str], Path, Callable[[], None]], tuple[int, str]] = ( - _spawn_subprocess + _spawn_default_worker ) -"""Runs one build child; replaced in tests by an in-process build.""" +"""Runs one build child; replaced in tests by an in-process build or `_spawn_subprocess`.""" + + +class _WarmWorker: + """Persistent `factory hub worker` child process for one `PayloadService`.""" + + def __init__(self, project: Project, cache_dir: Path) -> None: + self._project = project + self._cache_dir = cache_dir + self._lock = threading.Lock() + self._proc: subprocess.Popen[bytes] | None = None + self._log_path = cache_dir / "worker.log" + self._code_stamp: tuple[tuple[str, str], ...] | None = None + + @staticmethod + def _current_stamp() -> tuple[tuple[str, str], ...]: + return tuple((name, payload_code_hash(name)) for name in sorted(hub_build.BUILDERS)) + + def _log_tail(self) -> str: + try: + text = self._log_path.read_text(encoding="utf-8", errors="replace").strip() + lines = text.splitlines() + except OSError: + return "" + return "\n".join(lines[-12:]) + + def close(self, *, kill: bool = False) -> None: + with self._lock: + self._close_locked(kill=kill) + + def _close_locked(self, *, kill: bool = False) -> None: + proc = self._proc + self._proc = None + self._code_stamp = None + if proc is None: + return + _LIVE.discard(proc) + with contextlib.suppress(OSError): + if proc.stdin is not None: + proc.stdin.close() + if proc.poll() is None: + with contextlib.suppress(OSError): + if kill: + proc.kill() + else: + proc.terminate() + with contextlib.suppress(OSError, subprocess.TimeoutExpired): + proc.wait(timeout=2.0) + if proc.poll() is None: + with contextlib.suppress(OSError): + proc.kill() + proc.wait(timeout=1.0) + with contextlib.suppress(OSError): + if proc.stdout is not None: + proc.stdout.close() + + def _ensure_proc(self, stamp: tuple[tuple[str, str], ...]) -> subprocess.Popen[bytes]: + if self._proc is not None and (self._proc.poll() is not None or self._code_stamp != stamp): + self._close_locked() + if self._proc is None: + self._cache_dir.mkdir(parents=True, exist_ok=True) + cmd = worker_command(self._project, self._cache_dir, max(LINGER + 5.0, 5.0)) + with self._log_path.open("wb") as sink: + proc = subprocess.Popen( + cmd, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=sink, + ) + _LIVE.add(proc) + self._proc = proc + self._code_stamp = stamp + return self._proc + + def run(self, names: Sequence[str], out: Path, poll: Callable[[], None]) -> tuple[int, str]: + req = (json.dumps({"names": list(names), "out": str(out)}) + "\n").encode("utf-8") + for attempt in range(2): + stamp = self._current_stamp() + try: + with self._lock: + proc = self._ensure_proc(stamp) + assert proc.stdin is not None and proc.stdout is not None + proc.stdin.write(req) + proc.stdin.flush() + except OSError as exc: + with self._lock: + self._close_locked(kill=True) + if attempt == 0: + continue + return -1, f"could not start: {exc}" + started = time.monotonic() + line = b"" + assert proc.stdout is not None + while True: + ready, _, _ = select.select([proc.stdout], [], [], POLL_SECONDS) + if ready: + line = proc.stdout.readline() + break + poll() + if proc.poll() is not None: + line = proc.stdout.readline() + break + if time.monotonic() - started > CHILD_TIMEOUT: + with self._lock: + self._close_locked(kill=True) + return -1, f"stopped after {CHILD_TIMEOUT:.0f} s" + if not line: + rc = proc.poll() + if rc is None: + with contextlib.suppress(subprocess.TimeoutExpired): + rc = proc.wait(timeout=2.0) + tail = self._log_tail() + with self._lock: + self._close_locked() + if attempt == 0 and (rc == 0 or rc is None): + continue + return (rc if rc is not None and rc != 0 else -1), tail + try: + resp = json.loads(line.decode("utf-8")) + except ValueError: + tail = self._log_tail() + with self._lock: + self._close_locked(kill=True) + return -1, tail or line.decode("utf-8", errors="replace").strip() + if resp.get("ok"): + return 0, "" + errors = resp.get("errors") or {} + detail = "\n".join(f"{k}: {v}" for k, v in errors.items()) + return 1, detail or self._log_tail() + return -1, "worker failed" def accepts_gzip(header: str | None) -> bool: @@ -353,10 +794,17 @@ def accepts_gzip(header: str | None) -> bool: class PayloadService: """One project's payload cache and its on-demand builder (see the module docstring).""" - def __init__(self, project: Project, clock: Callable[[], float] = time.monotonic) -> None: + def __init__( + self, + project: Project, + clock: Callable[[], float] = time.monotonic, + build_gate: threading.Semaphore | None = None, + ) -> None: self._project = project self._clock = clock + self._build_gate = build_gate self._dir = site_dir(project) / CACHE_DIR / "data" + self._warm = _WarmWorker(project, self._dir.parent) self._cond = threading.Condition() self._queue: list[str] = [] self._current: str | None = None @@ -517,6 +965,7 @@ def prewarm(self) -> None: def stop(self) -> None: """Stop the fingerprint watch and end the build child, if one is running.""" self._stop.set() + self._warm.close() stop_children() def _watch(self) -> None: @@ -605,44 +1054,51 @@ def _install(self, out: Path, name: str, fp: str) -> bool: return True def _build_batch(self, batch: list[str]) -> None: - # fingerprints are taken first: an event landing meanwhile reads as stale - fps = {n: fingerprint(self._project, key_of(n)) for n in batch} - self._dir.mkdir(parents=True, exist_ok=True) - out = Path(tempfile.mkdtemp(prefix="build-", dir=self._dir.parent)) - done: set[str] = set() - - def install() -> None: - for name in batch: - if name in done: - continue - if name == GRIDS: - for found in sorted((out / "data").glob("grid-*.json")): - if self._install(out, found.stem, fps[GRIDS]): - done.add(GRIDS) - elif self._install(out, name, fps[name]): - done.add(name) + gate = contextlib.nullcontext() if self._build_gate is None else self._build_gate + with gate: + # fingerprints are taken first: an event landing meanwhile reads as stale + fps = {n: fingerprint(self._project, key_of(n)) for n in batch} + self._dir.mkdir(parents=True, exist_ok=True) + out = Path(tempfile.mkdtemp(prefix="build-", dir=self._dir.parent)) + done: set[str] = set() + + def install() -> None: + for name in batch: + if name in done: + continue + if name == GRIDS: + for found in sorted((out / "data").glob("grid-*.json")): + if self._install(out, found.stem, fps[GRIDS]): + done.add(GRIDS) + elif self._install(out, name, fps[name]): + done.add(name) - try: - (out / "data").mkdir() - only = ["grid" if n == GRIDS else n for n in batch] - code, tail = spawn_builder(self._project, only, out, install) - install() - missing = [n for n in batch if n not in done] - if missing: - _LOG.error( - "hub payload child exited %s; no payload for %s; last output:\n%s", - code, - ", ".join(missing), - tail, - ) - with self._cond: - for name in missing: - if code == 0 and name.startswith(hub_mining.GRID_PREFIX): - self._unknown[name] = fps[name] # the child built the rest: no such grid - elif code != 0 or name != GRIDS: - self._failed[name] = (fps[name], self._clock()) - finally: - shutil.rmtree(out, ignore_errors=True) + try: + (out / "data").mkdir() + only = ["grid" if n == GRIDS else n for n in batch] + if spawn_builder is _spawn_default_worker: + code, tail = self._warm.run(only, out, install) + else: + code, tail = spawn_builder(self._project, only, out, install) + install() + missing = [n for n in batch if n not in done] + if missing: + _LOG.error( + "hub payload child exited %s; no payload for %s; last output:\n%s", + code, + ", ".join(missing), + tail, + ) + with self._cond: + for name in missing: + if code == 0 and name.startswith(hub_mining.GRID_PREFIX): + self._unknown[name] = fps[ + name + ] # the child built the rest: no such grid + elif code != 0 or name != GRIDS: + self._failed[name] = (fps[name], self._clock()) + finally: + shutil.rmtree(out, ignore_errors=True) # ---------------------------------------------------------------- trace diff --git a/platform/src/factory/services/human_queue.py b/platform/src/factory/services/human_queue.py index 4d013771..b6fe78d2 100644 --- a/platform/src/factory/services/human_queue.py +++ b/platform/src/factory/services/human_queue.py @@ -21,10 +21,11 @@ from enum import StrEnum from factory.errors import FactoryValidationError +from factory.events.reader import cached_reads from factory.model.base import StrictModel from factory.model.members import ProjectRole from factory.model.protocol import ProtocolStatus, ScreeningStage -from factory.services import version_pairs +from factory.services import call_memo, version_pairs from factory.services.agreement import screen_agreement from factory.services.audit import audit_report from factory.services.calibration import calibration_drawn, calibration_status @@ -131,109 +132,114 @@ class HumanQueue(StrictModel): def human_queue(project: Project, *, agent: bool = False) -> HumanQueue: """The pending human acts of `project`; items with a positive count only. `agent` is the agent path's variant (see the module docstring).""" - project.index.sync() - slug = project.paths.slug - base = f"factory --project {slug}" - stages = [ScreeningStage.TITLE_ABSTRACT] - if has_full_text_plan(project): - stages.append(ScreeningStage.FULL_TEXT) - items: list[HumanItem] = [] - held = {} if agent else members(project) + with project.index.frozen_sync(), call_memo.entering(), cached_reads(): + slug = project.paths.slug + base = f"factory --project {slug}" + stages = [ScreeningStage.TITLE_ABSTRACT] + if has_full_text_plan(project): + stages.append(ScreeningStage.FULL_TEXT) + items: list[HumanItem] = [] + held = {} if agent else members(project) - def add(gate: Gate, stage: ScreeningStage | None, count: int, command: str) -> None: - if count > 0: - items.append( - HumanItem( - gate=gate, - stage=None if stage is None else stage.value, - count=count, - command=command, - assignee=assignee_for(gate, held), + def add(gate: Gate, stage: ScreeningStage | None, count: int, command: str) -> None: + if count > 0: + items.append( + HumanItem( + gate=gate, + stage=None if stage is None else stage.value, + count=count, + command=command, + assignee=assignee_for(gate, held), + ) ) - ) - protocol = current_protocol(project) - add( - Gate.PRESS_CONFIRMATION, - None, - int(protocol is not None and protocol.press == "reviewed"), - f"{base} protocol confirm-press ", - ) - for stage in stages: - calibration = calibration_status(project, stage=stage) - if ( - protocol is not None - and protocol.status is ProtocolStatus.READY - and calibration.required - and not calibration_drawn(project, stage=stage) - ): - # The draw itself is the awaiting act: screening is refused until it is made. + protocol = current_protocol(project) + add( + Gate.PRESS_CONFIRMATION, + None, + int(protocol is not None and protocol.press == "reviewed"), + f"{base} protocol confirm-press ", + ) + for stage in stages: + calibration = calibration_status(project, stage=stage) + if ( + protocol is not None + and protocol.status is ProtocolStatus.READY + and calibration.required + and not calibration_drawn(project, stage=stage) + ): + # The draw itself is the awaiting act: screening is refused until it is made. + add( + Gate.CALIBRATION_LABELS, + stage, + 1, + f"{base} calibrate draw --stage {stage.value}", + ) add( Gate.CALIBRATION_LABELS, stage, - 1, - f"{base} calibrate draw --stage {stage.value}", + calibration.drawn - calibration.labelled, + f"{base} calibrate label --stage {stage.value}", + ) + for stage in stages: + add( + Gate.SCREENING_DISAGREEMENTS, + stage, + _screening_disagreements(project, stage), + f"{base} screen disagreements --stage {stage.value}", + ) + for stage in stages: + report = audit_report(project, stage=stage) + add( + Gate.SCREENING_AUDIT, + stage, + 0 if report is None else report.sample_size - report.labelled, + f"{base} audit label ", ) add( - Gate.CALIBRATION_LABELS, - stage, - calibration.drawn - calibration.labelled, - f"{base} calibrate label --stage {stage.value}", - ) - for stage in stages: - add( - Gate.SCREENING_DISAGREEMENTS, - stage, - _screening_disagreements(project, stage), - f"{base} screen disagreements --stage {stage.value}", + Gate.EXTRACTION_DISAGREEMENTS, + None, + extraction_disagreement_count(project), + f"{base} extract agreement", ) - for stage in stages: - report = audit_report(project, stage=stage) + extraction = extraction_audit_report(project) add( - Gate.SCREENING_AUDIT, - stage, - 0 if report is None else report.sample_size - report.labelled, - f"{base} audit label ", + Gate.EXTRACTION_AUDIT, + None, + 0 if extraction is None else extraction.sample_size - extraction.labelled, + f"{base} extract audit-label --correct|--incorrect", ) - add( - Gate.EXTRACTION_DISAGREEMENTS, - None, - extraction_disagreement_count(project), - f"{base} extract agreement", - ) - extraction = extraction_audit_report(project) - add( - Gate.EXTRACTION_AUDIT, - None, - 0 if extraction is None else extraction.sample_size - extraction.labelled, - f"{base} extract audit-label --correct|--incorrect", - ) - intake = intake_counts(project, agent=agent) - for gate, count in ( - (Gate.IMPORT_CONFIRMATION, intake.confirmation), - (Gate.IMPORT_ADMISSION, intake.admission), - (Gate.ATTACHMENTS_WAITING, intake.attachments), - (Gate.DOCUMENTS_UNCONVERTED, intake.unconverted), - (Gate.INBOX_OPEN, intake.inbox), - ): - add(gate, None, count, f"{base} {INTAKE_COMMANDS[gate]}") - add(Gate.VERSION_PAIRS, None, len(version_pairs.candidates(project)), f"{base} dedup pairs") - waiting = _conductor_waiting(project) - if waiting is not None: - gate_id, step = waiting - command = CONDUCTOR_GATE_COMMANDS.get(gate_id, "conductor status") - items.append( - HumanItem( - gate=Gate.CONDUCTOR_WAITING, - stage=step, - count=1, - command=f"{base} {command}", - assignee=assignee_for(Gate.CONDUCTOR_WAITING, held), + intake = intake_counts(project, agent=agent) + for gate, count in ( + (Gate.IMPORT_CONFIRMATION, intake.confirmation), + (Gate.IMPORT_ADMISSION, intake.admission), + (Gate.ATTACHMENTS_WAITING, intake.attachments), + (Gate.DOCUMENTS_UNCONVERTED, intake.unconverted), + (Gate.INBOX_OPEN, intake.inbox), + ): + add(gate, None, count, f"{base} {INTAKE_COMMANDS[gate]}") + add(Gate.VERSION_PAIRS, None, len(version_pairs.candidates(project)), f"{base} dedup pairs") + waiting = _conductor_waiting(project) + if waiting is not None: + gate_id, step = waiting + command = CONDUCTOR_GATE_COMMANDS.get(gate_id, "conductor status") + items.append( + HumanItem( + gate=Gate.CONDUCTOR_WAITING, + stage=step, + count=1, + command=f"{base} {command}", + assignee=assignee_for(Gate.CONDUCTOR_WAITING, held), + ) ) - ) - if not agent: # agent-closed acts and audit samples are the researcher's to see - add(Gate.DEFERRED_REVIEW, None, deferred_count(project), f"{base} review deferred list") - return HumanQueue(items=items) + if not agent: # agent-closed acts and audit samples are the researcher's to see + add( + Gate.DEFERRED_REVIEW, + None, + deferred_count(project), + f"{base} review deferred list", + ) + return HumanQueue(items=items) def _conductor_waiting(project: Project) -> tuple[str, str] | None: diff --git a/platform/src/factory/services/level_statement.py b/platform/src/factory/services/level_statement.py index 75dfab90..dbf10065 100644 --- a/platform/src/factory/services/level_statement.py +++ b/platform/src/factory/services/level_statement.py @@ -18,12 +18,13 @@ from typing import Literal from pydantic import JsonValue +from sqlalchemy import bindparam, text -from factory.events.reader import read_typed from factory.model.base import StrictModel from factory.model.levels import AutonomyLevel, Tier from factory.model.project import RigorMode from factory.modules.contract import GateKind +from factory.services import call_memo from factory.services.context import Project from factory.services.gate_trust import trust_ledger from factory.services.gates import lowered_by_level @@ -97,13 +98,26 @@ def _validation_lines(project: Project, tier: Tier, level: AutonomyLevel) -> lis sample was drawn and labelled and whether a calibration was labelled. Where the profile's evidence is missing the line says `unvalidated`.""" profile = validation_profile(tier, level) - passes: dict[str, set[str]] = {"screening": set(), "extraction": set()} - seen: Counter[str] = Counter() - for event in read_typed(project.paths.events_dir, project.catalog, _VALIDATION_TYPES): - seen[event.type] += 1 - stage = event.type.split(".")[0] - if stage in passes and event.payload.get("pass_label") is not None: - passes[stage].add(str(event.payload["pass_label"])) + project.index.sync() + with project.index.connect() as conn: + type_rows = conn.execute( + text("SELECT type, COUNT(*) FROM events WHERE type IN :types GROUP BY type").bindparams( + bindparam("types", expanding=True) + ), + {"types": list(_VALIDATION_TYPES)}, + ).all() + screen_rows = conn.execute(text("SELECT DISTINCT pass_label FROM decisions")).all() + extract_rows = conn.execute( + text( + "SELECT DISTINCT pass_label FROM extraction_rows " + "UNION SELECT DISTINCT pass_label FROM extraction_claims" + ) + ).all() + seen: Counter[str] = Counter({str(t): int(c) for t, c in type_rows}) + passes: dict[str, set[str]] = { + "screening": {str(p) for (p,) in screen_rows if p is not None}, + "extraction": {str(p) for (p,) in extract_rows if p is not None}, + } ran = "; ".join( f"{stage} {'+'.join(sorted(labels))}" if labels else f"{stage} none" for stage, labels in passes.items() @@ -140,69 +154,75 @@ def _person_reviewed(project: Project) -> bool: } types.update(_VALIDATION_TYPES) types.add("gate.audit_labelled") - return any( - e.actor.kind == "human" - for e in read_typed(project.paths.events_dir, project.catalog, sorted(types)) - ) + project.index.sync() + with project.index.connect() as conn: + row = conn.execute( + text( + "SELECT 1 FROM events WHERE actor_kind = 'human' AND type IN :types LIMIT 1" + ).bindparams(bindparam("types", expanding=True)), + {"types": sorted(types)}, + ).first() + return row is not None def level_statement(project: Project, *, skipped: SkippedSteps | None = None) -> LevelStatement: """The statement for `project`. `skipped` replaces the tier-plan resolver (tests inject a fake); it is called only for a project that declared a tier.""" - levels = project_levels(project) - resolver = skipped if skipped is not None else skipped_steps - steps = resolver(levels.tier) if levels.tier is not None else () - closed = _agent_closed(project) - confirmed = levels.autonomy_level is AutonomyLevel.ATTENDED and not closed - lines: list[str] = [] - if levels.tier is None: - lines.append("tier: not declared (a project that predates tiers)") - else: - lines.append(f"tier: {levels.tier.value} (rigor mode {levels.rigor_mode.value})") - lines.append(f"autonomy level: {levels.autonomy_level.value}") - if levels.rigor_mode is RigorMode.EXPLORATORY: - lines.append("exploratory: the results are not a systematic review") - if steps: - lines.append("skipped compared with a systematic review: " + "; ".join(steps)) - lines.extend(cap_lines(levels.tier)) - lowered = lowered_by_level(project) - if lowered: - lines.append("preset lowered by autonomy level: " + ", ".join(lowered)) - if closed: - lines.append( - "gates closed by an agent: " - + ", ".join(f"{c.gate_id} ({c.closed_by_agent})" for c in closed) + with project.index.frozen_sync(), call_memo.entering(): + levels = project_levels(project) + resolver = skipped if skipped is not None else skipped_steps + steps = resolver(levels.tier) if levels.tier is not None else () + closed = _agent_closed(project) + confirmed = levels.autonomy_level is AutonomyLevel.ATTENDED and not closed + lines: list[str] = [] + if levels.tier is None: + lines.append("tier: not declared (a project that predates tiers)") + else: + lines.append(f"tier: {levels.tier.value} (rigor mode {levels.rigor_mode.value})") + lines.append(f"autonomy level: {levels.autonomy_level.value}") + if levels.rigor_mode is RigorMode.EXPLORATORY: + lines.append("exploratory: the results are not a systematic review") + if steps: + lines.append("skipped compared with a systematic review: " + "; ".join(steps)) + lines.extend(cap_lines(levels.tier)) + lowered = lowered_by_level(project) + if lowered: + lines.append("preset lowered by autonomy level: " + ", ".join(lowered)) + if closed: + lines.append( + "gates closed by an agent: " + + ", ".join(f"{c.gate_id} ({c.closed_by_agent})" for c in closed) + ) + overturned = [c for c in closed if c.overturned > 0] + if overturned: + lines.append( + "overturned by a human review: " + + ", ".join(f"{c.gate_id} ({c.overturned})" for c in overturned) + + "; the act is still active (an overturn writes a label, it does not undo the act)" + ) + reasons = [f"{c.gate_id} ({c.reason})" for c in closed if c.reason] + if reasons: + lines.append("agent-closed gates not yet audited: " + ", ".join(reasons)) + validation_label: str | None = None + if levels.tier is not None: + validation_label = validation_profile(levels.tier, levels.autonomy_level).label + lines.extend(_validation_lines(project, levels.tier, levels.autonomy_level)) + reviewed = _person_reviewed(project) + if not reviewed: + lines.append("no person has reviewed this output") + if not confirmed: + lines.append("not human-confirmed: no person has confirmed the acts an agent closed") + return LevelStatement( + tier=levels.tier, + autonomy_level=levels.autonomy_level, + rigor_mode=levels.rigor_mode, + steps_skipped=steps, + agent_closed=closed, + human_confirmed=confirmed, + person_reviewed=reviewed, + validation_label=validation_label, + lines=tuple(lines), ) - overturned = [c for c in closed if c.overturned > 0] - if overturned: - lines.append( - "overturned by a human review: " - + ", ".join(f"{c.gate_id} ({c.overturned})" for c in overturned) - + "; the act is still active (an overturn writes a label, it does not undo the act)" - ) - reasons = [f"{c.gate_id} ({c.reason})" for c in closed if c.reason] - if reasons: - lines.append("agent-closed gates not yet audited: " + ", ".join(reasons)) - validation_label: str | None = None - if levels.tier is not None: - validation_label = validation_profile(levels.tier, levels.autonomy_level).label - lines.extend(_validation_lines(project, levels.tier, levels.autonomy_level)) - reviewed = _person_reviewed(project) - if not reviewed: - lines.append("no person has reviewed this output") - if not confirmed: - lines.append("not human-confirmed: no person has confirmed the acts an agent closed") - return LevelStatement( - tier=levels.tier, - autonomy_level=levels.autonomy_level, - rigor_mode=levels.rigor_mode, - steps_skipped=steps, - agent_closed=closed, - human_confirmed=confirmed, - person_reviewed=reviewed, - validation_label=validation_label, - lines=tuple(lines), - ) def render_level_statement(statement: LevelStatement) -> str: diff --git a/platform/src/factory/services/prisma.py b/platform/src/factory/services/prisma.py index d00e05f9..4aa5524e 100644 --- a/platform/src/factory/services/prisma.py +++ b/platform/src/factory/services/prisma.py @@ -49,6 +49,7 @@ from factory.model.screening import ScreeningPhase from factory.model.search import QueryKind, QueryPurpose, RunStatus from factory.model.work import ProvenanceMethod, Work +from factory.services import call_memo from factory.services.agreement import ( Outcome, cannot_assess_open, @@ -57,13 +58,13 @@ tolerated_unscreened_works, ) from factory.services.context import Project -from factory.services.dedup import absorbed_by_primary, active_merges, canonical_works +from factory.services.dedup import absorbed_by_primary, active_merges, canonical_work_stubs from factory.services.fulltext_screening import fulltext_queue from factory.services.fulltext_status import fulltext_status from factory.services.protocol import current_protocol, registered_deviation, registered_import from factory.services.ranked_queue import stop_rules_text from factory.services.screening import background_works, screening_stops, stop_unscreened -from factory.services.search import RunSummary +from factory.services.search import RunSummary, WorkStub from factory.services.snowball import query_yields, recorded_rounds UNCONVERTED = "unconverted" @@ -415,74 +416,76 @@ def _omit_empty_selections(self, handler: SerializerFunctionWrapHandler) -> dict def prisma_flow(project: Project) -> PrismaFlow: """The PRISMA 2020 flow of the project as the events stand now.""" - project.index.sync() - canonical = canonical_works(project) - outcomes = final_outcomes(project) - criteria = exclusion_criteria(project) - - databases = _database_records(project) - imports = has_admission(project) - other = {method.value: 0 for method in reported_other_methods(project, imports=imports)} - mechanisms = _chase_mechanisms(project) - detail = dict.fromkeys(OTHER_DETAIL_KEYS, 0) - canonical_with_database = 0 - excluded: dict[str, int] = {} - included = pending = not_screened = 0 - unscreened = stop_unscreened(project) - tolerated = tolerated_unscreened_works(project) - unscreened - tolerated_pending: list[str] = [] - kept = background_works(project, stage=ScreeningStage.TITLE_ABSTRACT, criteria=criteria) - background: dict[str, int] = {} - for work in canonical: - methods = {entry.method for entry in work.provenance} - if ProvenanceMethod.DATABASE in methods: - canonical_with_database += 1 - else: - method = _other_method(work) - other[method.value] += 1 - if method is ProvenanceMethod.CITATION_CHASE: - mechanism = mechanisms.get(_first_chase_run(work), CHASE_UNATTRIBUTED) - detail[mechanism] = detail.get(mechanism, 0) + 1 - outcome = outcomes[work.id] - if outcome is Outcome.INCLUDED: - included += 1 - elif outcome is Outcome.PENDING: - pending += 1 - not_screened += work.id in unscreened - if work.id in tolerated: - tolerated_pending.append(work.id) - else: - criterion = criteria.get(work.id) or UNSPECIFIED - excluded[criterion] = excluded.get(criterion, 0) + 1 - if work.id in kept: - background[criterion] = background.get(criterion, 0) + 1 + with project.index.frozen_sync(), call_memo.entering(): + canonical = canonical_work_stubs(project) + outcomes = final_outcomes(project) + criteria = exclusion_criteria(project) + + databases = _database_records(project) + imports = has_admission(project) + other = {method.value: 0 for method in reported_other_methods(project, imports=imports)} + mechanisms = _chase_mechanisms(project) + detail = dict.fromkeys(OTHER_DETAIL_KEYS, 0) + canonical_with_database = 0 + excluded: dict[str, int] = {} + included = pending = not_screened = 0 + unscreened = stop_unscreened(project) + tolerated = tolerated_unscreened_works(project) - unscreened + tolerated_pending: list[str] = [] + kept = background_works(project, stage=ScreeningStage.TITLE_ABSTRACT, criteria=criteria) + background: dict[str, int] = {} + for work in canonical: + methods = {entry.method for entry in work.provenance} + if ProvenanceMethod.DATABASE in methods: + canonical_with_database += 1 + else: + method = _other_method(work) + other[method.value] += 1 + if method is ProvenanceMethod.CITATION_CHASE: + mechanism = mechanisms.get(_first_chase_run(work), CHASE_UNATTRIBUTED) + detail[mechanism] = detail.get(mechanism, 0) + 1 + outcome = outcomes[work.id] + if outcome is Outcome.INCLUDED: + included += 1 + elif outcome is Outcome.PENDING: + pending += 1 + not_screened += work.id in unscreened + if work.id in tolerated: + tolerated_pending.append(work.id) + else: + criterion = criteria.get(work.id) or UNSPECIFIED + excluded[criterion] = excluded.get(criterion, 0) + 1 + if work.id in kept: + background[criterion] = background.get(criterion, 0) + 1 - protocol = current_protocol(project) - boxes = full_text_boxes(project) - stops = screening_stops(project) - return PrismaFlow( - identified_databases=databases, - identified_other=other, - identified_other_detail=detail if other[ProvenanceMethod.CITATION_CHASE.value] else {}, - duplicates_removed=sum(databases.values()) - canonical_with_database, - version_pair_merges=sum("version-pair" in merge.rule for merge in active_merges(project)), - identical_title_merges=sum( - "title-identical" in merge.rule for merge in active_merges(project) - ), - screened=len(canonical), - excluded=dict(sorted(excluded.items())), - pending=pending, - included=included, - full_text=boxes, - included_in_review=boxes.included if boxes.stage_run else None, - provisional=pending - not_screened - len(tolerated_pending) > 0, - protocol_id=None if protocol is None else protocol.protocol_id, - stop_rule=stop_rules_text(stops) if stops else None, - not_screened_stop=not_screened, - unscreened_tolerated=len(tolerated_pending), - unscreened_tolerated_works=sorted(tolerated_pending), - background=dict(sorted(background.items())), - ) + protocol = current_protocol(project) + boxes = full_text_boxes(project) + stops = screening_stops(project) + return PrismaFlow( + identified_databases=databases, + identified_other=other, + identified_other_detail=detail if other[ProvenanceMethod.CITATION_CHASE.value] else {}, + duplicates_removed=sum(databases.values()) - canonical_with_database, + version_pair_merges=sum( + "version-pair" in merge.rule for merge in active_merges(project) + ), + identical_title_merges=sum( + "title-identical" in merge.rule for merge in active_merges(project) + ), + screened=len(canonical), + excluded=dict(sorted(excluded.items())), + pending=pending, + included=included, + full_text=boxes, + included_in_review=boxes.included if boxes.stage_run else None, + provisional=pending - not_screened - len(tolerated_pending) > 0, + protocol_id=None if protocol is None else protocol.protocol_id, + stop_rule=stop_rules_text(stops) if stops else None, + not_screened_stop=not_screened, + unscreened_tolerated=len(tolerated_pending), + unscreened_tolerated_works=sorted(tolerated_pending), + background=dict(sorted(background.items())), + ) def has_admission(project: Project) -> bool: @@ -721,7 +724,7 @@ def _database_records(project: Project) -> dict[str, int]: return {str(source): int(count) for source, count in rows} -def _first_chase_run(work: Work) -> str: +def _first_chase_run(work: Work | WorkStub) -> str: return min(e.run_id for e in work.provenance if e.method is ProvenanceMethod.CITATION_CHASE) @@ -731,13 +734,13 @@ def unattributed_chase_runs(project: Project) -> list[str]: return sorted( { run - for work in canonical_works(project) + for work in canonical_work_stubs(project) if _other_method_applies(work) and (run := _first_chase_run(work)) not in mechanisms } ) -def _other_method_applies(work: Work) -> bool: +def _other_method_applies(work: Work | WorkStub) -> bool: """Whether the work counts under `citation-chase` in the flow's other methods.""" methods = {entry.method for entry in work.provenance} return ( @@ -781,7 +784,7 @@ def _chase_mechanisms(project: Project) -> dict[str, str]: return out -def _other_method(work: Work) -> ProvenanceMethod: +def _other_method(work: Work | WorkStub) -> ProvenanceMethod: """The highest-precedence non-database method among a work's provenance.""" methods = {entry.method for entry in work.provenance} for method in OTHER_METHODS: diff --git a/platform/src/factory/services/search.py b/platform/src/factory/services/search.py index 43f88d7e..82a01edc 100644 --- a/platform/src/factory/services/search.py +++ b/platform/src/factory/services/search.py @@ -9,6 +9,7 @@ import dataclasses import json from collections.abc import Mapping, Sequence +from dataclasses import dataclass from datetime import date from typing import Any @@ -46,6 +47,26 @@ _PROVENANCE_COLUMNS = "work_id, run_id, query_id, source, method, raw_blob, raw_ref, at" +@dataclass(frozen=True) +class ProvenanceStub: + """Lightweight provenance fields for flow and PRISMA counts.""" + + source: str + run_id: str + query_id: str + method: ProvenanceMethod + + +@dataclass(frozen=True) +class WorkStub: + """Lightweight work projection avoiding Pydantic `Work` hydration.""" + + id: str + title: str + year: int | None + provenance: tuple[ProvenanceStub, ...] + + class RunSummary(StrictModel): """What one `run_query` call recorded, as the caller needs it.""" @@ -458,6 +479,70 @@ def list_works(project: Project, *, include_probe: bool = False) -> list[Work]: return _load_works(project, corpus=not include_probe) +def _year_from_published(published: object) -> int | None: + if published is None: + return None + text_val = str(published) + return int(text_val[:4]) if len(text_val) >= 4 and text_val[:4].isdigit() else None + + +@memoised +def list_work_stubs(project: Project, *, include_probe: bool = False) -> list[WorkStub]: + """Lightweight corpus stubs without hydrating Pydantic `Work` models.""" + project.index.sync() + with project.index.connect() as conn: + rows = conn.execute( + text( + "SELECT work_id, json_extract(data, '$.title'), " + "json_extract(data, '$.dates.published') FROM works ORDER BY work_id" + ) + ).all() + prov_rows = conn.execute( + text( + "SELECT work_id, source, run_id, query_id, method " + "FROM provenance ORDER BY at, run_id" + ) + ).all() + probe_queries = ( + set() + if include_probe + else { + str(row[0]) + for row in conn.execute( + text("SELECT query_id FROM queries WHERE purpose = :probe"), + {"probe": QueryPurpose.PROBE.value}, + ).all() + } + ) + by_work: dict[str, list[ProvenanceStub]] = {} + for work_id, source, run_id, query_id, method in prov_rows: + qid = str(query_id) + if qid in probe_queries: + continue + by_work.setdefault(str(work_id), []).append( + ProvenanceStub( + source=str(source), + run_id=str(run_id), + query_id=qid, + method=ProvenanceMethod(method), + ) + ) + stubs: list[WorkStub] = [] + for wid, title, published in rows: + work_id = str(wid) + provenance = by_work.get(work_id) + if provenance or include_probe: + stubs.append( + WorkStub( + id=work_id, + title=str(title), + year=_year_from_published(published), + provenance=tuple(provenance or ()), + ) + ) + return stubs + + def corpus_size(project: Project) -> tuple[int, int]: """The corpus's (works, records), counted as `list_works` would see them.""" project.index.sync() diff --git a/platform/src/factory/services/site_search.py b/platform/src/factory/services/site_search.py index 748722db..5724f3a5 100644 --- a/platform/src/factory/services/site_search.py +++ b/platform/src/factory/services/site_search.py @@ -15,14 +15,15 @@ from pathlib import Path from typing import Any +from sqlalchemy import text + +from factory.clock import parse_ts from factory.errors import FactoryError -from factory.events.reader import read_all from factory.services.call_memo import entering from factory.services.context import Project from factory.services.dedup import list_merges, merged_after_screening from factory.services.flow_skipped import _archived_pages, run_gaps, skipped_records from factory.services.prisma import search_report -from factory.services.search import list_works from factory.services.site_flow import _embed from factory.services.site_search_page import DATA_MARKER, PAGE from factory.services.site_widgets import FUTURE_CSS @@ -80,20 +81,31 @@ def _queries(project: Project) -> list[dict[str, Any]]: def _revert_times(project: Project) -> dict[str, str]: """The time of the first `dedup.reverted` event of each merge (the one the projection applies), - read from the log because the projection keeps the reason but not the time.""" + read from the events table because the projection keeps the reason but not the time.""" + project.index.sync() + with project.index.connect() as conn: + rows = conn.execute( + text( + "SELECT json_extract(refs, '$[0]'), ts FROM events " + "WHERE type = 'dedup.reverted' ORDER BY id" + ) + ).all() times: dict[str, str] = {} - for event in read_all(project.paths.events_dir, project.catalog): - if event.type == "dedup.reverted": - merge_id = event.payload.get("merge_id") - if isinstance(merge_id, str): - times.setdefault(merge_id, event.ts.strftime("%Y-%m-%d %H:%M")) + for merge_id, ts in rows: + if isinstance(merge_id, str) and merge_id: + times.setdefault(merge_id, parse_ts(str(ts)).strftime("%Y-%m-%d %H:%M")) return times def _merges(project: Project) -> list[dict[str, Any]]: """Every merge, active and reverted, with the titles of its primary and absorbed works.""" reverted_at = _revert_times(project) - titles = {w.id: w.title for w in list_works(project)} + project.index.sync() + with project.index.connect() as conn: + title_rows = conn.execute( + text("SELECT work_id, json_extract(data, '$.title') FROM works") + ).all() + titles = {str(wid): str(title or "") for wid, title in title_rows} rows: list[dict[str, Any]] = [] for m in list_merges(project): rows.append( diff --git a/platform/src/factory/services/site_server.py b/platform/src/factory/services/site_server.py index 77d074ca..06448716 100644 --- a/platform/src/factory/services/site_server.py +++ b/platform/src/factory/services/site_server.py @@ -1263,7 +1263,13 @@ class Slot: advance gate and resume runner. A write for one project never takes another's lock.""" def __init__( - self, project: Project, *, min_gap: float, eager: bool = False, child_builds: bool = False + self, + project: Project, + *, + min_gap: float, + eager: bool = False, + child_builds: bool = False, + build_gate: threading.Semaphore | None = None, ) -> None: self.project = project self.slug = project.paths.slug @@ -1277,14 +1283,16 @@ def __init__( self.write_lock = threading.Lock() self.advance_gate = threading.Lock() self.resumer = ResumeRunner() - self.ui = hub_serve.PayloadService(project) + self.ui = hub_serve.PayloadService(project, build_gate=build_gate) """The hub v2 payload cache and its on-demand builder (served at `/ui/`).""" - def prepare(self) -> None: - """Write the project's hub page, so a served project is never without its hub.""" + def prepare(self, *, prewarm: bool = True, render_classic: bool = True) -> None: + """Write the project's hub page and prewarm hub v2 payloads when requested.""" self.root.mkdir(parents=True, exist_ok=True) - site_service.render_hub(self.project) - self.ui.prewarm() # queues every hub v2 payload; a no-op when FACTORY_HUB_PREWARM=0 + if render_classic: + site_service.render_hub(self.project) + if prewarm: + self.ui.prewarm() # queues every hub v2 payload; a no-op when FACTORY_HUB_PREWARM=0 class Mount(NamedTuple): @@ -1457,6 +1465,11 @@ def do_GET(self) -> None: return if mount.prefix and url in ("/", "/index.html"): hub = slot.root / "index.html" + if not hub.is_file(): + with slot.write_lock: + if not hub.is_file(): + slot.root.mkdir(parents=True, exist_ok=True) + site_service.render_hub(slot.project) if hub.is_file(): text = hub.read_text(encoding="utf-8") self._html(text.replace("", PORTAL_LINK + "", 1)) @@ -2012,6 +2025,7 @@ def __init__( feed_every: float = FEED_CHECK_EVERY, create: Callable[[object, object, object], site_create.Created] | None = None, factory_feed: FactoryFeedEnv | None = None, + max_concurrent_builds: int = 1, ) -> None: self.feed = feed self._factory_feed = factory_feed @@ -2028,6 +2042,7 @@ def __init__( self._background = background self._eager = eager self._child_builds = child_builds + self._build_gate = threading.Semaphore(max_concurrent_builds) self._slots: dict[str, Slot] = {} self._lock = threading.Lock() self._warm_stop = threading.Event() @@ -2060,8 +2075,9 @@ def slot(self, slug: str) -> Slot | None: min_gap=self._min_gap, eager=self._eager, child_builds=self._child_builds, + build_gate=self._build_gate, ) - fresh.prepare() + fresh.prepare(prewarm=self._eager, render_classic=False) if self._background: fresh.rebuilder.start() self._slots[slug] = fresh @@ -2126,7 +2142,7 @@ def rows(self) -> list[site_portal.PortalRow]: built=site_service.built_count(found.project) if building else sum(s.built for s in states), - hub_ready=(found.root / "index.html").is_file(), + hub_ready=True, building=building, activity=activity, activity_end=today.isoformat(), diff --git a/platform/tests/test_agreement.py b/platform/tests/test_agreement.py index a98b3757..dd2adcc6 100644 --- a/platform/tests/test_agreement.py +++ b/platform/tests/test_agreement.py @@ -678,3 +678,27 @@ def test_pass_b_missing_beyond_or_without_tolerance_still_blocks( with pytest.raises(FactoryValidationError): screen_agreement(project, agent) assert not passes_settled(project) + + +def test_refuse_shared_uses_read_typed_not_read_all( + project: Project, + agent: Actor, + human: Actor, + mock_sources: SourcesFor, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import factory.services.agreement as agreement_mod + + protocol_id = _ready(project, agent, human, mock_sources) + for work in _ordinary(project): + _decide(project, agent, work, "A", "screening", "include", None, protocol_id) + for work in _b_queue(project): + _decide(project, agent, work, "B", "screening", "include", None, protocol_id) + + def fail_read_all(*_args: object, **_kwargs: object) -> object: + raise AssertionError("read_all must not be called by _refuse_shared") + + if hasattr(agreement_mod, "read_all"): + monkeypatch.setattr(agreement_mod, "read_all", fail_read_all) + result = screen_agreement(project, agent) + assert result.n_dual > 0 diff --git a/platform/tests/test_conductor.py b/platform/tests/test_conductor.py index d8a6ab3a..4fd5cbee 100644 --- a/platform/tests/test_conductor.py +++ b/platform/tests/test_conductor.py @@ -414,6 +414,53 @@ def test_default_gate_closed_reads_a_later_human_act(project: Project, fake: Fak assert status.state == "waiting" +def test_load_and_default_gate_closed_use_sql_fast_paths( + project: Project, fake: FakeRunner, human: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + import factory.events.reader as reader + from factory.model.imports import ImportResolutionDecided + from factory.model.references import Decision + + def boom(*_args: object, **_kwargs: object) -> object: + raise AssertionError("raw log scan should not run") + + # _load returns None without calling read_typed when no conductor.started event exists. + with monkeypatch.context() as mp: + mp.setattr(conductor, "read_typed", boom) + mp.setattr(reader, "read_typed", boom) + assert conductor._load(project) is None + + conductor.begin_conductor(project, plan("gather")) + conductor.advance(project, start_run=fake.start_run, pending=_idle, gate_closed=_open) + conductor.advance(project, start_run=fake.start_run, pending=_idle, escalate=lambda *_a: None) + + # default_gate_closed uses SQL and never calls read_all. + monkeypatch.setattr(reader, "read_all", boom) + if hasattr(conductor, "read_all"): + monkeypatch.setattr(conductor, "read_all", boom) + assert not conductor.default_gate_closed(project, "gather", "import.resolution_confirm") + assert not conductor.default_gate_closed(project, "gather", "no.such_gate") + + project.record( + [ + project.events.make( + "import.resolution_decided", + ImportResolutionDecided( + import_id=project.ids.new("imp"), + ordinal=1, + decision=Decision.REJECT, + work_id=None, + rationale="not a match", + quotes=("a", "b"), + confirmed_by="human", + ), + human, + ) + ] + ) + assert conductor.default_gate_closed(project, "gather", "import.resolution_confirm") + + # ------------------------------------------------------------------------------- role runs diff --git a/platform/tests/test_flow_ledger.py b/platform/tests/test_flow_ledger.py index 96e5734d..2a96a2f0 100644 --- a/platform/tests/test_flow_ledger.py +++ b/platform/tests/test_flow_ledger.py @@ -1,7 +1,10 @@ """The work ledger and the flow by source reconcile with the PRISMA flow (flow transparency).""" from factory.events.envelope import Actor +from factory.model.decisions import DecisionLevel +from factory.model.search import QueryKind, QuerySpec from factory.services.context import Project +from factory.services.dedup import active_merges, canonical_work_stubs, canonical_works, dedup_run from factory.services.flow_ledger import ( TOTAL, flow_by_source, @@ -11,9 +14,11 @@ ) from factory.services.fulltext_screening import fulltext_queue from factory.services.prisma import prisma_flow -from factory.services.search import list_works +from factory.services.probe import run_probe +from factory.services.search import ProvenanceStub, list_work_stubs, list_works from tests.fulltext_helpers import _ft_world, _ta_world -from tests.helpers import SourcesFor +from tests.helpers import SourcesFor, _seed_item, bind_ids +from tests.screening_helpers import _corpus, _ingest, _settle def test_source_group_is_a_pure_grouping() -> None: @@ -83,3 +88,85 @@ def test_ft_state_follows_the_queue_so_retrieved_matches_eligible( w for w, row in by_id.items() if row.ft_state == "retrieved" } assert all(by_id[w].ft_state in {"not-sought", "attempted-failed"} for w in queue.not_retrieved) + + +def test_canonical_work_stubs_matches_canonical_works_including_description_rank( + explore_project: Project, fake_sources: SourcesFor +) -> None: + # Primary wins `_rank` (more identifiers + abstract), while absorbed wins `_description_rank` + # (`journal-article` vs `other`) and supplies the canonical title and year. + pages = [ + [ + { + "title": "Untyped Draft", + "authors": ["Ada Zhou"], + "year": 2021, + "openalex": "W9001", + "doi": "10.1000/desc-rank", + "type": "other", + "abstract": "Long abstract so _rank chooses this record as primary.", + }, + { + "title": "Published Journal Title", + "authors": ["Ada Zhou"], + "year": 2024, + "openalex": "W9001", + "type": "journal-article", + }, + {"title": "Standalone Paper", "authors": ["Ben Li"], "year": 2023}, + {"title": "Undated Paper", "authors": ["Cai Wu"]}, + ] + ] + _ingest(explore_project, fake_sources, pages) + dedup_run(explore_project) + + [merge] = active_merges(explore_project) + works = canonical_works(explore_project) + stubs = canonical_work_stubs(explore_project) + + expected = [ + ( + w.id, + w.title, + w.dates.year, + tuple(ProvenanceStub(p.source, p.run_id, p.query_id, p.method) for p in w.provenance), + ) + for w in works + ] + actual = [(s.id, s.title, s.year, s.provenance) for s in stubs] + assert actual == expected + + merged_stub = next(s for s in stubs if s.id == merge.primary) + assert merged_stub.title == "Published Journal Title" + assert merged_stub.year == 2024 + + +def test_list_work_stubs_matches_list_works_and_filters_probe( + project: Project, agent: Actor, human: Actor, mock_sources: SourcesFor +) -> None: + protocol_id = _corpus(project, agent, human, mock_sources) + _settle(project, agent, human, protocol_id) + probe = QuerySpec(source="openalex", kind=QueryKind.KEYWORD, text="attention") + run_probe( + project, + agent, + [probe], + sources=mock_sources(openalex=[_seed_item(999)]), + decision_ids=bind_ids(project, agent, DecisionLevel.PROBE), + ) + + for include_probe in (False, True): + works = list_works(project, include_probe=include_probe) + stubs = list_work_stubs(project, include_probe=include_probe) + expected = [ + ( + w.id, + w.title, + w.dates.year, + tuple( + ProvenanceStub(p.source, p.run_id, p.query_id, p.method) for p in w.provenance + ), + ) + for w in works + ] + assert [(s.id, s.title, s.year, s.provenance) for s in stubs] == expected diff --git a/platform/tests/test_gate_audit.py b/platform/tests/test_gate_audit.py index f8afc99b..b00dd042 100644 --- a/platform/tests/test_gate_audit.py +++ b/platform/tests/test_gate_audit.py @@ -240,3 +240,68 @@ def test_rebuild_determinism_with_gate_audit( assert project.index.state_hash() == before report = gate_audit_report(project, LINK) assert report is not None and report.incorrect == 1 + + +def test_agent_labels_skips_log_scan_when_unsampled_or_no_agent_labels( + project: Project, + extraction: str, + agent: Actor, + human: Actor, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import factory.events.reader as reader + from factory.services import gate_trust + + def boom(*_args: object, **_kwargs: object) -> object: + raise AssertionError("read_typed should not run") + + monkeypatch.setattr(reader, "read_typed", boom) + assert gate_trust.agent_labels(project, LINK) == {} + + monkeypatch.undo() + _second_agent_confirms(project, extraction, agent) + gate_audit_sample(project, human, LINK, random_seed=4) + + monkeypatch.setattr(reader, "read_typed", boom) + assert gate_trust.agent_labels(project, LINK) == {} + + +def test_agent_labels_memoises_log_scan_and_keeps_latest_label( + project: Project, + extraction: str, + agent: Actor, + agent_other: Actor, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import factory.events.reader as reader + from factory.model.levels import AutonomyLevel + from factory.services import call_memo, gate_trust + from factory.services import project as project_service + + monkeypatch.setattr( + project_service, + "project_levels", + lambda _p: type("L", (), {"autonomy_level": AutonomyLevel.SUPERVISED})(), + ) + _second_agent_confirms(project, extraction, agent) + sampled = gates.gate_audit_sample_platform(project, LINK) + [act] = sampled.act_event_ids + third = agent_other.model_copy(update={"session": "01JZ9Q3K5M7N8P0R2S4T6V8W0Z"}) + gates.gate_audit_record_agent(project, third, sampled.audit_id, act, False, "first") + gates.gate_audit_record_agent(project, third, sampled.audit_id, act, True, "revised") + + calls = 0 + real_read_typed = reader.read_typed + + def counting_read_typed(*args: object, **kwargs: object) -> object: + nonlocal calls + calls += 1 + return real_read_typed(*args, **kwargs) # type: ignore[arg-type] + + monkeypatch.setattr(reader, "read_typed", counting_read_typed) + with call_memo.entering(): + first_read = gate_trust.agent_labels(project, LINK) + second_read = gate_trust.agent_labels(project, LINK) + assert first_read == {act: True} + assert second_read == {act: True} + assert calls == 1 diff --git a/platform/tests/test_gates_service.py b/platform/tests/test_gates_service.py index 05012287..eec1b5d8 100644 --- a/platform/tests/test_gates_service.py +++ b/platform/tests/test_gates_service.py @@ -148,3 +148,116 @@ def test_autonomy_counts_per_gate( counts = autonomy_counts(project, LINK) assert counts == {Autonomy.HUMAN: 0, Autonomy.AUDITED_AGENT: 0, Autonomy.AGENT: 1} assert sum(autonomy_counts(project, "screening.resolve").values()) == 0 + + +def test_miner_resolutions_fast_paths_and_memo( + project: Project, human: Actor, monkeypatch: pytest.MonkeyPatch +) -> None: + import factory.events.reader as reader + from factory.model.extraction import ExtractionPassOpened, ExtractionResolved + from factory.services import call_memo, gates + + def boom(*_args: object, **_kwargs: object) -> object: + raise AssertionError("unexpected log scan") + + real_read_typed = reader.read_typed + monkeypatch.setattr(reader, "read_all", boom) + monkeypatch.setattr(reader, "read_typed", boom) + assert gates._miner_resolutions(project) == set() + + project.record( + [ + project.events.make( + "extraction.pass_opened", + ExtractionPassOpened( + pass_label=PassLabel.A, + random_seed=1, + field_order="schema", + pack="m-demo", + ), + human, + ) + ] + ) + assert gates._miner_resolutions(project) == set() + + miner_event = project.events.make( + "extraction.resolved", + ExtractionResolved( + work_id="rf:000000000001", + row_key="rk_0123456789ab", + field=None, + choice="a", + reason="ok", + channel=Channel.CLI, + protocol_id="P@00000001", + pack="m-demo", + ), + human, + ) + other_event = project.events.make( + "extraction.resolved", + ExtractionResolved( + work_id="rf:000000000002", + row_key="rk_0123456789ac", + field=None, + choice="b", + reason="ok", + channel=Channel.CLI, + protocol_id="P@00000001", + pack=None, + ), + human, + ) + project.record([miner_event, other_event]) + + calls = 0 + + def counting_read_typed(*args: object, **kwargs: object) -> object: + nonlocal calls + calls += 1 + return real_read_typed(*args, **kwargs) # type: ignore[arg-type] + + monkeypatch.setattr(reader, "read_typed", counting_read_typed) + with call_memo.entering(): + first = gates._miner_resolutions(project) + second = gates._miner_resolutions(project) + assert first == {miner_event.id} + assert second == {miner_event.id} + assert calls == 1 + + +def test_gate_acts_resolves_protocol_without_per_row_protocol_at( + project: Project, human: Actor, monkeypatch: pytest.MonkeyPatch +) -> None: + from factory.services import gates + + first_pid = amend_gate_policies(project, human, []) + e1 = project.events.make( + "screening.pass_joined", + PassJoined(pass_label=PassLabel.A, actor_kind="human", session=human.session), + human, + ) + project.record([e1]) + second_pid = amend_gate_policies(project, human, []) + e2 = project.events.make( + "screening.pass_joined", + PassJoined(pass_label=PassLabel.B, actor_kind="human", session=human.session), + human, + ) + project.record([e2]) + + expected_first = protocol_at(project, e1.id) + expected_second = protocol_at(project, e2.id) + assert expected_first == first_pid + assert expected_second == second_pid + + def fail_protocol_at(*_args: object, **_kwargs: object) -> str | None: + raise AssertionError("protocol_at should not be called per row inside gate_acts") + + monkeypatch.setattr(gates, "protocol_at", fail_protocol_at) + acts = list(gate_acts(project, "screening.pass_join")) + assert [(a.event_id, a.protocol_id) for a in acts] == [ + (e1.id, expected_first), + (e2.id, expected_second), + ] diff --git a/platform/tests/test_hub_build.py b/platform/tests/test_hub_build.py index fdc9f126..76dbfe6a 100644 --- a/platform/tests/test_hub_build.py +++ b/platform/tests/test_hub_build.py @@ -636,3 +636,70 @@ def test_corpus_payload_has_citation_rate_results_and_no_absolute_paths( "file" not in doc and doc["inspector"].startswith("../conversion/doc/") ) assert "/home/" not in json.dumps(payload["works"]) + + +def test_payload_inputs_covers_all_builders_except_payload_events() -> None: + assert set(hb.BUILDERS) - set(hb.PAYLOAD_EVENTS) <= set(hb.PAYLOAD_INPUTS) + assert not hb.reads("platform", "project.created") + assert not hb.reads("platform", "inbox.link_added") + assert hb.reads("pipeline", "runner.finished") + assert not hb.reads("sources", "runner.finished") + assert hb.reads("sources", "file.converted") + assert hb.reads("learn", "feed.fetched") + assert not hb.reads("learn", "file.converted") + assert hb.reads("living", "notice.recorded") + assert not hb.reads("living", "runner.finished") + assert hb.reads("protocol", "protocol.amended") + assert not hb.reads("protocol", "runner.finished") + assert hb.reads("levels", "gate.decided") + assert not hb.reads("levels", "feed.fetched") + assert hb.reads("contradictions", "contradiction.proposed") + assert not hb.reads("contradictions", "runner.finished") + assert hb.reads("chat", "chat.requested") + assert hb.reads("chat", "runner.finished") + + +def test_warm_builder_reuses_context_until_last_event_id_changes( + world: Project, tmp_path: Path +) -> None: + from factory.model.screening import Channel + from factory.services import inbox as inbox_service + + out = tmp_path / "warm" + worker = hb.WarmBuilder(world) + r1 = worker.build_into(["living"], out) + assert r1.errors == {} and "living" in r1.payloads + ctx1 = worker._ctx + assert ctx1 is not None + assert (out / "data/living.json").is_file() and (out / "data/living.json.gz").is_file() + + r2 = worker.build_into(["protocol"], out) + assert r2.errors == {} and "protocol" in r2.payloads + assert worker._ctx is ctx1 # context reused when last_event_id is unchanged + + inbox_service.add_links( + world, world.human_actor(), [inbox_service.LinkInput("10.1234/warm-reset")], Channel.CLI + ) + r3 = worker.build_into(["living"], out) + assert r3.errors == {} and worker._ctx is not ctx1 + + +def test_cli_hub_worker_builds_requests_and_exits_on_eof( + world: Project, settings: Settings, tmp_path: Path +) -> None: + out = tmp_path / "worker-out" + req = json.dumps({"names": ["living", "overview"], "out": str(out)}) + "\n" + result = CliRunner().invoke( + app, + ["hub", "worker", world.paths.slug, "--out", str(out), "--idle", "0"], + input=req, + env=_env(settings.root), + ) + assert result.exit_code == 0, result.output + lines = [json.loads(line) for line in result.output.strip().splitlines() if line.strip()] + assert len(lines) == 1 + assert lines[0]["ok"] is True + assert set(lines[0]["payloads"]) == {"living", "overview"} + assert lines[0]["errors"] == {} + assert (out / "data/living.json").is_file() + assert (out / "data/overview.json.gz").is_file() diff --git a/platform/tests/test_hub_payloads_overview.py b/platform/tests/test_hub_payloads_overview.py index b09c779d..edd56b48 100644 --- a/platform/tests/test_hub_payloads_overview.py +++ b/platform/tests/test_hub_payloads_overview.py @@ -241,3 +241,28 @@ def test_overview_without_a_listed_human_miner_leaves_values_uncoded( assert out["lead"]["human"]["share_none"] is None assert out["lead"]["read_in_full"] == 0 assert out["sets"]["not_read_yet"] == out["sets"]["included"] + + +def test_overview_payload_uses_provided_citation_graph( + project: Project, + agent: Actor, + human: Actor, + mock_sources: SourcesFor, + monkeypatch: pytest.MonkeyPatch, +) -> None: + _ft_world(project, agent, human, mock_sources) + data = hp.load_flow_data(project) + inc = list(data.sets.included) + assert len(inc) >= 3 + graph = make_graph(inc, [(inc[1], inc[0]), (inc[2], inc[0])]) + + def fail_load(_project: Project) -> CitationGraph: + raise AssertionError("load_citation_graph should not be called when graph is provided") + + monkeypatch.setattr(hp, "load_citation_graph", fail_load) + expected = hp.cited_here(project, inc, graph) + out = hp.overview_payload(project, data, graph=graph) + assert out["cited_here"][inc[0]] == [expected[inc[0]].count, expected[inc[0]].self_count] + assert out["cited_here"][inc[0]][0] == 2 + assert out["most_cited"][0]["id"] == inc[0] + assert out["most_cited"][0]["cited_here"] == 2 diff --git a/platform/tests/test_hub_ui_routes.py b/platform/tests/test_hub_ui_routes.py index 84b9aa6a..331116ab 100644 --- a/platform/tests/test_hub_ui_routes.py +++ b/platform/tests/test_hub_ui_routes.py @@ -1114,3 +1114,143 @@ def test_status_reports_a_state_per_payload(project: Project, calls: list[str]) status = service.status() assert status["corpus"]["state"] == "failed" and status["corpus"]["error"] == "build failed" assert status["costs"]["fresh"] is True # the old keys stay + + +def test_asset_version_change_does_not_change_payload_fingerprint( + project: Project, monkeypatch: pytest.MonkeyPatch +) -> None: + hub_serve.code_hash.cache_clear() + before = {n: hub_serve.fingerprint(project, n) for n in ("overview", "corpus", "landscape")} + monkeypatch.setattr(hub_ui, "asset_version", lambda: "changed-asset-version") + hub_serve.code_hash.cache_clear() + after = {n: hub_serve.fingerprint(project, n) for n in ("overview", "corpus", "landscape")} + assert after == before + + +def test_payload_code_hash_differs_per_builder_and_reacts_to_imported_service( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from pathlib import Path + + assert hub_serve.payload_code_hash("costs") != hub_serve.payload_code_hash("overview") + assert hub_serve.payload_code_hash("platform") != hub_serve.payload_code_hash("protocol") + assert hub_serve.payload_code_hash("grid-m-test") == hub_serve.payload_code_hash("mining") + assert hub_serve.payload_code_hash(hub_serve.GRIDS) == hub_serve.payload_code_hash("mining") + + before_overview = hub_serve.payload_code_hash("overview") + before_costs = hub_serve.payload_code_hash("costs") + before_ideas = hub_serve.payload_code_hash("ideas") + before_intuition = hub_serve.payload_code_hash("intuition") + + flow_ledger_path = Path(hub_serve.__file__).resolve().parent / "flow_ledger.py" + real_stat = Path.stat + real_read = Path.read_bytes + + def fake_stat(self: Path, *args: Any, **kwargs: Any) -> os.stat_result: + st = real_stat(self, *args, **kwargs) + if self == flow_ledger_path: + vals = list(st) + vals[6] = st.st_size + 1 # st_size + vals[8] = st.st_mtime + 1 # st_mtime + return os.stat_result(vals) + return st + + def fake_read(self: Path) -> bytes: + data = real_read(self) + if self == flow_ledger_path: + return data + b"\n# edited\n" + return data + + monkeypatch.setattr(Path, "stat", fake_stat) + monkeypatch.setattr(Path, "read_bytes", fake_read) + + assert hub_serve.payload_code_hash("overview") != before_overview + assert hub_serve.payload_code_hash("ideas") == before_ideas + assert hub_serve.payload_code_hash("intuition") == before_intuition + assert hub_serve.payload_code_hash("costs") != before_costs + + +def test_build_gate_caps_concurrent_builds_across_payload_services( + settings: Settings, clock: FixedClock, project: Project, monkeypatch: pytest.MonkeyPatch +) -> None: + from factory.services.project import init_project + + other = init_project(settings, "other", "pilot", session=SESSION, clock=clock) + gate = threading.Semaphore(1) + lock = threading.Lock() + active = 0 + peak = 0 + + def slow(ctx: hb.HubContext) -> dict[str, Any]: + nonlocal active, peak + with lock: + active += 1 + peak = max(peak, active) + time.sleep(0.15) + with lock: + active -= 1 + return {"slug": ctx.project.paths.slug} + + monkeypatch.setitem(hb.BUILDERS, "overview", slow) + monkeypatch.setattr(hub_serve, "LINGER", 0.0) + s1 = hub_serve.PayloadService(project, build_gate=gate) + s2 = hub_serve.PayloadService(other, build_gate=gate) + try: + s1.get("overview") + s2.get("overview") + _idle(s1) + _idle(s2) + assert peak == 1 + assert isinstance(s1.get("overview"), hub_serve.Ready) + assert isinstance(s2.get("overview"), hub_serve.Ready) + finally: + s1.stop() + s2.stop() + + +def test_warm_worker_reuses_one_subprocess_across_batches( + project: Project, monkeypatch: pytest.MonkeyPatch, tmp_path: Any +) -> None: + script = ( + "import json, os, pathlib, sys\n" + "while True:\n" + " line = sys.stdin.readline()\n" + " if not line:\n" + " break\n" + " if not line.strip():\n" + " continue\n" + " req = json.loads(line)\n" + " out = pathlib.Path(req['out']) / 'data'\n" + " out.mkdir(parents=True, exist_ok=True)\n" + " for name in req['names']:\n" + " (out / f'{name}.json').write_text(json.dumps({'pid': os.getpid()}) + '\\n')\n" + " reply = json.dumps({'ok': True, 'payloads': req['names'], 'errors': {}})\n" + " sys.stdout.write(reply + '\\n')\n" + " sys.stdout.flush()\n" + ) + monkeypatch.setattr(hub_serve, "spawn_builder", hub_serve._spawn_default_worker) + monkeypatch.setattr( + hub_serve, + "worker_command", + lambda proj, cache_dir, idle: [sys.executable, "-c", script], + ) + monkeypatch.setattr(hub_serve, "LINGER", 2.0) + service = hub_serve.PayloadService(project) + try: + deadline = time.monotonic() + 20 + a1 = service.get("overview") + while not isinstance(a1, hub_serve.Ready) and time.monotonic() < deadline: + time.sleep(0.05) + a1 = service.get("overview") + assert isinstance(a1, hub_serve.Ready) + pid1 = json.loads(a1.body)["pid"] + + a2 = service.get("living") + while not isinstance(a2, hub_serve.Ready) and time.monotonic() < deadline: + time.sleep(0.05) + a2 = service.get("living") + assert isinstance(a2, hub_serve.Ready) + pid2 = json.loads(a2.body)["pid"] + assert pid1 == pid2 and pid1 != os.getpid() + finally: + service.stop() diff --git a/platform/tests/test_level_statement.py b/platform/tests/test_level_statement.py index dd460323..7aa15aa9 100644 --- a/platform/tests/test_level_statement.py +++ b/platform/tests/test_level_statement.py @@ -210,3 +210,134 @@ def test_statement_carries_the_validation_label_for_the_hub_chip( assert statement.validation_label in render_level_statement(statement) legacy = init_project(settings, "old", "pilot", session=SESSION, clock=clock) assert build_statement(legacy).validation_label is None + + +def test_level_statement_sql_fast_paths_skip_raw_event_reads( + settings: Settings, clock: FixedClock, monkeypatch: pytest.MonkeyPatch +) -> None: + import factory.events.reader as reader + + def boom(*_args: object, **_kwargs: object) -> object: + raise AssertionError("raw log scan should not run") + + monkeypatch.setattr(reader, "read_typed", boom) + monkeypatch.setattr(reader, "read_all", boom) + if hasattr(level_statement, "read_typed"): + monkeypatch.setattr(level_statement, "read_typed", boom) + + project = init_project(settings, "demo", None, session=SESSION, clock=clock, tier="brief") + statement = build_statement(project, skipped=lambda _t: ()) + assert not statement.person_reviewed + assert "passes that ran: screening none; extraction none" in statement.lines + assert "audit: no sample drawn (unvalidated)" in statement.lines + + +def test_validation_lines_and_person_reviewed_read_real_events_from_sql( + settings: Settings, + clock: FixedClock, + human: object, + agent: object, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import factory.events.reader as reader + from factory.events.envelope import Actor + from factory.model.extraction import ClaimRecorded, ClaimType, EvidenceType, Strength + from factory.model.screening import ( + AuditLabelled, + AuditSampled, + Channel, + DecisionRecorded, + PassLabel, + ScreeningPhase, + ScreeningStage, + Verdict, + ) + + assert isinstance(human, Actor) and isinstance(agent, Actor) + project = init_project(settings, "demo", None, session=SESSION, clock=clock, tier="brief") + blob = project.blobs.put_json({"pass": "test"}) + project.record( + [ + project.events.make( + "screening.decision_recorded", + DecisionRecorded( + decision_id=project.ids.new("dec"), + work_id="rf:000000000001", + pass_label=PassLabel.A, + phase=ScreeningPhase.SCREENING, + stage=ScreeningStage.TITLE_ABSTRACT, + verdict=Verdict.INCLUDE, + criterion=None, + quote="quoted text", + rationale="relevant", + protocol_id="P@00000001", + task_id=project.ids.new("tsk"), + supersedes=None, + ), + agent, + input_blob=blob, + ), + project.events.make( + "extraction.claim_recorded", + ClaimRecorded( + claim_id=project.ids.new("clm"), + work_id="rf:000000000001", + pass_label=PassLabel.B, + task_id=project.ids.new("tsk"), + protocol_id="P@00000001", + document_id=project.ids.new("doc"), + conversion_id=project.ids.new("cnv"), + statement="Supported claim.", + claim_type=ClaimType.FINDING, + evidence_type=EvidenceType.EXPERIMENT, + strength=Strength.STRONG, + anchor="s1.p1", + quote="evidence", + supersedes=None, + ), + agent, + input_blob=blob, + ), + ] + ) + audit_id = project.ids.new("aud") + project.record( + [ + project.events.make( + "audit.sampled", + AuditSampled( + audit_id=audit_id, + work_ids=("rf:000000000001",), + random_seed=1, + population=1, + exclusions=0, + inclusions=1, + ), + human, + ), + project.events.make( + "audit.labelled", + AuditLabelled( + audit_id=audit_id, + work_id="rf:000000000001", + verdict="include", + criterion=None, + channel=Channel.CLI, + ), + human, + ), + ] + ) + + def boom(*_args: object, **_kwargs: object) -> object: + raise AssertionError("raw log scan should not run") + + monkeypatch.setattr(reader, "read_typed", boom) + monkeypatch.setattr(reader, "read_all", boom) + if hasattr(level_statement, "read_typed"): + monkeypatch.setattr(level_statement, "read_typed", boom) + + statement = build_statement(project, skipped=lambda _t: ()) + assert statement.person_reviewed + assert "passes that ran: screening A; extraction B" in statement.lines + assert "audit: 1 sample(s) drawn, 1 label(s) recorded" in statement.lines diff --git a/platform/tests/test_site_main_hub.py b/platform/tests/test_site_main_hub.py index c03ef5ce..9df8f20a 100644 --- a/platform/tests/test_site_main_hub.py +++ b/platform/tests/test_site_main_hub.py @@ -91,6 +91,16 @@ def _action_page(project: Project) -> None: def test_every_scanned_project_has_its_hub_before_the_first_request( served: tuple[int, site_server.MainHub], project: Project, two: Project ) -> None: + """Classic index.html is rendered lazily on first visit to `/p//`, while `/api/projects` + always reports `hub_ready=True`.""" + port, _ = served + assert not (site_dir(project) / "index.html").exists() + assert not (site_dir(two) / "index.html").exists() + listing = json.loads(_get(port, "/api/projects")[2]) + assert [p["slug"] for p in listing["projects"]] == ["demo", "other"] + assert all(p["hub_ready"] for p in listing["projects"]) + assert _get(port, "/p/demo/")[0] == 200 + assert _get(port, "/p/other/")[0] == 200 assert (site_dir(project) / "index.html").is_file() assert (site_dir(two) / "index.html").is_file() @@ -292,3 +302,30 @@ def test_a_portal_row_reads_the_funnel_from_the_last_built_overview_and_never_bu assert next(r for r in hub.rows() if r.slug == "other").funnel == (50, 40, 7) (data / "overview.json").write_text("{not json") assert next(r for r in hub.rows() if r.slug == "other").funnel is None + + +def test_main_hub_prepare_all_does_not_start_prewarm_when_not_eager( + settings: Settings, clock: FixedClock, two: Project, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("FACTORY_HUB_PREWARM", "1") + hub = site_server.MainHub( + settings.root, + lambda: list_projects(settings), + lambda slug: open_project(settings, slug, session=SESSION, clock=clock), + min_gap=300.0, + background=True, + eager=False, + ) + try: + slugs = hub.prepare_all() + assert set(slugs) == {"demo", "other"} + demo_slot = hub.slot("demo") + other_slot = hub.slot("other") + assert demo_slot is not None and other_slot is not None + assert demo_slot.ui._worker is None and demo_slot.ui._watcher is None + assert other_slot.ui._worker is None and other_slot.ui._watcher is None + assert demo_slot.ui._queue == [] and other_slot.ui._queue == [] + assert demo_slot.ui._build_gate is hub._build_gate + assert other_slot.ui._build_gate is hub._build_gate + finally: + hub.stop() diff --git a/platform/tests/test_site_search.py b/platform/tests/test_site_search.py index ba99874b..e8a33e58 100644 --- a/platform/tests/test_site_search.py +++ b/platform/tests/test_site_search.py @@ -76,3 +76,36 @@ def ingest(records: list[dict[str, Any]]) -> list[str]: assert sum(c.get("reverted", 0) for c in payload["rule_counts"].values()) == len(reverted) assert all(m["reason"] and m["rat"] for m in shown) assert all(m["rat"] is None for m in payload["merges"] if m["status"] == "active") + + +def test_merges_and_revert_times_read_from_sql_only( + explore_project: Project, fake_sources: SourcesFor, monkeypatch: Any +) -> None: + import factory.events.reader as reader + from factory.services import search, site_search + from factory.services.dedup_incremental import dedup_new + + def ingest(records: list[dict[str, Any]]) -> list[str]: + before = {w.id for w in search.list_works(explore_project)} + _ingest(explore_project, fake_sources, [records]) + return [w.id for w in search.list_works(explore_project) if w.id not in before] + + dedup_new(explore_project, ingest([PUBLISHED, PREPRINT])) + dedup_new(explore_project, ingest([OPENALEX_COPY])) + + expected_times = site_search._revert_times(explore_project) + expected_merges = site_search._merges(explore_project) + assert expected_times + + def boom(*_args: object, **_kwargs: object) -> object: + raise AssertionError("should read from SQLite, not raw log or list_works") + + monkeypatch.setattr(reader, "read_all", boom) + monkeypatch.setattr(search, "list_works", boom) + if hasattr(site_search, "read_all"): + monkeypatch.setattr(site_search, "read_all", boom) + if hasattr(site_search, "list_works"): + monkeypatch.setattr(site_search, "list_works", boom) + + assert site_search._revert_times(explore_project) == expected_times + assert site_search._merges(explore_project) == expected_merges