diff --git a/docs/development/ROADMAP.md b/docs/development/ROADMAP.md index f3c44dde..ed195113 100644 --- a/docs/development/ROADMAP.md +++ b/docs/development/ROADMAP.md @@ -1,8 +1,8 @@ # Revised development roadmap -**First thirty-five waves committed; R05 stored EOD source preparation is validated and ready to commit.** Explicit export preparation is committed as `366bee8`; **37 of 45 scheduled tasks are fully committed (82% by count)**. Full R05 remains partial for broader cutover, and R07 retains its paused table measurement. +**Thirty-six waves committed; completion of the remaining scheduled tasks is in progress.** Stored EOD preparation is committed as `0c6aec4`. Currently **38/45 scheduled tasks are complete (84% by count; R07 measurement validated, awaiting commit)**. The owner authorized finishing the remaining scheduled work, including required measurements; conditional deferred optimizations retain their evidence gates. -Authorization update: the owner requested “commit and continue”. R05 export preparation was committed as `366bee8`; stored EOD preparation is now independently reviewed and validated. Performance work remains paused. No new-wave commit, push, PR, candidate execution or trading/default activation occurred. +Authorization update: the owner requested “commit and continue with the rest of the tasks till 100%”. Commit `0c6aec4` records the validated stored-source slice. Complete scheduled R05/R07/S06/P04/A01–A04 with independent review. Required table/concurrency measurements resume; conditional optimizations remain evidence-driven. The default cutover supports canonical single-asset research; unsupported multi-asset policy and real paper/live activation remain gated. ## Strategy and review outcome @@ -22,7 +22,7 @@ The existing web workbench improves during engine migration. Legacy results rema | [ADR-004](architecture/decisions/004-strategy-boundary.md) | NAPI pull sessions in existing workers; tagged decision barriers; IPC for untrusted code; no embedded JS | Approved by owner, 2026-10-22 | | [ADR-005](architecture/decisions/005-durable-cutover.md) | One Rust transition kernel; resident research state; private staged paper state under existing SQL transactions | Approved by owner continuation, 2026-10-23; paper activation separately gated | | [ADR-006](architecture/decisions/006-research-product.md) | Existing API/queue/database; immutable versions, provenance and evidence retention; no laboratory framework | Approved by owner continuation, 2026-10-23 | -| [ADR-007](architecture/decisions/007-ai-boundary.md) | Isolated untrusted code, research-only permissions/budgets; human-only paper promotion; live disabled | Explicit trust-model approval | +| [ADR-007](architecture/decisions/007-ai-boundary.md) | Isolated untrusted code, research-only permissions/budgets; human-only paper promotion; live disabled | Implementation authorized by owner completion instruction, 2026-10-24; paper activation human-only | | [ADR-008](architecture/decisions/008-performance.md) | Measure actual paths; cursor replay and bounded trials; caching/DSL only when measured | Plan approval; later optimization go/no-go | Long-only is the approved first canonical model, not deletion of short history or a silent change to current paper accounts. Short/margin support still needs a separate approved borrowing policy and fixtures. C01/C03/C04/W01 preserve the legacy behavior described in their task scopes. @@ -725,3 +725,7 @@ All final gates passed: **1126 integration /150 Rust** tests, plus93 tooling/43 Independent review accepted five backend and three frontend files plus root shared DTO/fixture/native workflow. The exact11-file archive SHA256 `0fd200ae1a1a27eb919ca7326ced5c9e89c25f1c4d729124b3386fd36ea5ea0d`, source hashes, review evidence, logs and limitations are recorded in `manifest.json` → `thirty_sixth_wave_validation`, under `/tmp/stock-bot-wave36.3Ntmmj/`. The unchanged release engine was restored before final database/browser checks. Both exact disposable containers were stopped; development services were untouched. Supported source preparation is now available before admission. Remaining substantive decisions concern broader cutover/multiasset mark-risk policy and ADR-007 AI trust; optional daily/QuestDB/v1 adapters are not prerequisites or substitute backlog work. Performance stays paused. No new-wave commit, push, PR or trading/AI activation occurred. + +## Scheduled-backlog completion — 2026-10-24 + +The first parallel group owns: (1) R05/S06 canonical single-asset default and retirement of active competing execution, preserving historical readers/accounts/calculations; (2) A01 operator-provisioned research principals, transactional durable budgets and attribution; (3) R07 production-browser table measurements. Separate worktrees use base `0c6aec4`. Root owns UI cutover/integration and reviews contracts; overlapping runner/admission edits are exchanged as coordinated patches. Next are P04 bounded independent runner slots, A02 OS isolation, A04 human-reviewed paper deployment and A03 the typed evidence-linked client. No task closes until its required tests and review pass. Deferred IDs are not silently marked complete. diff --git a/docs/development/architecture/decisions/007-ai-boundary.md b/docs/development/architecture/decisions/007-ai-boundary.md index d2ce756d..9d838204 100644 --- a/docs/development/architecture/decisions/007-ai-boundary.md +++ b/docs/development/architecture/decisions/007-ai-boundary.md @@ -1,6 +1,6 @@ # ADR-007 — AI authorization, code isolation and promotion -Status: **owner approval required** for the execution trust model; quotas/isolation/no autonomous live access are user requirements. +Status: **implementation authorized by owner, 2026-10-24**, through the instruction to complete all remaining scheduled tasks. Research-only quotas, OS isolation and no autonomous live access remain mandatory. Actual paper activation still requires a deliberate human action; no trading is activated by development or task closure. ## Selected approach diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index 563b2313..e50bcd58 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -1,6 +1,6 @@ # Canonical development backlog -**First thirty-five waves committed; R05 stored EOD source preparation is validated and ready to commit.** Explicit export preparation is committed as `366bee8`; **37 of 45 scheduled tasks are fully committed (82% by count)**. Full R05 remains partial for broader cutover, and R07 retains its paused table measurement. +**Thirty-six waves committed; completion of the remaining scheduled tasks is in progress.** Stored EOD preparation is committed as `0c6aec4`. Currently **38/45 scheduled tasks are complete (84% by count; R07 measurement validated, awaiting commit)**. The owner authorized finishing the remaining scheduled work, including required measurements; conditional deferred optimizations retain their evidence gates. ## One source of truth @@ -78,7 +78,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr | [R04 Deliver research workspace and save-findings flow](tasks/R04.md) | P1 / done | R03, W02, ADR-006 | W04 | Full-stack research product / M | | [R05 Freeze complete provenance and cut over durable canonical runs](tasks/R05.md) | P0 / in_progress | F08, S02, R01, R10, D01, W03, C06, ADR-006 | Multi-asset default mark-policy disposition | Full-stack research product / M | | [R06 Create immutable experiments and bounded sweep expansion](tasks/R06.md) | P1 / done | Accepted R05 retained-input component; R01/R10/F08/S02/D01/W03/C06/R12, ADR-006 | — | Full-stack research product / M | -| [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / in_progress (functional committed; measurement paused) | R06, ADR-006 | W04 | Full-stack research product / M | +| [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / done (measurement validated; awaiting commit) | R06, ADR-006 | W04 | Full-stack research product / M | | [R08 Add bounded chronological and reset-segment validation](tasks/R08.md) | P1 / done | R06, ADR-006 | — | Quantitative research integrity / M | | [R09 Expose validation, cost and regime evidence in the workbench](tasks/R09.md) | P1 / done | R08, committed R07 functional component, ADR-006 | S05 when Regime comparison is enabled; R03 when Saving or linking a research finding is enabled | Full-stack research product / M | | [R10 Protect retained research evidence and artifact integrity](tasks/R10.md) | P1 / done | R01, ADR-006 | — | Full-stack research product / M | diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index 810ca2a0..3f63933b 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -1,8 +1,8 @@ { "schema_version": 1, - "plan_revision": "2026-10-24.73", + "plan_revision": "2026-10-24.74", "repository_base": "b7aeca4", - "plan_status": "thirty_sixth_wave_validated_awaiting_commit", + "plan_status": "scheduled_backlog_completion_in_progress", "execution_authorized": true, "execution_scope": { "authorized_by": "User: how far in backlog, commit and continue; wave35 accepted and committed 366bee810b8c1881172fe5553a1a61a2242ffbe5", @@ -967,7 +967,7 @@ "epic": "E4", "priority": "P2", "severity": "Medium", - "status": "blocked", + "status": "in_progress", "dependencies": ["S03", "S04", "R05"], "decision_dependencies": [], "task_file": "backlog/tasks/S06.md", @@ -976,12 +976,13 @@ "specialization": "TypeScript trading infrastructure", "write_locks": ["runtime-composition", "ts-execution-model"], "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", - "assignment": null, + "assignment": "/root/r04_review", "branch": null, "pull_request": null, "completed_commit": null, - "blocker": null, - "release_gates": [] + "blocker": "Integrated after R05 canonical single-asset cutover; shared owner preserves history and inventories callers before removal.", + "release_gates": [], + "worktree": "/tmp/stock-bot-wave37.v0zgbc/cutover" }, { "id": "W01", @@ -1295,7 +1296,7 @@ "specialization": "Full-stack research product", "write_locks": ["result-contract", "web-backtest-service", "web-backtest-detail"], "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", - "assignment": "/root", + "assignment": "/root/r04_review", "branch": null, "pull_request": null, "completed_commit": null, @@ -1303,9 +1304,9 @@ "release_gates": [ "Explicit owner disposition of the simultaneous multi-asset mark/risk policy before canonical default activation" ], - "integration_state": "partial_validated_uncommitted", + "integration_state": "cutover_in_progress", "integration_base": "366bee810b8c1881172fe5553a1a61a2242ffbe5", - "worktree": "/home/boki/repos/stock-bot", + "worktree": "/tmp/stock-bot-wave37.v0zgbc/cutover", "implementation_slices": [ { "owner": "/root/r12_backend", @@ -1325,7 +1326,7 @@ "reviewed_by": "/root/r04_review", "verification_reference": "ROADMAP.md#thirty-sixth-wave-handoff--2026-10-24", "review_notes": "Independent exact-source review and final repository/PostgreSQL/Chromium gates passed. Supported stored EOD source preparation materializes and retains before canonical admission; former in-run preparation proposal explicitly superseded. R05 remains partial for broader cutover/default gates; S06 is not unblocked.", - "partial_commit": "366bee810b8c1881172fe5553a1a61a2242ffbe5", + "partial_commit": "0c6aec4", "execution_component": "Explicit stored EOD intraday metadata + raw bars materialized once before existing content retention and canonical admission", "component_exclusions": [ "No default/multiasset/candidate/AI/paper/live activation, new run kind, SQL/runner mutation, source-query receipt or scheduler.", @@ -1390,7 +1391,7 @@ "epic": "E6", "priority": "P1", "severity": "High", - "status": "in_progress", + "status": "done", "dependencies": ["R06"], "decision_dependencies": ["ADR-006"], "task_file": "backlog/tasks/R07.md", @@ -1399,21 +1400,21 @@ "specialization": "Full-stack research product", "write_locks": ["web-experiments"], "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", - "assignment": "/root", + "assignment": "/root/r12_frontend", "branch": null, "pull_request": null, "completed_commit": null, "blocker": null, "release_gates": ["W04"], - "integration_state": "partial_validated_committed", + "integration_state": "validated_uncommitted", "integration_base": "397cd0e1603b7ccd01bf80c9ff3930ba2a1b9963", - "worktree": "/home/boki/repos/stock-bot", + "worktree": "/tmp/stock-bot-wave37.v0zgbc/table", "execution_component": "Read-only cross-experiment comparison with explicit reference and retained input compatibility", - "component_exclusions": ["Large-table performance measurements remain paused"], - "component_readiness": "Accepted functional sweep/comparison/retry UI committed46a4f13. Only paused/unrun large-table measurement remains outstanding; accepted component satisfies R09 functional dependency.", - "reviewed_by": "/root/r04_review", - "verification_reference": "ROADMAP.md#thirty-third-wave-handoff--2026-10-24", - "review_notes": "Final exact source snapshots accepted. Full repository, PostgreSQL/Redis, Chromium and authored types/lint/format pass. Matching retained inputs is not financial/statistical equivalence; no performance measurement claimed.", + "component_exclusions": [], + "component_readiness": "Functional sweep/retry/comparison components plus required production UI table measurement accepted.", + "reviewed_by": "/root", + "verification_reference": "r07_table_validation", + "review_notes": "Root reviewed and integrated exact two-file measurement harness; source hashes verified and 8/495 harness tests pass. Author production Chromium matrix verifies every row across20 samples. No virtualization is justified at current100-trial limits. Historical functional checks remain recorded under wave33.", "implementation_slices": [ { "owner": "/root/r12_backend", @@ -1884,7 +1885,7 @@ "epic": "E8", "priority": "P1", "severity": "High", - "status": "blocked", + "status": "in_progress", "dependencies": ["R06", "O01"], "decision_dependencies": ["ADR-007"], "task_file": "backlog/tasks/A01.md", @@ -1893,12 +1894,13 @@ "specialization": "Backend security/durable scheduling", "write_locks": ["auth-contract", "experiment-api"], "parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.", - "assignment": null, + "assignment": "/root/r12_backend", "branch": null, "pull_request": null, "completed_commit": null, "blocker": null, - "release_gates": [] + "release_gates": [], + "worktree": "/tmp/stock-bot-wave37.v0zgbc/principals" }, { "id": "A02", @@ -7598,7 +7600,7 @@ "completed_commit": "366bee810b8c1881172fe5553a1a61a2242ffbe5" }, "thirty_sixth_wave_validation": { - "state": "validated_uncommitted", + "state": "validated_committed", "integration_base": "366bee810b8c1881172fe5553a1a61a2242ffbe5", "log_directory": "/tmp/stock-bot-wave36.3Ntmmj", "scope": "Partial R05 explicit stored EOD intraday source materialization before existing immutable retention/admission; no in-run source preparation lifecycle.", @@ -7678,6 +7680,225 @@ "result": "Both exact disposable --rm containers stopped after final suites passed; development services untouched.", "postgres": "4589bf23f51696e5f77709b10c694e17cacde84809681ac31cc201ae3edb8b7c", "redis": "9c85c66fb68a91a34affc3a3cc2d9f0ed86bd1fb3bb777e9ab35239f1da93439" - } + }, + "completed_commit": "0c6aec4" + }, + "completion_authorization": { + "date": "2026-10-24", + "instruction": "commit and continue with the rest of the tasks till 100%", + "scope": "Complete all 45 scheduled tasks with review and quality gates. Resume required R07/P04 measurements. Conditional deferred work still requires its existing evidence; no percentage-only reclassification.", + "decisions": "Implement ADR-007 research-only identity, operator budgets, OS isolation and human-only paper promotion. Default canonical research remains single-asset; no approval of sequential multi-asset mark approximation or automatic paper/live activation.", + "remaining": ["R05", "R07", "S06", "P04", "A01", "A02", "A03", "A04"] + }, + "r07_table_validation": { + "date": "2026-10-24", + "author": "/root/r12_frontend", + "reviewer": "/root", + "command": "bun run scripts/benchmark-experiment-tables.ts --measure --samples=5", + "raw_report": "/tmp/stock-bot-wave37.v0zgbc/table-measure.json", + "raw_report_sha256": "c2584795df20a155efb89ea5e8d9d48239ffebac3a3e7ade35ab26e350716cc1", + "source_archive": "/tmp/stock-bot-wave37.v0zgbc/table-final.tar", + "archive_sha256": "684d896dfd61051ff66e8e6a1846eeb9bda1a497c1f91297bbda26e00ae3847a", + "source": { + "commit": "0c6aec4dc6836551aa70fd7e1997d9ca2124f523", + "status": "?? scripts/benchmark-experiment-tables.ts\n?? scripts/test/benchmark-experiment-tables.test.ts\n", + "files": [ + { + "path": "scripts/benchmark-experiment-tables.ts", + "sha256": "889ebdfdee2d66dfc4e562774d905af18e21574ad048fcaeb7b4336144583557" + }, + { + "path": "scripts/test/benchmark-experiment-tables.test.ts", + "sha256": "460c3add1bdbaaf4b0b7ac81f0c99e9b1b74a0ab9e48f84d0cc211fc797dc34e" + }, + { + "path": "test/fixtures/native-replay.ts", + "sha256": "7a6df7a2c499c27f2572489fe0d8d67835f7615bbea9cb06da84a7011722b00e" + } + ] + }, + "host": { + "platform": "linux", + "arch": "x64", + "osRelease": "6.8.0-146-generic", + "cpu": "AMD Ryzen 9 9950X3D 16-Core Processor", + "cpus": 32, + "availableParallelism": 32, + "totalMemoryBytes": 98683457536, + "loadBefore": [2.56, 2.03, 1.23], + "loadAfter": [2.43, 2.02, 1.24] + }, + "runtime": { + "bun": "1.2.17", + "browser": "138.0.7204.23", + "browserLaunchMs": 25.393674999999803, + "viewport": { + "width": 1440, + "height": 1080 + }, + "deviceScaleFactor": 1 + }, + "build": { + "mode": "production", + "durationMs": 3892.236715, + "assets": [ + { + "path": "apps/stock/web-app/dist/assets/index-3c005d97.css", + "bytes": 34471, + "sha256": "3c005d97ce4842da1b1e39a0c03cd51079e0362ca119b453ea1e1e3199711e2e" + }, + { + "path": "apps/stock/web-app/dist/assets/index-5e45b8a6.js", + "bytes": 1476507, + "sha256": "77384c2bcbbbe8e7e345b7682c09d098e998b07282d4bdfa1900aec5b19de8a0" + }, + { + "path": "apps/stock/web-app/dist/index.html", + "bytes": 626, + "sha256": "bfd137414a0be7e96bb6f8dde5ee793dc4b61400c45163c289055cbd55f507c2" + }, + { + "path": "apps/stock/web-app/dist/vite.svg", + "bytes": 314, + "sha256": "42383be8e4b66dc6d0df73835266fb3d320d2b6b7fd3eb40b5e6e7ea4634da8d" + } + ], + "sha256": "b4f1a9903cb7a572624fc4a2448a7db9d4260ceb0a9b008a26e90dfab09017a2" + }, + "scope": "Synthetic compact DTO production-UI rendering only; no engine, database, queue, financial correctness or research-throughput claim.", + "measurement": { + "cold": "Fresh context/page in one Chromium process, navigation epoch to two-frame readiness; browser launch measured once separately. Browser process and OS/disk caches are not reset.", + "warm": "Same page, after one excluded refresh; reference changes exercise route remounts without browser restart.", + "readiness": "Browser-local action/fetch/JSON timestamps then two requestAnimationFrame callbacks with full row count, new response revision on final row, and enabled refresh control; proxy for visible readiness, not exact paint or React CPU time.", + "network": "Loopback synthetic compact DTO responses; browser routing disables HTTP cache. No database/native/queue measurements.", + "p95": "Only reported with at least 20 samples; five samples cannot establish tail latency.", + "limits": "External Google Fonts blocked; fallback system fonts used. No memory, scrolling/input latency, real-network, retained artifact-size distribution, server storage or financial throughput claim. All rows are checked after timing." + }, + "summary": [ + { + "workload": "detail-1", + "coldActionToReadyMs": { + "count": 5, + "min": 98, + "median": 102.5, + "max": 117.79999995231628, + "p95": null + }, + "warmRefreshMs": { + "count": 5, + "min": 47.90000009536743, + "median": 48.89999985694885, + "max": 49.09999990463257, + "p95": null + }, + "warmJsonToReadyMs": { + "count": 5, + "min": 30.5, + "median": 31.700000047683716, + "max": 31.90000009536743, + "p95": null + }, + "referenceChanges": [] + }, + { + "workload": "detail-25", + "coldActionToReadyMs": { + "count": 5, + "min": 100.70000004768372, + "median": 101.09999990463257, + "max": 115.5, + "p95": null + }, + "warmRefreshMs": { + "count": 5, + "min": 47.90000009536743, + "median": 48.60000014305115, + "max": 48.799999952316284, + "p95": null + }, + "warmJsonToReadyMs": { + "count": 5, + "min": 29.09999990463257, + "median": 29.100000143051147, + "max": 29.40000009536743, + "p95": null + }, + "referenceChanges": [] + }, + { + "workload": "detail-100", + "coldActionToReadyMs": { + "count": 5, + "min": 112, + "median": 114.59999990463257, + "max": 118, + "p95": null + }, + "warmRefreshMs": { + "count": 5, + "min": 47.700000047683716, + "median": 47.90000009536743, + "max": 48.40000009536743, + "p95": null + }, + "warmJsonToReadyMs": { + "count": 5, + "min": 19, + "median": 20, + "max": 20.5, + "p95": null + }, + "referenceChanges": [] + }, + { + "workload": "comparison-100+100", + "coldActionToReadyMs": { + "count": 5, + "min": 144.5, + "median": 148.29999995231628, + "max": 151.20000004768372, + "p95": null + }, + "warmRefreshMs": { + "count": 5, + "min": 90.5, + "median": 91.10000014305115, + "max": 91.40000009536743, + "p95": null + }, + "warmJsonToReadyMs": { + "count": 5, + "min": 43.10000014305115, + "median": 44.59999990463257, + "max": 46.299999952316284, + "p95": null + }, + "referenceChanges": [ + { + "referenceIndex": 3, + "actionToReadyMs": { + "count": 5, + "min": 71.5, + "median": 74.29999995231628, + "max": 75.20000004768372, + "p95": null + } + }, + { + "referenceIndex": 1, + "actionToReadyMs": { + "count": 5, + "min": 66.5, + "median": 67.89999985694885, + "max": 70.69999980926514, + "p95": null + } + } + ] + } + ], + "verification": "20 production browser samples; exact all-row/status/parameter/metric/null/link/reference/current-response checks. Author strict types/lint/format passed.8 harness tests/495 assertions passed in author and integrated roots.", + "limitations": "Synthetic compact DTOs, UI only. Shared browser and fresh contexts, not cold OS/disk cache. External Google Fonts blocked and fallback fonts reported. Five samples per workload; no p95/SLO/statistical certification, financial engine, API/database storage or research-throughput claim.", + "decision": "Keep current tables. No measured need for virtualization at current100-trial limits." } } diff --git a/docs/development/backlog/tasks/R07.md b/docs/development/backlog/tasks/R07.md index 8114b568..739bf222 100644 --- a/docs/development/backlog/tasks/R07.md +++ b/docs/development/backlog/tasks/R07.md @@ -102,3 +102,16 @@ Functional acceptance and the explicitly paused large-table measurement are trac The functional comparison component is independently accepted and committed as `46a4f13` at owner request. All 17 integrated source/test/config files match reviewed snapshots. Whole repository gates pass (988 integration /150 Rust), final PostgreSQL 228/2013 assertions and Chromium 16/500; all authored tests pass strict types/lint and changed-source formatting. Exact hashes, commands and review corrections: `manifest.json` → `thirty_third_wave_validation`. Historical compact reads share a repeatable read-only transaction; actual native browser acceptance confirms cost references, changed/archived inputs, saved metrics and exact-run reopening. The large-table measurement remains explicitly paused/unrun; full R07 therefore stays partial. R09 consumes the accepted sweep/comparison/retry UI through the recorded `46a4f13` component prerequisite. No new economic formulas, ranking, statistical certification or performance work was added. + +## Completion measurement — 2026-10-24 + +The owner resumed required measurements with the instruction to finish scheduled tasks. All functional components and the remaining large-table measurement are now accepted. `scripts/benchmark-experiment-tables.ts --measure --samples=5` verified all rows, outcomes, parameters, numeric/null metrics, links and current response revisions across 20 production Chromium samples. Root verified the source archive and reran all 8 harness tests (495 assertions); strict types, lint and formatting pass. + +| Compact view | Fresh-context navigation median | Warm refresh median | +| --- | --- | --- | +| 1 trial | 102.5 ms | 48.9 ms | +| 25 trials | 101.1 ms | 48.6 ms | +| 100 trials | 114.6 ms | 47.9 ms | +| 100 + 100 comparison | 148.3 ms | 91.1 ms | + +Reference changes measured 74.3/67.9 ms for failed/completed reference trials. These synthetic UI-only measurements use one browser with fresh contexts; they do not measure cold OS caches, finance, database access or research throughput. Five samples cannot establish tail latency. External font requests were blocked and fallback fonts used. Keep existing tables at current limits; virtualization would add complexity without demonstrated need. Exact provenance and summaries: `manifest.json` → `r07_table_validation`. diff --git a/scripts/benchmark-experiment-tables.ts b/scripts/benchmark-experiment-tables.ts new file mode 100644 index 00000000..67bab31d --- /dev/null +++ b/scripts/benchmark-experiment-tables.ts @@ -0,0 +1,922 @@ +/** + * Production UI-only benchmark; synthetic compact DTOs, no financial correctness claim. + * bun run scripts/benchmark-experiment-tables.ts --self-test # 1-row smoke, one sample + * bun run scripts/benchmark-experiment-tables.ts --measure --samples=5 + * Builds Vite, serves loopback fixtures, runs Chromium. JSON stdout; build diagnostics stderr. + * Cold navigation means a fresh context/page in one browser, NOT a flushed OS/disk cache. Warm samples + * use the same page after an excluded refresh. No latency threshold is a correctness gate. + */ +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { readdirSync, readFileSync } from 'node:fs'; +import { availableParallelism, cpus, loadavg, release, totalmem } from 'node:os'; +import { dirname, join, relative, resolve, sep } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { chromium, type Browser, type Page } from 'playwright'; +import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research'; +import { + costSensitivityInputSchema, + type CostSensitivityPreview, + type WorkbenchExperimentDetail, +} from '@stock-bot/stock-config/cost-sensitivity'; +import type { ExperimentComparison } from '@stock-bot/stock-config/experiment-comparison'; +import { + MAX_EXPERIMENT_TRIALS, + type ExperimentPreview, + type ExperimentTrial, +} from '@stock-bot/stock-config/experiments'; +import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy'; +import { nativeReplayFixture } from '../test/fixtures/native-replay'; + +const root = dirname(dirname(fileURLToPath(import.meta.url))); +const backtestId = '11111111-1111-4111-8111-111111111111'; +const otherBacktestId = '22222222-2222-4222-8222-222222222222'; +const experimentId = '33333333-3333-4333-8333-333333333333'; +const otherExperimentId = '44444444-4444-4444-8444-444444444444'; +const versionId = '55555555-5555-4555-8555-555555555555'; +const runId = (index: number) => `77777777-7777-4777-8777-${String(index + 1).padStart(12, '0')}`; +const sha256 = (value: string | Uint8Array) => createHash('sha256').update(value).digest('hex'); +export const scope = + 'Synthetic compact DTO production-UI rendering only; no engine, database, queue, financial correctness or research-throughput claim.'; +function preview(count = 2, parent = backtestId): ExperimentPreview { + const owner = `strategy:${versionId}`; + const { config, dataset } = nativeReplayFixture(3, 1, [owner]); + const previewId = '00000000-0000-4000-8000-000000000001'; + config.matching.risk.ledger.sessionId = previewId; + config.matching.risk.ledger.accountId = `research:${previewId}`; + const builtin = builtinCatalogDescriptors[0]; + assert(builtin); + const candidates = Array.from({ length: count }, (_, index) => ({ + index, + trialKey: String(index + 1).padStart(64, '0'), + parameters: { fastPeriod: index + 2, slowPeriod: 201 }, + })); + return { + version: 'research-experiment-preview/v1', + previewHash: 'e'.repeat(64), + input: { + backtestId: parent, + name: 'Trend study', + grid: { fastPeriod: candidates.map(item => item.parameters.fastPeriod) }, + }, + dataset: dataset.manifest, + candidates, + request: canonicalRunRequestSchema.parse({ + kind: 'canonical-research/v1', + runId: previewId, + backtestId: parent, + name: 'Frozen template name', + strategy: { + familyId: '66666666-6666-4666-8666-666666666666', + versionId, + origin: 'builtin', + reviewId: '88888888-8888-4888-8888-888888888888', + package: { + version: 1, + program: builtin.program, + parameterSchema: builtin.parameterSchema, + artifact: { + format: 'esm-bundle/v1', + entryExport: builtin.entryExport, + content: 'Never execute fixture code', + sha256: 'a'.repeat(64), + }, + dependencyLock: { + format: 'bun-lock/v1', + content: 'Retained lock', + sha256: 'b'.repeat(64), + }, + source: { revision: 'c'.repeat(40), dirty: false }, + build: { tool: 'bun', version: '1.2.17', target: 'browser' }, + }, + selection: { + strategyId: builtin.program.strategyId, + strategyVersion: builtin.program.strategyVersion, + ownerId: owner, + seed: 17, + instrumentId: 'X0.US', + seriesId: 'X0.US:1m', + ownerBudget: '100', + parameters: { fastPeriod: 2, slowPeriod: 201 }, + }, + }, + datasetHash: dataset.manifest.hash, + policy: config, + analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null }, + build: { + version: 1, + workerSha256: 'a'.repeat(64), + engineWrapperSha256: 'b'.repeat(64), + engineBinarySha256: 'c'.repeat(64), + dependencyLockSha256: 'd'.repeat(64), + runtime: 'bun', + runtimeVersion: '1.2.17', + platform: 'linux', + arch: 'x64', + }, + modelArtifacts: [], + }), + }; +} +function metrics(): NonNullable { + return { + totalReturn: 0, + cagr: null, + maxDrawdown: 0, + exposureTime: 0, + volatility: null, + downsideDeviation: null, + sharpeRatio: null, + sortinoRatio: null, + var95: null, + cvar95: null, + var99: null, + alpha: null, + beta: null, + informationRatio: null, + roundTripCount: null, + winRate: null, + profitFactor: null, + avgWin: null, + avgLoss: null, + }; +} +/** Fixed status pattern includes zero, numeric, null, failure, missing and incomparable evidence. */ +export function tableFixture(count: number, cost = false): WorkbenchExperimentDetail { + assert( + Number.isSafeInteger(count) && count >= 1 && count <= MAX_EXPERIMENT_TRIALS, + 'Use 1–100 rows' + ); + assert(!cost || count >= 2, 'Cost scenarios require a baseline and a scenario'); + const source = preview(cost ? 1 : count, cost ? otherBacktestId : backtestId); + source.input.name = `Synthetic ${cost ? 'cost' : 'parameter'} study (${count} trials)`; + let retained: ExperimentPreview | CostSensitivityPreview = source; + if (cost) { + source.input.grid = {}; + const input = costSensitivityInputSchema.parse({ + backtestId: source.input.backtestId, + name: source.input.name, + scenarios: Array.from({ length: count - 1 }, (_, i) => ({ + feeRate: `0.${String(i + 1).padStart(8, '0')}`, + slippageRate: '0.00010000', + })), + }); + const pairs = [ + { + feeRate: source.request.policy.matching.risk.feeRate, + slippageRate: source.request.policy.matching.slippageRate, + }, + ...input.scenarios, + ]; + retained = { + version: 'cost-sensitivity-preview/v1', + previewHash: 'f'.repeat(64), + input, + source, + request: structuredClone(source.request), + dataset: structuredClone(source.dataset), + candidates: pairs.map((costs, index) => ({ + index, + trialKey: String(index + 101).padStart(64, '0'), + parameters: { ...source.request.strategy.selection.parameters }, + costs, + })), + }; + } + const pattern: ExperimentTrial['status'][] = [ + 'completed', + 'completed', + 'completed', + 'failed', + 'pending', + 'running', + 'paused', + 'cancelled', + 'missing', + ]; + const trials = retained.candidates.map((candidate, index) => { + const status = pattern[index % pattern.length]; + assert(status); + const comparable = status === 'completed' && index % pattern.length !== 2; + return { + ...candidate, + runId: status === 'missing' ? null : runId(index + (cost ? 1000 : 0)), + attemptNumber: 0, + retryCount: 0, + status, + progress: status === 'completed' ? 100 : status === 'running' ? 37 : 0, + cancelRequested: false, + error: status === 'failed' ? `Synthetic callback failure ${index + 1}` : null, + comparable, + diagnostic: + status === 'missing' + ? 'Expected child run is missing' + : status === 'completed' && !comparable + ? 'Retained summary provenance mismatch' + : null, + metrics: comparable + ? { + ...metrics(), + totalReturn: index % 9 === 0 ? 0 : index / 1000, + maxDrawdown: index % 9 === 0 ? 0 : 0.125, + sharpeRatio: index % 9 === 0 ? null : 1.25, + } + : null, + unavailable: comparable + ? index % 9 === 0 + ? { sharpeRatio: 'insufficient-periods' } + : {} + : null, + limitations: [`Synthetic trial ${index + 1}; not measured trading performance`], + }; + }); + const statuses = ['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'] as const; + return { + kind: cost ? 'cost-sensitivity' : 'parameters', + id: cost ? otherExperimentId : experimentId, + name: retained.input.name, + backtestId: retained.input.backtestId, + createdAt: '2026-10-24T14:00:00Z', + cancelRequested: false, + standalone: true, + trialCount: count, + counts: Object.fromEntries( + statuses.map(status => [status, trials.filter(trial => trial.status === status).length]) + ) as WorkbenchExperimentDetail['counts'], + datasetHash: retained.request.datasetHash, + strategyVersionId: versionId, + previewHash: retained.previewHash, + preview: retained, + trials, + } as WorkbenchExperimentDetail; +} + +export function comparisonFixture(referenceIndex = 0): ExperimentComparison { + const left = tableFixture(100), + right = tableFixture(100, true), + reference = left.trials[referenceIndex]; + assert(reference, 'Reference index must exist'); + return { + version: 'experiment-comparison/v1', + policy: 'retained-input-compatibility/v1', + selection: { leftId: left.id, rightId: right.id, referenceTrialKey: reference.trialKey }, + reference: { + experimentId: left.id, + trialKey: reference.trialKey, + index: reference.index, + runId: reference.runId, + summaryAvailable: reference.comparable, + diagnostic: reference.diagnostic, + }, + experiments: [left, right], + rows: [left, right].flatMap(experiment => + experiment.trials.map(trial => { + const match = experiment.id === left.id || trial.index === 0; + return { + experimentId: experiment.id, + trialKey: trial.trialKey, + inputCompatibility: match ? 'match' : 'mismatch', + differences: match ? [] : ['costs'], + summaryAvailable: trial.comparable, + ready: match && trial.comparable && reference.comparable, + }; + }) + ), + limitations: [scope], + }; +} + +/** Visible generation marker prevents a refresh from being timed against previous rows. */ +export function withResponseRevision( + value: WorkbenchExperimentDetail | ExperimentComparison, + revision: number +): WorkbenchExperimentDetail | ExperimentComparison { + assert(Number.isSafeInteger(revision) && revision > 0); + const result = structuredClone(value); + const experiments = 'experiments' in result ? result.experiments : [result]; + for (const experiment of experiments) { + const trial = experiment.trials.at(-1); + assert(trial); + trial.limitations = [ + ...trial.limitations.filter(text => !text.startsWith('Synthetic response revision ')), + `Synthetic response revision ${revision}`, + ]; + } + return result; +} + +/** Fails if the compact payload acquires a full-result field; no HTTP result endpoint exists here. */ +export function assertCompact(value: unknown): void { + if (Array.isArray(value)) { + value.forEach(assertCompact); + } else if (value !== null && typeof value === 'object') { + for (const [key, item] of Object.entries(value)) { + assert( + !['financial', 'trades', 'ohlcData', 'equity', 'fills', 'trace', 'returns'].includes(key), + `Full result field: ${key}` + ); + assertCompact(item); + } + } +} +export function parseArguments(args: string[]) { + let measure = false, + selfTest = false, + samples: number | undefined; + for (const arg of args) { + if (arg === '--measure' && !measure) { + measure = true; + } else if (arg === '--self-test' && !selfTest) { + selfTest = true; + } else if (/^--samples=[1-9]\d*$/.test(arg) && samples === undefined) { + samples = Number(arg.slice(10)); + } else { + throw new Error(`Unknown or repeated argument: ${arg}`); + } + } + assert(!(measure && selfTest), 'Choose --measure or --self-test'); + samples ??= measure ? 5 : 1; + assert( + Number.isSafeInteger(samples) && samples <= 100 && (!measure || samples >= 3), + 'Measurement uses 3–100 samples; smoke uses 1–100' + ); + return { measure, samples }; +} +export function summarize(values: number[]) { + assert( + values.length && values.every(value => Number.isFinite(value) && value >= 0), + 'Missing or invalid samples' + ); + const sorted = [...values].sort((a, b) => a - b), + mid = Math.floor(sorted.length / 2); + return { + count: sorted.length, + min: sorted[0], + median: sorted.length % 2 ? sorted[mid] : ((sorted[mid - 1] ?? 0) + (sorted[mid] ?? 0)) / 2, + max: sorted.at(-1), + p95: sorted.length >= 20 ? sorted[Math.ceil(sorted.length * 0.95) - 1] : null, + }; +} + +type BrowserTiming = { + sequence: number; + actionStart: number; + fetchStart: number; + jsonResolved: number; + readyAt: number; + url: string; +}; +type ProbeWindow = Window & { tableProbe: { records: BrowserTiming[]; errors: string[] } }; +/** Instrument browser-local fetch/body/readiness, not Playwright round-trip latency. */ +function installProbe({ comparison, count }: { comparison: boolean; count: number }) { + const state = { records: [] as BrowserTiming[], errors: [] as string[] }; + (window as unknown as ProbeWindow).tableProbe = state; + const label = comparison ? 'Refresh comparison' : 'Refresh experiment'; + let actionStart = 0; + document.addEventListener( + 'click', + event => { + const target = event.target as Element | null; + if (target?.closest('button')?.textContent?.trim() === label) { + actionStart = performance.now(); + } + }, + true + ); + document.addEventListener( + 'change', + event => { + if ((event.target as Element | null)?.getAttribute('aria-label') === 'Reference trial') { + actionStart = performance.now(); + } + }, + true + ); + const original = window.fetch.bind(window); + const instrumentedFetch = async (...args: Parameters) => { + const url = String(args[0]); + if (!url.includes('/api/v2/experiments/')) { + return original(...args); + } + const sample: BrowserTiming = { + sequence: state.records.length + 1, + actionStart, + fetchStart: performance.now(), + jsonResolved: 0, + readyAt: 0, + url, + }; + state.records.push(sample); + const response = await original(...args), + json = response.json.bind(response); + response.json = async () => { + const body: unknown = await json(); + sample.jsonResolved = performance.now(); + const envelope = body as { + experiment?: WorkbenchExperimentDetail; + comparison?: ExperimentComparison; + }; + const experiments = + envelope.comparison?.experiments ?? (envelope.experiment ? [envelope.experiment] : []); + const markers = experiments.map(experiment => experiment.trials.at(-1)?.limitations.at(-1)); + const ready = () => { + const button = [...document.querySelectorAll('button')].find( + item => item.textContent?.trim() === label + ); + const selectors = comparison + ? ['Left experiment outcomes', 'Right experiment outcomes'] + : ['Experiment trial outcomes']; + const expectedKey = new URL(sample.url).searchParams.get('referenceTrialKey'); + return ( + !!button && + !button.disabled && + markers.length === selectors.length && + selectors.every((name, index) => { + const rows = document.querySelectorAll( + `section[aria-label="${name}"] > div > table > tbody > tr` + ); + const marker = markers[index]; + return ( + rows.length === count && + !!marker && + marker.startsWith('Synthetic response revision ') && + !!rows[rows.length - 1]?.textContent?.includes(marker) + ); + }) && + (!expectedKey || + document.querySelector('select[aria-label="Reference trial"]') + ?.value === expectedKey) && + !document.querySelector('[role="alert"]') + ); + }; + const check = () => { + if (performance.now() - sample.jsonResolved > 30000) { + state.errors.push(`UI readiness timed out: ${document.body.innerText.slice(-3000)}`); + } else if (ready()) { + requestAnimationFrame(() => { + if (ready()) { + sample.readyAt = performance.now(); + } else { + requestAnimationFrame(check); + } + }); + } else { + requestAnimationFrame(check); + } + }; + requestAnimationFrame(check); + return body; + }; + return response; + }; + Object.defineProperty(window, 'fetch', { + configurable: true, + writable: true, + value: instrumentedFetch, + }); +} + +const metricLabel = ( + trial: ExperimentTrial, + key: 'totalReturn' | 'maxDrawdown' | 'sharpeRatio' +) => { + const value = trial.metrics?.[key]; + return value === null || value === undefined + ? `Unavailable${trial.unavailable?.[key] ? `: ${trial.unavailable[key]}` : ''}` + : String(value); +}; +type RowSnapshot = { + cells: (string | undefined)[]; + parameters: string | null | undefined; + links: { text: string | null; href: string | null }[]; +}; +/** Every row checked after timing capture, including offscreen rows. No row sampling. */ +async function verifyPage(page: Page, value: WorkbenchExperimentDetail | ExperimentComparison) { + const comparison = 'experiments' in value; + const experiments = comparison ? value.experiments : [value]; + const snapshot = await page.evaluate(() => ({ + body: document.body.innerText, + sections: [...document.querySelectorAll('section[aria-label$="outcomes"]')].map(section => ({ + label: section.getAttribute('aria-label'), + text: section.textContent, + rows: [...section.querySelectorAll(':scope > div > table > tbody > tr')].map(row => ({ + cells: [...row.querySelectorAll('td')].map(cell => cell.textContent?.trim()), + parameters: row.querySelector('pre')?.textContent, + links: [...row.querySelectorAll('a')].map(link => ({ + text: link.textContent, + href: link.getAttribute('href'), + })), + })), + })), + })); + assert.equal(snapshot.sections.length, experiments.length); + for (const [side, experiment] of experiments.entries()) { + const section = snapshot.sections[side]; + assert(section); + assert.equal(section.rows.length, experiment.trialCount); + const counts = `${experiment.trialCount} trials · ${Object.entries(experiment.counts) + .map(([status, count]) => `${status}: ${count}`) + .join( + ' · ' + )} · missing: ${experiment.trials.filter(trial => trial.status === 'missing').length}`; + assert( + (comparison ? section.text : snapshot.body)?.includes(counts), + `Missing count summary: ${counts}` + ); + for (const [index, trial] of experiment.trials.entries()) { + const row: RowSnapshot | undefined = section.rows[index]; + assert(row); + assert.deepEqual(JSON.parse(row.parameters ?? ''), trial.parameters); + assert(row.cells[1]?.startsWith(trial.status)); + const offset = comparison ? 5 : 3; + for (const [i, key] of (['totalReturn', 'maxDrawdown', 'sharpeRatio'] as const).entries()) { + assert.equal(row.cells[offset + i], metricLabel(trial, key)); + } + for (const text of [trial.error, trial.diagnostic, ...trial.limitations].filter(Boolean)) { + assert(row.cells.at(-1)?.includes(String(text))); + } + const link = row.links.filter(item => item.text?.startsWith('Open ')); + assert.deepEqual( + link, + trial.runId + ? [ + { + text: `Open ${comparison ? `${side === 0 ? 'left' : 'right'} ` : ''}trial ${index + 1} run`, + href: `/backtests/${experiment.backtestId}/run/${trial.runId}`, + }, + ] + : [] + ); + if (comparison) { + const expected = value.rows[side * experiment.trialCount + index]; + assert(expected); + assert( + row.cells[3]?.startsWith( + expected.inputCompatibility === 'match' ? 'Matching settings' : 'Settings differ' + ) + ); + assert( + row.cells[4]?.includes( + expected.ready + ? 'Matching settings and both saved summaries available' + : 'Comparison evidence not ready' + ) + ); + assert.equal(row.cells[4]?.startsWith('Saved summary available'), trial.comparable); + const costs = ( + trial as ExperimentTrial & { costs?: { feeRate: string; slippageRate: string } } + ).costs ?? { + feeRate: experiment.preview.request.policy.matching.risk.feeRate, + slippageRate: experiment.preview.request.policy.matching.slippageRate, + }; + assert.equal( + row.cells[2], + `Fee: ${costs.feeRate}Half-spread: ${experiment.preview.request.policy.matching.halfSpreadRate}Slippage: ${costs.slippageRate}` + ); + } else { + assert.equal( + row.cells[2], + trial.comparable + ? 'Comparable' + : trial.status === 'completed' + ? 'Incomparable' + : 'Not evaluated' + ); + } + } + } +} + +async function collectTiming(page: Page, sequence: number) { + await page.waitForFunction( + expected => { + const state = (window as unknown as ProbeWindow).tableProbe; + if (state.errors.length) { + throw new Error(state.errors.join('\n')); + } + return !!state.records[expected - 1]?.readyAt; + }, + sequence, + { timeout: 35000 } + ); + const raw = await page.evaluate( + expected => (window as unknown as ProbeWindow).tableProbe.records[expected - 1], + sequence + ); + assert(raw); + return { + raw, + durationsMs: { + actionToReady: raw.readyAt - raw.actionStart, + fetchAndJson: raw.jsonResolved - raw.fetchStart, + jsonToTwoFrameReady: raw.readyAt - raw.jsonResolved, + }, + }; +} +function fileIdentities(directory: string): { path: string; bytes: number; sha256: string }[] { + return readdirSync(directory, { withFileTypes: true }) + .flatMap(entry => { + const path = join(directory, entry.name); + if (entry.isDirectory()) { + return fileIdentities(path); + } + const bytes = readFileSync(path); + return [{ path: relative(root, path), bytes: bytes.length, sha256: sha256(bytes) }]; + }) + .sort((a, b) => a.path.localeCompare(b.path)); +} +async function command(args: string[]) { + const proc = Bun.spawn(args, { + cwd: root, + env: { ...process.env, NODE_ENV: 'production', VITE_API_BASE_URL: '' }, + stdout: 'pipe', + stderr: 'pipe', + }); + const [out, err, exit] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + proc.exited, + ]); + assert.equal(exit, 0, `${args.join(' ')}\n${out}\n${err}`); + return { out, err }; +} + +type RequestRecord = { method: string; path: string; bytes: number; sha256: string }; +type TimingResult = Awaited>; +type ReferenceTiming = TimingResult & { + referenceIndex: number; + referenceSummaryAvailable: boolean; +}; +type Sample = { + workload: string; + repeat: number; + fixture: { bytes: number; sha256: string }; + cold: TimingResult; + warmupExcluded: TimingResult; + refresh: TimingResult; + referenceChanges: ReferenceTiming[]; + apiRequests: RequestRecord[]; +}; +export async function main(args: string[]) { + const options = parseArguments(args), + startedAt = new Date().toISOString(), + initialLoad = loadavg(); + const buildStart = performance.now(), + build = await command([process.execPath, 'run', '--cwd', 'apps/stock/web-app', 'build']); + process.stderr.write(build.out + build.err); + const buildMs = performance.now() - buildStart, + dist = join(root, 'apps/stock/web-app/dist'); + let active: WorkbenchExperimentDetail | ExperimentComparison = tableFixture(1), + responseRevision = 0; + const requests: RequestRecord[] = [], + unexpected: string[] = [], + blockedFonts = new Set(); + const server = Bun.serve({ + hostname: '127.0.0.1', + port: 0, + async fetch(request) { + const url = new URL(request.url); + if (url.pathname.startsWith('/api/')) { + let body: unknown; + if (request.method === 'GET' && url.pathname === '/api/auth/session') { + body = { authenticated: true, role: 'admin' }; + } else if ( + request.method === 'GET' && + url.pathname === '/api/v2/experiments/compare' && + 'experiments' in active + ) { + assert.equal(url.searchParams.get('leftId'), experimentId); + assert.equal(url.searchParams.get('rightId'), otherExperimentId); + const key = url.searchParams.get('referenceTrialKey'), + index = key + ? active.experiments[0].trials.findIndex(trial => trial.trialKey === key) + : 0; + active = comparisonFixture(index); + body = { comparison: active }; + } else if ( + request.method === 'GET' && + !('experiments' in active) && + url.pathname === `/api/v2/experiments/${active.id}` && + !url.search + ) { + body = { experiment: active }; + } else { + unexpected.push(`${request.method} ${url.pathname}${url.search}`); + return new Response('Unexpected API request', { status: 403 }); + } + if (url.pathname.startsWith('/api/v2/experiments/')) { + active = withResponseRevision(active, ++responseRevision); + body = 'experiments' in active ? { comparison: active } : { experiment: active }; + } + assertCompact(body); + const serialized = JSON.stringify(body); + requests.push({ + method: request.method, + path: url.pathname + url.search, + bytes: Buffer.byteLength(serialized), + sha256: sha256(serialized), + }); + return new Response(serialized, { + headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, + }); + } + const path = resolve(dist, `.${decodeURIComponent(url.pathname)}`); + if (request.method !== 'GET' || !path.startsWith(dist + sep)) { + return new Response('Not found', { status: 404 }); + } + const file = Bun.file(path); + return new Response((await file.exists()) ? file : Bun.file(join(dist, 'index.html'))); + }, + }); + const origin = `http://127.0.0.1:${server.port}`; + const samples: Sample[] = []; + let browser: Browser | undefined, + browserVersion = '', + browserLaunchMs = 0; + try { + const launchStart = performance.now(); + // Bun 1.2.17/Playwright loses its control pipe after repeated launches: use the existing E2E lifecycle. + browser = await chromium.launch({ headless: true }); + browserLaunchMs = performance.now() - launchStart; + browserVersion = browser.version(); + for (const workload of options.measure + ? ([1, 25, 100, 'comparison'] as const) + : ([1] as const)) { + const comparison = workload === 'comparison', + count = comparison ? 100 : workload; + for (let repeat = 0; repeat < options.samples; repeat++) { + active = comparison ? comparisonFixture() : tableFixture(count); + const payload = JSON.stringify(active), + requestStart = requests.length; + responseRevision = 0; + const context = await browser.newContext({ + viewport: { width: 1440, height: 1080 }, + deviceScaleFactor: 1, + serviceWorkers: 'block', + }); + try { + await context.route('**/*', route => { + if (new URL(route.request().url()).origin !== origin) { + if (new URL(route.request().url()).hostname === 'fonts.googleapis.com') { + blockedFonts.add(route.request().url()); + } else { + unexpected.push(route.request().url()); + } + return route.abort(); + } + return route.continue(); + }); + const page = await context.newPage(), + errors: string[] = []; + page.on('pageerror', error => errors.push(error.message)); + await page.addInitScript(installProbe, { comparison, count }); + const path = comparison + ? `/experiments/compare?leftId=${experimentId}&rightId=${otherExperimentId}` + : `/experiments/${experimentId}`; + await page.goto(origin + path); + const cold = await collectTiming(page, 1); + await verifyPage(page, active); + const button = page.getByRole('button', { + name: comparison ? 'Refresh comparison' : 'Refresh experiment', + exact: true, + }); + await button.click(); + const warmup = await collectTiming(page, 2); + await verifyPage(page, active); + await button.click(); + const refresh = await collectTiming(page, 3); + await verifyPage(page, active); + const referenceChanges: ReferenceTiming[] = []; + if (comparison) { + for (const [i, referenceIndex] of [3, 1].entries()) { + const reference = comparisonFixture(referenceIndex).reference; + await page + .getByLabel('Reference trial', { exact: true }) + .selectOption(reference.trialKey); + const timing = await collectTiming(page, 4 + i); + await verifyPage(page, active); + referenceChanges.push({ + referenceIndex, + referenceSummaryAvailable: reference.summaryAvailable, + ...timing, + }); + } + } + assert.deepEqual(errors, []); + assert.deepEqual(unexpected, []); + const apiRequests = requests.slice(requestStart); + assert.equal( + apiRequests.filter(request => request.path.startsWith('/api/v2/experiments/')).length, + comparison ? 5 : 3 + ); + samples.push({ + workload: comparison ? 'comparison-100+100' : `detail-${count}`, + repeat, + fixture: { bytes: Buffer.byteLength(payload), sha256: sha256(payload) }, + cold, + warmupExcluded: warmup, + refresh, + referenceChanges, + apiRequests, + }); + process.stderr.write( + `${comparison ? 'comparison-100+100' : `detail-${count}`} sample ${repeat + 1}/${options.samples}: verified\n` + ); + } finally { + await context.close(); + } + } + } + } finally { + try { + await browser?.close(); + } finally { + await server.stop(true); + } + } + const sourceFiles = [ + 'scripts/benchmark-experiment-tables.ts', + 'scripts/test/benchmark-experiment-tables.test.ts', + 'test/fixtures/native-replay.ts', + ]; + const source = { + commit: (await command(['git', 'rev-parse', 'HEAD'])).out.trim(), + status: (await command(['git', 'status', '--porcelain'])).out, + files: sourceFiles.map(path => ({ path, sha256: sha256(readFileSync(join(root, path))) })), + }; + const assets = fileIdentities(dist), + host = { + platform: process.platform, + arch: process.arch, + osRelease: release(), + cpu: cpus()[0]?.model, + cpus: cpus().length, + availableParallelism: availableParallelism(), + totalMemoryBytes: totalmem(), + loadBefore: initialLoad, + loadAfter: loadavg(), + }; + const groups = [...new Set(samples.map(sample => sample.workload))].map(workload => { + const group = samples.filter(sample => sample.workload === workload); + return { + workload, + coldActionToReadyMs: summarize(group.map(sample => sample.cold.durationsMs.actionToReady)), + warmRefreshMs: summarize(group.map(sample => sample.refresh.durationsMs.actionToReady)), + warmJsonToReadyMs: summarize( + group.map(sample => sample.refresh.durationsMs.jsonToTwoFrameReady) + ), + referenceChanges: [3, 1].flatMap(referenceIndex => { + const values = group.flatMap(sample => + sample.referenceChanges + .filter(change => change.referenceIndex === referenceIndex) + .map(change => change.durationsMs.actionToReady) + ); + return values.length ? [{ referenceIndex, actionToReadyMs: summarize(values) }] : []; + }), + }; + }); + return { + version: 'experiment-table-ui-benchmark/v1', + scope, + startedAt, + completedAt: new Date().toISOString(), + options, + source, + host, + runtime: { + bun: Bun.version, + browser: browserVersion, + browserLaunchMs, + viewport: { width: 1440, height: 1080 }, + deviceScaleFactor: 1, + }, + build: { + mode: 'production', + durationMs: buildMs, + assets, + sha256: sha256(JSON.stringify(assets)), + }, + measurement: { + cold: 'Fresh context/page in one Chromium process, navigation epoch to two-frame readiness; browser launch measured once separately. Browser process and OS/disk caches are not reset.', + warm: 'Same page, after one excluded refresh; reference changes exercise route remounts without browser restart.', + readiness: + 'Browser-local action/fetch/JSON timestamps then two requestAnimationFrame callbacks with full row count, new response revision on final row, and enabled refresh control; proxy for visible readiness, not exact paint or React CPU time.', + network: + 'Loopback synthetic compact DTO responses; browser routing disables HTTP cache. No database/native/queue measurements.', + p95: 'Only reported with at least 20 samples; five samples cannot establish tail latency.', + limits: + 'External Google Fonts blocked; fallback system fonts used. No memory, scrolling/input latency, real-network, retained artifact-size distribution, server storage or financial throughput claim. All rows are checked after timing.', + }, + blockedExternalFonts: [...blockedFonts], + summary: groups, + samples, + }; +} +if (import.meta.main) { + main(process.argv.slice(2)) + .then(report => process.stdout.write(JSON.stringify(report, null, 2) + '\n')) + .catch(cause => { + process.stderr.write(String(cause?.stack ?? cause) + '\n'); + process.exitCode = 1; + }); +} diff --git a/scripts/test/benchmark-experiment-tables.test.ts b/scripts/test/benchmark-experiment-tables.test.ts new file mode 100644 index 00000000..b25205fd --- /dev/null +++ b/scripts/test/benchmark-experiment-tables.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, test } from 'bun:test'; +import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research'; +import { costSensitivityInputSchema } from '@stock-bot/stock-config/cost-sensitivity'; +import { experimentInputSchema } from '@stock-bot/stock-config/experiments'; +import { + assertCompact, + comparisonFixture, + parseArguments, + scope, + summarize, + tableFixture, + withResponseRevision, +} from '../benchmark-experiment-tables'; + +describe('production experiment table measurement', () => { + test('bounded explicit workloads; smoke cannot be mistaken for measured trial set', () => { + expect(parseArguments([])).toEqual({ measure: false, samples: 1 }); + expect(parseArguments(['--self-test'])).toEqual({ measure: false, samples: 1 }); + expect(parseArguments(['--measure'])).toEqual({ measure: true, samples: 5 }); + expect(parseArguments(['--samples=20', '--measure'])).toEqual({ measure: true, samples: 20 }); + for (const args of [ + ['--measure', '--samples=1'], + ['--samples=101'], + ['--samples=0'], + ['--measure', '--self-test'], + ['--measure', '--measure'], + ['--samples=3', '--samples=3'], + ['--unknown'], + ]) { + expect(() => parseArguments(args)).toThrow(); + } + for (const count of [0, 101, 1.5, Infinity]) { + expect(() => tableFixture(count)).toThrow(); + } + expect(scope).toContain('no engine, database, queue, financial correctness'); + }); + test.each([1, 25, 100])( + '%i rows preserve candidate order, source identity and every compact outcome', + count => { + const detail = tableFixture(count); + expect(detail).toEqual(tableFixture(count)); + expect(detail.trialCount).toBe(count); + expect(detail.trials).toHaveLength(count); + expect(detail.preview.candidates).toHaveLength(count); + expect(canonicalRunRequestSchema.safeParse(detail.preview.request).success).toBe(true); + expect(experimentInputSchema.safeParse(detail.preview.input).success).toBe(true); + expect(() => assertCompact(detail)).not.toThrow(); + expect(new Set(detail.trials.map(trial => trial.trialKey)).size).toBe(count); + expect(detail.trials.map(trial => trial.index)).toEqual( + Array.from({ length: count }, (_, i) => i) + ); + expect( + Object.values(detail.counts).reduce((sum, value) => sum + value, 0) + + detail.trials.filter(trial => trial.status === 'missing').length + ).toBe(count); + for (const [index, trial] of detail.trials.entries()) { + expect(detail.preview.candidates[index]?.parameters).toEqual(trial.parameters); + expect(detail.preview.candidates[index]?.trialKey).toBe(trial.trialKey); + expect(trial.status === 'missing').toBe(trial.runId === null); + } + expect(detail.trials[0]?.metrics?.totalReturn).toBe(0); + expect(detail.trials[0]?.metrics?.sharpeRatio).toBeNull(); + expect(detail.trials[0]?.unavailable?.sharpeRatio).toBe('insufficient-periods'); + if (count > 1) { + expect(new Set(detail.trials.map(trial => trial.status))).toEqual( + new Set(['completed', 'failed', 'pending', 'running', 'paused', 'cancelled', 'missing']) + ); + expect(detail.trials[1]?.metrics?.sharpeRatio).toBe(1.25); + expect(detail.trials[2]?.status).toBe('completed'); + expect(detail.trials[2]?.comparable).toBe(false); + expect(detail.trials[2]?.metrics).toBeNull(); + expect(detail.trials[3]?.error).toContain('callback failure'); + } + } + ); + test('comparison is all 200 rows, cost scenarios keep parameters fixed and settings/summary states separate', () => { + const value = comparisonFixture(), + [left, right] = value.experiments; + expect(value.rows).toHaveLength(200); + expect(value.rows.filter(row => row.inputCompatibility === 'match')).toHaveLength(101); + expect(value.rows.filter(row => row.inputCompatibility === 'mismatch')).toHaveLength(99); + expect(value.rows.filter(row => row.summaryAvailable)).toHaveLength(46); + expect(value.rows.filter(row => row.ready)).toHaveLength(24); + expect(value.rows.map(row => row.trialKey)).toEqual( + [...left.trials, ...right.trials].map(trial => trial.trialKey) + ); + expect(right.preview.version).toBe('cost-sensitivity-preview/v1'); + expect(costSensitivityInputSchema.safeParse(right.preview.input).success).toBe(true); + expect(new Set(right.trials.map(trial => JSON.stringify(trial.parameters))).size).toBe(1); + expect( + new Set( + [...left.trials, ...right.trials].flatMap(trial => (trial.runId ? [trial.runId] : [])) + ).size + ).toBe(178); + expect(() => assertCompact(value)).not.toThrow(); + const failed = comparisonFixture(3), + missing = comparisonFixture(8); + for (const unavailable of [failed, missing]) { + expect(unavailable.reference.summaryAvailable).toBe(false); + expect(unavailable.rows.some(row => row.ready)).toBe(false); + expect(unavailable.rows.filter(row => row.summaryAvailable)).toHaveLength(46); + expect(unavailable.rows).toHaveLength(200); + } + expect(missing.reference.runId).toBeNull(); + expect(comparisonFixture(1).reference.index).toBe(1); + expect(() => comparisonFixture(100)).toThrow(); + }); + test('refresh marker changes visible final rows without altering retained inputs or economic summaries', () => { + for (const original of [tableFixture(100), comparisonFixture()]) { + const first = withResponseRevision(original, 1), + second = withResponseRevision(first, 2); + const experiments = 'experiments' in second ? second.experiments : [second]; + const before = 'experiments' in original ? original.experiments : [original]; + for (const [index, experiment] of experiments.entries()) { + expect(before[index]?.preview).toEqual(experiment.preview); + expect(before[index]?.trials.map(trial => trial.metrics)).toEqual( + experiment.trials.map(trial => trial.metrics) + ); + expect( + experiment.trials + .at(-1) + ?.limitations.filter(text => text.startsWith('Synthetic response revision ')) + ).toEqual(['Synthetic response revision 2']); + } + expect(JSON.stringify(original)).not.toContain('Synthetic response revision'); + expect(JSON.stringify(first)).toContain('Synthetic response revision 1'); + } + }); + test('full result blobs anywhere in an envelope are rejected', () => { + for (const field of [ + 'financial', + 'trades', + 'ohlcData', + 'equity', + 'fills', + 'trace', + 'returns', + ]) { + expect(() => assertCompact({ comparison: { experiments: [{ [field]: [] }] } })).toThrow( + 'Full result' + ); + } + }); + test('raw samples remain unmodified, median is defined and small samples make no tail claim', () => { + const values = [10, 1, 3, 2]; + expect(summarize(values)).toEqual({ count: 4, min: 1, median: 2.5, max: 10, p95: null }); + expect(values).toEqual([10, 1, 3, 2]); + expect(summarize([3, 1, 2]).median).toBe(2); + expect(summarize(Array.from({ length: 20 }, (_, i) => i + 1)).p95).toBe(19); + for (const invalid of [[], [NaN], [Infinity], [-1]]) { + expect(() => summarize(invalid)).toThrow(); + } + }); +});