From b4ac6460efd40734f55d12bc94f1969583fd8587 Mon Sep 17 00:00:00 2001 From: Boki Date: Mon, 26 Oct 2026 23:57:39 -0400 Subject: [PATCH] fix(core): own cache transports and accept cleanup reviews --- docs/development/CLEANUP.md | 2 + docs/development/backlog/README.md | 35 ++-- docs/development/backlog/manifest.json | 181 +++++++++++++----- docs/development/backlog/tasks/RP01.md | 17 ++ docs/development/backlog/tasks/RP02.md | 15 ++ docs/development/cleanup-execution.md | 2 + docs/development/cleanup-review.md | 2 + docs/development/real-data-research.md | 17 ++ docs/guide/system-map.md | 12 ++ libs/core/cache/src/connection-manager.ts | 2 + libs/core/cache/src/redis-cache.ts | 12 ++ libs/core/cache/src/types.ts | 4 + .../config/src/schemas/database.schema.ts | 18 +- libs/core/di/src/container/types.ts | 1 + .../src/registrations/cache.registration.ts | 23 ++- .../registrations/database.registration.ts | 10 + .../src/registrations/service.registration.ts | 22 ++- libs/core/di/src/utils/lifecycle.ts | 2 + libs/core/queue/src/queue-manager.ts | 7 +- libs/core/queue/src/service-cache.ts | 13 +- libs/core/queue/src/types.ts | 2 + libs/core/queue/src/utils.ts | 2 +- test/integration/cache-ownership.test.ts | 130 +++++++++++++ test/integration/store-configuration.test.ts | 70 ++++++- 24 files changed, 504 insertions(+), 97 deletions(-) create mode 100644 docs/development/backlog/tasks/RP01.md create mode 100644 docs/development/backlog/tasks/RP02.md create mode 100644 docs/development/real-data-research.md create mode 100644 test/integration/cache-ownership.test.ts diff --git a/docs/development/CLEANUP.md b/docs/development/CLEANUP.md index 6f85285b..c6c16fb3 100644 --- a/docs/development/CLEANUP.md +++ b/docs/development/CLEANUP.md @@ -1,5 +1,7 @@ # Cleanup and maintainability plan +Current acceptance: all 13 cleanup stories received independent review; the resulting cache/configuration corrections and check evidence are recorded in [real-data-research.md](real-data-research.md). Earlier review-pending statements below describe the historical execution state. + Baseline: `fbf2eb9e`, inspected October 26, 2026. This extends the existing development backlog. The original 45 scheduled tasks remain complete; these 13 cleanup stories are new work. The owner subsequently authorized implementation and validated commits; progress and checks are recorded in [cleanup-execution.md](cleanup-execution.md). All 13 stories are implemented and validated. They remain in `review` until an independent reviewer signs off; no additional agents have been launched. [manifest.json](backlog/manifest.json) remains the scheduling source of truth. It records task states, prerequisites, priorities and write locks. This page explains the execution contract and recommended order; it is not a second status tracker. Current evidence is appended to [findings.md](backlog/findings.md#cleanup-audit-2026-10-26). diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index 7ddeae95..2d7f1802 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -2,13 +2,13 @@ **The original 45/45 scheduled tasks are complete.** The canonical Rust engine, TypeScript research/workbench, bounded worker pool, isolated candidates, AI evidence workflow and human-reviewed paper promotion are validated. Implementation commits: `bbf0dd4`, `26b9726`, `25b5cbf` (R07 measurement `ab08db8`). Six conditional tasks remain deferred; four merged IDs remain redirects. This is scheduled-backlog completion, not live-trading activation. -**New work:** [13 cleanup stories](../CLEANUP.md) were proposed on October 26, 2026. The owner subsequently authorized implementation and commits; see [execution evidence](../cleanup-execution.md). All 13 are implemented and validated; independent review is the remaining completion gate. +**New work:** [13 cleanup stories](../CLEANUP.md) were proposed on October 26, 2026. The owner subsequently authorized implementation and commits; see [execution evidence](../cleanup-execution.md). All 13 are implemented and independently accepted; review corrections are recorded in [real-data-research.md](../real-data-research.md). ## One source of truth [manifest.json](manifest.json) owns scheduling metadata: status, priorities, dependencies, ADR approvals, assignments and write locks. Task Markdown owns implementation scope/evidence/acceptance. This index and the [graph](dependencies.mmd) are derived views. Only the planning/integration owner updates scheduling state. -**Current total: 76 retained IDs.** The earlier 68 IDs retain their state. E11 adds seven authorized cleanup tasks and one conditional replay extraction; see the manifest for current scheduling. The original backlog accounted for 55 IDs. F09/P07 added projection/profiling work; the owner deferred P08's TypeScript optimization. Merged records preserve traceability; never execute them separately. Deferred work requires its stated trigger and explicit activation. +**Current total: 78 retained IDs.** RP01/RP02 add the authorized real-data workflow. The earlier 68 IDs retain their state. E11 adds seven authorized cleanup tasks and one conditional replay extraction; see the manifest for current scheduling. The original backlog accounted for 55 IDs. F09/P07 added projection/profiling work; the owner deferred P08's TypeScript optimization. Merged records preserve traceability; never execute them separately. Deferred work requires its stated trigger and explicit activation. States: ready, claimed, in_progress, review, done, blocked, deferred, merged. “Ready” means no code/ADR prerequisite, not execution authority. Implementation dependencies require accepted integration. `release_gates` govern enabling an end-to-end feature, not component coding or integration; conditional gates apply only to the named capability. F05 may integrate before F06, but its replay behavior is not released until F06 proves it. @@ -122,19 +122,19 @@ Scope and first execution wave: [CLEANUP.md](../CLEANUP.md). The owner has autho | Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size | | --- | --- | --- | --- | --- | -| [CL01 Replace permissive DI configuration tests with production-path assertions](tasks/CL01.md) | P1 / review | None | — | TypeScript infrastructure testing / M | -| [CL02 Normalize database configuration once and enforce consistent service switches](tasks/CL02.md) | P1 / review | CL01 | — | TypeScript configuration and database adapters / M | -| [CL03 Roll back failed shared-service startup and clear initialization timers](tasks/CL03.md) | P1 / review | None | — | TypeScript resource lifecycle and concurrency / M | -| [CL04 Provide one consistent research startup path and repair stale commands](tasks/CL04.md) | P1 / review | None | — | Bun/Turbo developer tooling / S | -| [CL05 Extract shared dataset and reporting logic behind a research library boundary](tasks/CL05.md) | P2 / review | D01, F08, R05 | — | TypeScript domain boundaries and package migration / M | -| [CL06 Use shared dataset response schemas and eligibility checks in the workbench](tasks/CL06.md) | P2 / review | CL05 | — | Shared contracts and frontend validation / M | -| [CL07 Share JSON transport handling across experiment and validation clients](tasks/CL07.md) | P2 / review | None | — | Frontend HTTP contracts and retry semantics / M | -| [CL08 Split backtest template, run and reproduction responsibilities behind the existing service](tasks/CL08.md) | P2 / review | CL05 | — | TypeScript application services and PostgreSQL transactions / M | -| [CL09 Separate strategy metadata, version inspection and publication UI](tasks/CL09.md) | P2 / review | None | — | React strategy workflows / M | -| [CL10 Separate experiment modes and make draft/submission state explicit](tasks/CL10.md) | P2 / review | None | — | React experiment workflow state / M | -| [CL11 Separate backtest template loading, run monitoring and submission state](tasks/CL11.md) | P2 / review | None | — | React asynchronous state and durable-run UX / M | -| [CL12 Simplify retired execution seams while preserving historical reads](tasks/CL12.md) | P2 / review | CL08 | — | Compatibility cleanup and execution boundaries / M | -| [CL13 Hide placeholder navigation while preserving useful product routes](tasks/CL13.md) | P2 / review | None | — | React navigation and product clarity / S | +| [CL01 Replace permissive DI configuration tests with production-path assertions](tasks/CL01.md) | P1 / done | None | — | TypeScript infrastructure testing / M | +| [CL02 Normalize database configuration once and enforce consistent service switches](tasks/CL02.md) | P1 / done | CL01 | — | TypeScript configuration and database adapters / M | +| [CL03 Roll back failed shared-service startup and clear initialization timers](tasks/CL03.md) | P1 / done | None | — | TypeScript resource lifecycle and concurrency / M | +| [CL04 Provide one consistent research startup path and repair stale commands](tasks/CL04.md) | P1 / done | None | — | Bun/Turbo developer tooling / S | +| [CL05 Extract shared dataset and reporting logic behind a research library boundary](tasks/CL05.md) | P2 / done | D01, F08, R05 | — | TypeScript domain boundaries and package migration / M | +| [CL06 Use shared dataset response schemas and eligibility checks in the workbench](tasks/CL06.md) | P2 / done | CL05 | — | Shared contracts and frontend validation / M | +| [CL07 Share JSON transport handling across experiment and validation clients](tasks/CL07.md) | P2 / done | None | — | Frontend HTTP contracts and retry semantics / M | +| [CL08 Split backtest template, run and reproduction responsibilities behind the existing service](tasks/CL08.md) | P2 / done | CL05 | — | TypeScript application services and PostgreSQL transactions / M | +| [CL09 Separate strategy metadata, version inspection and publication UI](tasks/CL09.md) | P2 / done | None | — | React strategy workflows / M | +| [CL10 Separate experiment modes and make draft/submission state explicit](tasks/CL10.md) | P2 / done | None | — | React experiment workflow state / M | +| [CL11 Separate backtest template loading, run monitoring and submission state](tasks/CL11.md) | P2 / done | None | — | React asynchronous state and durable-run UX / M | +| [CL12 Simplify retired execution seams while preserving historical reads](tasks/CL12.md) | P2 / done | CL08 | — | Compatibility cleanup and execution boundaries / M | +| [CL13 Hide placeholder navigation while preserving useful product routes](tasks/CL13.md) | P2 / done | None | — | React navigation and product clarity / S | ## Scheduling checks @@ -156,3 +156,8 @@ Owner authorized planning and per-task implementation commits. [Execution plan a | [CL19 Share pure strategy bookkeeping and event ordering](tasks/CL19.md) | P2 | None | | [CL20 Return validated retained results from the worker supervisor](tasks/CL20.md) | P2 | CL14 | | [CL21 Extract private deterministic replay preparation when needed](tasks/CL21.md) | P3 | Conditional | + +## E12 — Real-data research workflow + +- [RP01: Stored source coverage and quality](tasks/RP01.md) — in progress. +- [RP02: Retained real-data pilot](tasks/RP02.md) — in progress; preserves explicit strategy approval. diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index 5cf6d9d2..b20e2492 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -1,8 +1,8 @@ { "schema_version": 1, - "plan_revision": "2026-10-26.86", + "plan_revision": "2026-10-26.87", "repository_base": "b7aeca4", - "plan_status": "orchestrator_engine_cleanup_scheduled_complete", + "plan_status": "real_data_research_in_progress", "execution_authorized": true, "execution_scope": { "authorized_by": "Owner: commit and continue with the rest of the tasks till 100%", @@ -189,7 +189,8 @@ "id": "E10", "title": "Cleanup and maintainability foundations" }, - {"id": "E11", "title": "Orchestrator and engine cleanup"} + {"id": "E11", "title": "Orchestrator and engine cleanup"}, + {"id": "E12", "title": "Real-data research workflow"} ], "first_wave": ["C01", "C03", "C04", "W01"], "tasks": [ @@ -2115,7 +2116,7 @@ "epic": "E10", "priority": "P1", "severity": "High", - "status": "review", + "status": "done", "dependencies": [], "decision_dependencies": [], "task_file": "backlog/tasks/CL01.md", @@ -2131,10 +2132,10 @@ "assignment": null, "branch": null, "pull_request": null, - "completed_commit": null, + "completed_commit": "8c39ccf7", "blocker": null, "release_gates": [], - "integration_state": "validated_pending_independent_review", + "integration_state": "validated_committed", "integration_base": "fbf2eb9e", "review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.", "concrete_write_scope": [ @@ -2146,7 +2147,9 @@ "implementation_commits": [ "805a9f8f", "8c39ccf7" - ] + ], + "reviewer": "/root/review_cleanup_foundations", + "review_evidence": "real-data-research.md" }, { "id": "CL02", @@ -2154,7 +2157,7 @@ "epic": "E10", "priority": "P1", "severity": "High", - "status": "review", + "status": "done", "dependencies": [ "CL01" ], @@ -2177,7 +2180,7 @@ "completed_commit": null, "blocker": null, "release_gates": [], - "integration_state": "validated_pending_independent_review", + "integration_state": "validated_pending_commit", "integration_base": "fbf2eb9e", "review_notes": "Primary follow-up reproduced and fixed configuration/lifecycle defects; all repository gates pass on 9d3e1a7b. Independent reviewer-agent permission/sign-off is pending; status remains review.", "concrete_write_scope": [ @@ -2198,7 +2201,9 @@ "8c39ccf7", "9d3e1a7b" ], - "review_followup_file": "cleanup-review.md" + "review_followup_file": "cleanup-review.md", + "reviewer": "/root/review_cleanup_foundations", + "review_evidence": "real-data-research.md" }, { "id": "CL03", @@ -2206,7 +2211,7 @@ "epic": "E10", "priority": "P1", "severity": "High", - "status": "review", + "status": "done", "dependencies": [], "decision_dependencies": [], "task_file": "backlog/tasks/CL03.md", @@ -2226,7 +2231,7 @@ "completed_commit": null, "blocker": null, "release_gates": [], - "integration_state": "validated_pending_independent_review", + "integration_state": "validated_pending_commit", "integration_base": "fbf2eb9e", "review_notes": "Primary follow-up reproduced and fixed configuration/lifecycle defects; all repository gates pass on 9d3e1a7b. Independent reviewer-agent permission/sign-off is pending; status remains review.", "concrete_write_scope": [ @@ -2242,7 +2247,9 @@ "8c39ccf7", "9d3e1a7b" ], - "review_followup_file": "cleanup-review.md" + "review_followup_file": "cleanup-review.md", + "reviewer": "/root/review_cleanup_foundations", + "review_evidence": "real-data-research.md" }, { "id": "CL04", @@ -2250,7 +2257,7 @@ "epic": "E10", "priority": "P1", "severity": "Medium", - "status": "review", + "status": "done", "dependencies": [], "decision_dependencies": [], "task_file": "backlog/tasks/CL04.md", @@ -2268,10 +2275,10 @@ "assignment": null, "branch": null, "pull_request": null, - "completed_commit": null, + "completed_commit": "8c39ccf7", "blocker": null, "release_gates": [], - "integration_state": "validated_pending_independent_review", + "integration_state": "validated_committed", "integration_base": "fbf2eb9e", "review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.", "concrete_write_scope": [ @@ -2287,7 +2294,9 @@ "implementation_commits": [ "805a9f8f", "8c39ccf7" - ] + ], + "reviewer": "/root/review_cleanup_foundations", + "review_evidence": "real-data-research.md" }, { "id": "CL05", @@ -2295,7 +2304,7 @@ "epic": "E10", "priority": "P2", "severity": "High", - "status": "review", + "status": "done", "dependencies": [ "D01", "F08", @@ -2321,10 +2330,10 @@ "assignment": null, "branch": null, "pull_request": null, - "completed_commit": null, + "completed_commit": "8c39ccf7", "blocker": null, "release_gates": [], - "integration_state": "validated_pending_independent_review", + "integration_state": "validated_committed", "integration_base": "fbf2eb9e", "review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.", "concrete_write_scope": [ @@ -2347,7 +2356,9 @@ "implementation_commit": "8c39ccf7", "implementation_commits": [ "8c39ccf7" - ] + ], + "reviewer": "/root/review_cleanup_backend", + "review_evidence": "real-data-research.md" }, { "id": "CL06", @@ -2355,7 +2366,7 @@ "epic": "E10", "priority": "P2", "severity": "Medium", - "status": "review", + "status": "done", "dependencies": [ "CL05" ], @@ -2374,10 +2385,10 @@ "assignment": null, "branch": null, "pull_request": null, - "completed_commit": null, + "completed_commit": "8c39ccf7", "blocker": null, "release_gates": [], - "integration_state": "validated_pending_independent_review", + "integration_state": "validated_committed", "integration_base": "fbf2eb9e", "review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.", "concrete_write_scope": [ @@ -2392,7 +2403,9 @@ "implementation_commit": "8c39ccf7", "implementation_commits": [ "8c39ccf7" - ] + ], + "reviewer": "/root/review_cleanup_frontend", + "review_evidence": "real-data-research.md" }, { "id": "CL07", @@ -2400,7 +2413,7 @@ "epic": "E10", "priority": "P2", "severity": "Medium", - "status": "review", + "status": "done", "dependencies": [], "decision_dependencies": [], "task_file": "backlog/tasks/CL07.md", @@ -2416,10 +2429,10 @@ "assignment": null, "branch": null, "pull_request": null, - "completed_commit": null, + "completed_commit": "8c39ccf7", "blocker": null, "release_gates": [], - "integration_state": "validated_pending_independent_review", + "integration_state": "validated_committed", "integration_base": "fbf2eb9e", "review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.", "concrete_write_scope": [ @@ -2434,7 +2447,9 @@ "implementation_commit": "8c39ccf7", "implementation_commits": [ "8c39ccf7" - ] + ], + "reviewer": "/root/review_cleanup_frontend", + "review_evidence": "real-data-research.md" }, { "id": "CL08", @@ -2442,7 +2457,7 @@ "epic": "E10", "priority": "P2", "severity": "Medium", - "status": "review", + "status": "done", "dependencies": [ "CL05" ], @@ -2464,10 +2479,10 @@ "assignment": null, "branch": null, "pull_request": null, - "completed_commit": null, + "completed_commit": "8c39ccf7", "blocker": null, "release_gates": [], - "integration_state": "validated_pending_independent_review", + "integration_state": "validated_committed", "integration_base": "fbf2eb9e", "review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.", "concrete_write_scope": [ @@ -2484,7 +2499,9 @@ "implementation_commit": "8c39ccf7", "implementation_commits": [ "8c39ccf7" - ] + ], + "reviewer": "/root/review_cleanup_backend", + "review_evidence": "real-data-research.md" }, { "id": "CL09", @@ -2492,7 +2509,7 @@ "epic": "E10", "priority": "P2", "severity": "Medium", - "status": "review", + "status": "done", "dependencies": [], "decision_dependencies": [], "task_file": "backlog/tasks/CL09.md", @@ -2508,10 +2525,10 @@ "assignment": null, "branch": null, "pull_request": null, - "completed_commit": null, + "completed_commit": "8c39ccf7", "blocker": null, "release_gates": [], - "integration_state": "validated_pending_independent_review", + "integration_state": "validated_committed", "integration_base": "fbf2eb9e", "review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.", "concrete_write_scope": [ @@ -2526,7 +2543,9 @@ "implementation_commit": "8c39ccf7", "implementation_commits": [ "8c39ccf7" - ] + ], + "reviewer": "/root/review_cleanup_frontend", + "review_evidence": "real-data-research.md" }, { "id": "CL10", @@ -2534,7 +2553,7 @@ "epic": "E10", "priority": "P2", "severity": "Medium", - "status": "review", + "status": "done", "dependencies": [], "decision_dependencies": [], "task_file": "backlog/tasks/CL10.md", @@ -2550,10 +2569,10 @@ "assignment": null, "branch": null, "pull_request": null, - "completed_commit": null, + "completed_commit": "8c39ccf7", "blocker": null, "release_gates": [], - "integration_state": "validated_pending_independent_review", + "integration_state": "validated_committed", "integration_base": "fbf2eb9e", "review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.", "concrete_write_scope": [ @@ -2568,7 +2587,9 @@ "implementation_commit": "8c39ccf7", "implementation_commits": [ "8c39ccf7" - ] + ], + "reviewer": "/root/review_cleanup_frontend", + "review_evidence": "real-data-research.md" }, { "id": "CL11", @@ -2576,7 +2597,7 @@ "epic": "E10", "priority": "P2", "severity": "Medium", - "status": "review", + "status": "done", "dependencies": [], "decision_dependencies": [], "task_file": "backlog/tasks/CL11.md", @@ -2592,10 +2613,10 @@ "assignment": null, "branch": null, "pull_request": null, - "completed_commit": null, + "completed_commit": "8c39ccf7", "blocker": null, "release_gates": [], - "integration_state": "validated_pending_independent_review", + "integration_state": "validated_committed", "integration_base": "fbf2eb9e", "review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.", "concrete_write_scope": [ @@ -2610,7 +2631,9 @@ "implementation_commit": "8c39ccf7", "implementation_commits": [ "8c39ccf7" - ] + ], + "reviewer": "/root/review_cleanup_frontend", + "review_evidence": "real-data-research.md" }, { "id": "CL12", @@ -2618,7 +2641,7 @@ "epic": "E10", "priority": "P2", "severity": "Medium", - "status": "review", + "status": "done", "dependencies": [ "CL08" ], @@ -2639,10 +2662,10 @@ "assignment": null, "branch": null, "pull_request": null, - "completed_commit": null, + "completed_commit": "8c39ccf7", "blocker": null, "release_gates": [], - "integration_state": "validated_pending_independent_review", + "integration_state": "validated_committed", "integration_base": "fbf2eb9e", "review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.", "concrete_write_scope": [ @@ -2657,7 +2680,9 @@ "implementation_commit": "8c39ccf7", "implementation_commits": [ "8c39ccf7" - ] + ], + "reviewer": "/root/review_cleanup_backend", + "review_evidence": "real-data-research.md" }, { "id": "CL13", @@ -2665,7 +2690,7 @@ "epic": "E10", "priority": "P2", "severity": "Low", - "status": "review", + "status": "done", "dependencies": [], "decision_dependencies": [], "task_file": "backlog/tasks/CL13.md", @@ -2681,10 +2706,10 @@ "assignment": null, "branch": null, "pull_request": null, - "completed_commit": null, + "completed_commit": "8c39ccf7", "blocker": null, "release_gates": [], - "integration_state": "validated_pending_independent_review", + "integration_state": "validated_committed", "integration_base": "fbf2eb9e", "review_notes": "Implementation and relevant checks are complete. Separate self-review performed; independent reviewer sign-off remains pending. No reviewer agent was launched.", "concrete_write_scope": [ @@ -2698,7 +2723,9 @@ "implementation_commit": "8c39ccf7", "implementation_commits": [ "8c39ccf7" - ] + ], + "reviewer": "/root/review_cleanup_frontend", + "review_evidence": "real-data-research.md" }, { "id": "CL14", @@ -3054,6 +3081,54 @@ "integration_state": "not_started", "integration_base": "700ee09c", "completion_evidence": "orchestrator-engine-cleanup.md" + }, + { + "id": "RP01", + "title": "Inspect stored market-data coverage and quality", + "epic": "E12", + "priority": "P1", + "severity": "High", + "status": "in_progress", + "dependencies": [ + "CL05", + "CL06", + "CL17" + ], + "decision_dependencies": [], + "task_file": "backlog/tasks/RP01.md", + "complexity": "M", + "assignment": "/root/implement_source_inspection", + "completed_commit": null, + "blocker": null, + "integration_state": "implementing", + "integration_base": "bd9332b2", + "completion_evidence": "real-data-research.md", + "release_gates": [] + }, + { + "id": "RP02", + "title": "Complete a retained real-data research pilot", + "epic": "E12", + "priority": "P1", + "severity": "High", + "status": "in_progress", + "dependencies": [ + "CL02", + "CL03", + "R05", + "R08", + "R12" + ], + "decision_dependencies": [], + "task_file": "backlog/tasks/RP02.md", + "complexity": "M", + "assignment": "/root", + "completed_commit": null, + "blocker": null, + "integration_state": "implementing", + "integration_base": "bd9332b2", + "completion_evidence": "real-data-research.md", + "release_gates": [] } ], "review_note": "Independent skeptical revision: four superseded tasks retain stable IDs; deferred work is not a dependency of scheduled tasks. Release gates are distinct from implementation prerequisites.", diff --git a/docs/development/backlog/tasks/RP01.md b/docs/development/backlog/tasks/RP01.md new file mode 100644 index 00000000..7ee33e60 --- /dev/null +++ b/docs/development/backlog/tasks/RP01.md @@ -0,0 +1,17 @@ +# RP01 — Inspect stored market-data coverage and quality + +Parent: E12. Priority P1. Complexity M. Authorized by the owner's request to implement the real-data research workflow. + +Outcome: the stored-EOD preparation UI shows available instruments/timeframes/date coverage and diagnostics for an explicit UTC window before requiring complete dataset metadata. + +Evidence: `DatasetPreparation.tsx` currently begins with metadata JSON; `prepareStoredDataset` calls the strict historical reader, which rejects an invalid row before returning a preview. The read-only October 26 pilot again found 22 null-volume rows in 1,816 AAPL five-minute records. Quality inspection must not weaken execution admission. + +Scope: browser-safe shared contracts, fixed EOD Mongo collection coverage and window inspection, existing dataset routes, separate stored-mode inspector, focused API/domain/UI regressions. Show unknown identity/timestamps, malformed OHLCV and duplicates truthfully. No implicit filtering, metadata inference, row caps, writes, cache, financial changes or research-agent permission expansion. Existing strict preview/retain remains authoritative. + +Dependencies: accepted CL05/CL06/CL17. Agent lock: stored-source contracts/service/routes/UI and new tests. Can run beside cache corrections and pilot preparation. + +Acceptance: actual stored coverage is inspectable; empty/error/loading/cancel states work; changing input fences late responses; full requested range is diagnosed; no source or research records are written; a clean diagnostic never implies execution eligibility. In-flight Mongo cancellation limitations are explicit. + +Tests: source inspection domain/HTTP and production component tests; existing stored/prepared dataset suites; shared contract/browser bundle tests; read-only actual Mongo smoke; typecheck/lint; repository and browser integration gates. Independent backend and frontend review before completion. + +Risk: falsely claiming complete sessions, losing UTC range identity, stale UI results, or bypassing strict preparation. Root owns manifest status and commit evidence in `real-data-research.md`. diff --git a/docs/development/backlog/tasks/RP02.md b/docs/development/backlog/tasks/RP02.md new file mode 100644 index 00000000..ee46b673 --- /dev/null +++ b/docs/development/backlog/tasks/RP02.md @@ -0,0 +1,15 @@ +# RP02 — Complete a retained real-data research pilot + +Parent: E12. Priority P1. Complexity M. Authorized by the owner's real-data workflow request. This is a bounded workflow proof, not alpha validation or trading activation. + +Outcome: one clean, explicitly declared stored-market window becomes a frozen dataset, a reviewed retained TypeScript baseline runs on Rust, chronological/cost experiments can be reopened, and exact reproduction plus an evidence-linked finding are recorded. + +Scope: use existing preparation, strategy catalog, durable runner, experiments, validation, reproduction and research APIs/services. Preserve raw query bytes, metadata evidence and policies in local durable artifacts; persist research inputs/results through existing custody. Prefer a clean single session over inventing a filtering policy. Only newly created pilot research records may be written; source history and paper/live state remain untouched. No new simulator, model, optimizer, MCP framework, calendar inference or claims of statistical significance. + +Dependencies: reviewed foundations and existing accepted research engine; RP01 supplies inspection but does not block offline metadata preparation. Root owns pilot artifacts and execution. A strategy's explicit operator-review gate remains in effect; prepare its exact artifact before requesting any missing approval. + +Acceptance: recorded source/data/artifact/build identities; no coerced or silently excluded rows; supported calendar/action/universe declarations; deterministic economic equality on reproduction; finite predeclared parameter/cost trials, chronological selection using training only; results/finding reopened through existing product APIs. Record unavailable approval/data/runtime honestly instead of weakening gates. + +Tests: existing durable research/validation/reproduction regression suites on disposable stores, pilot assertions using real stored input, relevant browser workflow, full repository gate. A one-session result must be labelled workflow-only and cannot establish profitability or universe robustness. + +Risk: mislabelled source availability, retrospective universe assumptions, incomplete approvals, non-idempotent metadata writes or accidental repeated experiments. Keep an append-only local intent/receipt record and resume by saved IDs. Root records final evidence in `real-data-research.md` and canonical manifest. diff --git a/docs/development/cleanup-execution.md b/docs/development/cleanup-execution.md index 50d57560..2a482b91 100644 --- a/docs/development/cleanup-execution.md +++ b/docs/development/cleanup-execution.md @@ -1,5 +1,7 @@ # Cleanup execution evidence +Current acceptance: all 13 cleanup stories received independent review; the resulting cache/configuration corrections and check evidence are recorded in [real-data-research.md](real-data-research.md). Earlier review-pending statements below describe the historical execution state. + The owner authorized implementation and validated commits after plan commit `4ddffa6b`. The [manifest](backlog/manifest.json) remains the task-state authority. No additional agents were launched; review here is a separate self-review pass, not an independent diff --git a/docs/development/cleanup-review.md b/docs/development/cleanup-review.md index b2f37d15..da518737 100644 --- a/docs/development/cleanup-review.md +++ b/docs/development/cleanup-review.md @@ -1,5 +1,7 @@ # Cleanup review and first research pilot +Current acceptance: all 13 cleanup stories received independent review; the resulting cache/configuration corrections and check evidence are recorded in [real-data-research.md](real-data-research.md). Earlier review-pending statements below describe the historical execution state. + Review baseline: `512f2f1c`, October 26, 2026. This records the primary agent's follow-up inspection and fixes, **not independent sign-off**. The 13 cleanup stories remain in `review`. A request to use three independent read-only reviewer agents is diff --git a/docs/development/real-data-research.md b/docs/development/real-data-research.md new file mode 100644 index 00000000..e86f14e7 --- /dev/null +++ b/docs/development/real-data-research.md @@ -0,0 +1,17 @@ +# Real-data research workflow + +Authorized follow-up to cleanup on October 26, 2026. Baseline `bd9332b2`. The manifest owns scheduling. RP01 adds read-only source inspection; RP02 exercises existing research paths with actual stored data. Performance, conditional CL21 and paper/live activation remain deferred. + +## Independent cleanup reviews + +- CL01/CL04: foundation reviewer accepted; CL02/CL03 required owned-cache corrections before acceptance. Real adapter probes reproduced transport leakage, cross-container endpoint reuse and ignored options. The correction owns DI/queue cache transports, preserves shared callers and namespaces, wires supported retries/TTL and diagnoses obsolete controls. Foundation reviewer accepted the fix; root scoped tests passed 38/190 assertions and application types. Expanded implementer gates passed 75/280. Three historical queue-utils expectations independently fail on the old baseline; no claim those passed. +- CL05/CL08/CL12: backend reviewer accepted; 154 domain/admission cases, 15 retained-worker cases, and 55 disposable PostgreSQL cases passed. Dataset/report moves preserve algorithms and transaction/receipt boundaries. +- CL06/CL07/CL09/CL10/CL11/CL13: frontend reviewer accepted; 390 UI/transport and 41 dataset/architecture cases passed. A pre-existing body-read abort diagnostic limitation remains nonblocking because cancelled generations are fenced. + +Reviewers: `/root/review_cleanup_foundations`, `/root/review_cleanup_backend`, `/root/review_cleanup_frontend`. Exact logs under `/tmp/stock-bot-*-review*.log` and `/tmp/stock-bot-research-next-20261026/`. Combined integration evidence follows. + +## Rechecked source + +Read-only Mongo query reproduced the previous AAPL October 2024 snapshot exactly: 1,816 five-minute rows, 22 null volumes at 20:00 UTC, no duplicate timestamps; raw query JSON hash `a8772d01d388b8fc9bca0d2790ad0d37146570fd09d057fcf1f1fcb5e6113bde`. PostgreSQL initially contained zero retained datasets/strategy versions and no experiments; existing runs are not evidence of this pilot. The development API responds on port 2003. + +Plan: inspect the full window; prepare one explicitly bounded regular trading session without changing source rows. Complete calendar/timing/action declarations and record limitations. No simulation outcome has yet been claimed here. diff --git a/docs/guide/system-map.md b/docs/guide/system-map.md index e21cd3b1..0e0b66f2 100644 --- a/docs/guide/system-map.md +++ b/docs/guide/system-map.md @@ -72,6 +72,18 @@ The stored-source adapter currently accepts **one raw EOD intraday series at `1m | **QuestDB** | An existing time-series adapter and historical storage route. The current web API, ingestion and pipeline entrypoints explicitly disable it in their container composition. Do not add it to the required retained-dataset research path just because the adapter exists. | | **Local build artifacts** | Native binary, worker bundle and retained strategy package identities are verified before execution. They supply executable code; they are not another account database. See [canonical-build.ts](../../apps/stock/orchestrator/src/backtest/canonical-build.ts). | +DI owns each service/global/proxy cache transport and closes only that container's connections. +Their key prefixes and cache DB1 remain unchanged; queue data uses DB0 and each QueueManager +owns its batch-cache transports. Direct shared-cache factory callers retain shared ownership. +`database.dragonfly.ttl` sets the service/global default cache TTL; `keyPrefix` is a deprecated +DI compatibility input and produces a diagnostic when set because service namespaces are fixed. +`database.dragonfly.maxRetries` maps to cache/rate-limiter `maxRetriesPerRequest`, and +`retryDelay` sets the fixed Redis reconnect delay in milliseconds. BullMQ workers deliberately +keep unlimited per-request retries; producers keep their fail-fast request policy. +QuestDB `bufferSize` and `flushInterval` are deprecated compatibility settings with no effect: +the client does not run a background buffered writer. Nondefault values produce a diagnostic; +explicit Influx writer operation options remain the supported batching interface. + ## What the shared libraries are for | Library | Why it exists | diff --git a/libs/core/cache/src/connection-manager.ts b/libs/core/cache/src/connection-manager.ts index 008148c3..c9252518 100644 --- a/libs/core/cache/src/connection-manager.ts +++ b/libs/core/cache/src/connection-manager.ts @@ -50,6 +50,7 @@ export class RedisConnectionManager { * Create a new Redis connection */ private createConnection(config: RedisConfig): Redis { + const retryDelay = config.retryDelay; return new Redis({ host: config.host, port: config.port, @@ -60,6 +61,7 @@ export class RedisConnectionManager { connectTimeout: config.connectTimeout ?? REDIS_DEFAULTS.CONNECT_TIMEOUT, commandTimeout: config.commandTimeout ?? REDIS_DEFAULTS.COMMAND_TIMEOUT, lazyConnect: false, + ...(retryDelay === undefined ? {} : { retryStrategy: () => retryDelay }), ...(config.tls && { tls: config.tls }), }); } diff --git a/libs/core/cache/src/redis-cache.ts b/libs/core/cache/src/redis-cache.ts index f84e17f5..27266deb 100644 --- a/libs/core/cache/src/redis-cache.ts +++ b/libs/core/cache/src/redis-cache.ts @@ -8,6 +8,8 @@ import type { CacheOptions, CacheProvider, CacheStats } from './types'; */ export class RedisCache implements CacheProvider { private redis: Redis; + private readonly ownsConnection: boolean; + private disconnected = false; private logger: NonNullable; private defaultTTL: number; private keyPrefix: string; @@ -15,6 +17,7 @@ export class RedisCache implements CacheProvider { private startTime = Date.now(); constructor(options: CacheOptions) { + this.ownsConnection = options.shared === false; this.defaultTTL = options.ttl ?? CACHE_DEFAULTS.TTL; this.keyPrefix = options.keyPrefix ?? CACHE_DEFAULTS.KEY_PREFIX; this.logger = options.logger || console; @@ -30,6 +33,15 @@ export class RedisCache implements CacheProvider { }); } + /** Only nonshared caches own their socket. Shared callers keep manager ownership. */ + async disconnect(): Promise { + if (this.ownsConnection && !this.disconnected) { + this.disconnected = true; + // A cache has no flush protocol; disconnect also stops retry handles when Redis is unavailable. + this.redis.disconnect(); + } + } + private getKey(key: string): string { return `${this.keyPrefix}${key}`; } diff --git a/libs/core/cache/src/types.ts b/libs/core/cache/src/types.ts index 46d3e767..24c21232 100644 --- a/libs/core/cache/src/types.ts +++ b/libs/core/cache/src/types.ts @@ -9,6 +9,8 @@ export interface RedisConfig { keyPrefix?: string; maxRetriesPerRequest?: number; retryDelayOnFailover?: number; + /** Fixed reconnect delay in milliseconds when explicitly configured. */ + retryDelay?: number; connectTimeout?: number; commandTimeout?: number; keepAlive?: number; @@ -41,6 +43,8 @@ export interface CacheProvider { keys(pattern: string): Promise; getStats(): CacheStats; health(): Promise; + /** Release an owned transport; borrowed/shared providers need not expose this. */ + disconnect?(): Promise; /** * Wait for the cache to be ready and connected diff --git a/libs/core/config/src/schemas/database.schema.ts b/libs/core/config/src/schemas/database.schema.ts index 19101f6e..77a92fba 100644 --- a/libs/core/config/src/schemas/database.schema.ts +++ b/libs/core/config/src/schemas/database.schema.ts @@ -25,8 +25,12 @@ export const questdbConfigSchema = z.object({ database: z.string().default('questdb'), user: z.string().optional(), // No default - QuestDB doesn't require auth by default password: z.string().optional(), // No default - QuestDB doesn't require auth by default - bufferSize: z.number().default(65536), - flushInterval: z.number().default(1000), + // Deprecated compatibility fields: DI uses the client, not a background buffered writer. + bufferSize: z.number().default(65536).describe('Deprecated: no effect on QuestDB client/writer'), + flushInterval: z + .number() + .default(1000) + .describe('Deprecated: no effect on QuestDB client/writer'), }); // MongoDB configuration @@ -52,10 +56,14 @@ export const dragonflyConfigSchema = z.object({ password: z.string().optional(), db: z.number().min(0).max(15).default(0), username: z.string().optional(), - keyPrefix: z.string().optional(), + keyPrefix: z + .string() + .optional() + .describe('Deprecated at DI boundary: service cache namespaces are fixed'), ttl: z.number().optional(), - maxRetries: z.number().default(3), - retryDelay: z.number().default(100), + // Cache/rate-limiter request retries. BullMQ retains its dedicated worker/producer policy. + maxRetries: z.number().default(3).describe('Cache/rate-limiter maxRetriesPerRequest'), + retryDelay: z.number().default(100).describe('Fixed Redis reconnect delay in milliseconds'), }); // Combined database configuration diff --git a/libs/core/di/src/container/types.ts b/libs/core/di/src/container/types.ts index a16b8760..d141a324 100644 --- a/libs/core/di/src/container/types.ts +++ b/libs/core/di/src/container/types.ts @@ -23,6 +23,7 @@ export interface ServiceDefinitions { // Core services cache: CacheProvider | null; globalCache: CacheProvider | null; + proxyCache: CacheProvider | null; proxyManager: ProxyManager | null; browser: Browser | null; queueManager: QueueManager | null; diff --git a/libs/core/di/src/registrations/cache.registration.ts b/libs/core/di/src/registrations/cache.registration.ts index d0a7204e..f42d06a0 100644 --- a/libs/core/di/src/registrations/cache.registration.ts +++ b/libs/core/di/src/registrations/cache.registration.ts @@ -7,6 +7,13 @@ export function registerCacheServices( config: AppConfig ): void { if (config.redis?.enabled) { + if (config.redis.keyPrefix !== undefined) { + container + .resolve('logger') + .warn( + 'Redis keyPrefix is deprecated at the DI boundary; service/global/proxy namespaces remain fixed' + ); + } container.register({ cache: asFunction(({ logger }) => { const { createServiceCache } = require('@stock-bot/queue'); @@ -21,11 +28,15 @@ export function registerCacheServices( port: config.redis.port, password: config.redis.password, username: config.redis.username, + maxRetriesPerRequest: config.redis.maxRetries, + retryDelay: config.redis.retryDelay, db: config.redis.db, // This will be overridden by ServiceCache }, - { logger } + { logger, shared: false, ttl: config.redis.ttl } ); - }).singleton(), + }) + .singleton() + .disposer(cache => cache.disconnect()), // Also provide global cache for shared data globalCache: asFunction(({ logger }) => { @@ -39,10 +50,14 @@ export function registerCacheServices( port: config.redis.port, password: config.redis.password, username: config.redis.username, + maxRetriesPerRequest: config.redis.maxRetries, + retryDelay: config.redis.retryDelay, }, - { global: true, logger } + { global: true, logger, shared: false, ttl: config.redis.ttl } ); - }).singleton(), + }) + .singleton() + .disposer(cache => cache.disconnect()), }); } else { container.register({ diff --git a/libs/core/di/src/registrations/database.registration.ts b/libs/core/di/src/registrations/database.registration.ts index 1f4aec04..d0ab84c5 100644 --- a/libs/core/di/src/registrations/database.registration.ts +++ b/libs/core/di/src/registrations/database.registration.ts @@ -76,6 +76,16 @@ export function registerDatabaseServices( if (config.questdb?.enabled) { container.register({ questdbClient: asFunction(({ logger }) => { + // Compatibility fields never configured the writer. Warn on requested tuning, + // rather than pretending bytes map to its explicit per-operation row batching. + if ( + defined(config.questdb).bufferSize !== 65536 || + defined(config.questdb).flushInterval !== 1000 + ) { + logger.warn( + 'QuestDB bufferSize/flushInterval are deprecated and have no effect; configure explicit writer batch options instead' + ); + } return new QuestDBClient( { host: defined(config.questdb).host, diff --git a/libs/core/di/src/registrations/service.registration.ts b/libs/core/di/src/registrations/service.registration.ts index 4e746ced..06be66e7 100644 --- a/libs/core/di/src/registrations/service.registration.ts +++ b/libs/core/di/src/registrations/service.registration.ts @@ -30,31 +30,35 @@ export function registerApplicationServices( // Proxy Manager if (config.proxy && config.redis?.enabled) { container.register({ - proxyManager: asFunction(({ logger }) => { + proxyCache: asFunction(({ logger }) => { // Create a separate cache instance for proxy with global prefix const { createCache } = require('@stock-bot/cache'); - const proxyCache = createCache({ + return createCache({ redisConfig: { host: config.redis.host, port: config.redis.port, password: config.redis.password, username: config.redis.username, + maxRetriesPerRequest: config.redis.maxRetries, + retryDelay: config.redis.retryDelay, db: 1, // Use cache DB (usually DB 1) }, + shared: false, keyPrefix: 'cache:proxy:', ttl: 86400, // 24 hours default enableMetrics: true, logger, }); - - const proxyManager = new ProxyManager(proxyCache, config.proxy, logger); - - // Note: Initialization will be handled by the lifecycle manager - return proxyManager; - }).singleton(), + }) + .singleton() + .disposer(cache => cache.disconnect?.()), + proxyManager: asFunction( + ({ logger, proxyCache }) => new ProxyManager(defined(proxyCache), config.proxy, logger) + ).singleton(), }); } else { container.register({ + proxyCache: asValue(null), proxyManager: asValue(null), }); } @@ -72,6 +76,8 @@ export function registerApplicationServices( port: config.redis.port, password: config.redis.password, username: config.redis.username, + maxRetriesPerRequest: config.redis.maxRetries, + retryDelay: config.redis.retryDelay, db: config.redis.db, }, defaultQueueOptions: { diff --git a/libs/core/di/src/utils/lifecycle.ts b/libs/core/di/src/utils/lifecycle.ts index fa196a93..32aadf73 100644 --- a/libs/core/di/src/utils/lifecycle.ts +++ b/libs/core/di/src/utils/lifecycle.ts @@ -14,6 +14,8 @@ export class ServiceLifecycleManager { private readonly logger = getLogger('service-lifecycle'); private readonly services = [ { name: 'cache', key: 'cache' as const }, + { name: 'globalCache', key: 'globalCache' as const }, + { name: 'proxyCache', key: 'proxyCache' as const }, { name: 'mongoClient', key: 'mongoClient' as const }, { name: 'postgresClient', key: 'postgresClient' as const }, { name: 'questdbClient', key: 'questdbClient' as const }, diff --git a/libs/core/queue/src/queue-manager.ts b/libs/core/queue/src/queue-manager.ts index 1a0f024e..ea2d0b7d 100644 --- a/libs/core/queue/src/queue-manager.ts +++ b/libs/core/queue/src/queue-manager.ts @@ -61,13 +61,15 @@ export class QueueManager { this.redisConnection = getRedisConnection(config.redis); // Create ioredis connection for rate limiter + const retryDelay = config.redis.retryDelay; this.ioredisConnection = new Redis({ host: config.redis.host, port: config.redis.port, password: config.redis.password, username: config.redis.username, db: config.redis.db || 0, - maxRetriesPerRequest: 3, + maxRetriesPerRequest: config.redis.maxRetriesPerRequest ?? 3, + ...(retryDelay === undefined ? {} : { retryStrategy: () => retryDelay }), enableReadyCheck: true, }); @@ -205,6 +207,7 @@ export class QueueManager { if (!this.caches.has(queueName)) { const cacheProvider = createCache({ redisConfig: this.config.redis, + shared: false, keyPrefix: `batch:${queueName}:`, ttl: 86400, // 24 hours default enableMetrics: true, @@ -499,6 +502,8 @@ export class QueueManager { await cache.clear(); } catch (error) { this.logger.warn('Error clearing cache', { error: (error as Error).message }); + } finally { + await cache.disconnect?.(); } }); diff --git a/libs/core/queue/src/service-cache.ts b/libs/core/queue/src/service-cache.ts index 11c0726a..3d527399 100644 --- a/libs/core/queue/src/service-cache.ts +++ b/libs/core/queue/src/service-cache.ts @@ -15,7 +15,8 @@ export class ServiceCache implements CacheProvider { serviceName: string, redisConfig: RedisConfig, isGlobalCache: boolean = false, - logger?: LoggerLike + logger?: LoggerLike, + options: { shared?: boolean; ttl?: number } = {} ) { // Determine Redis DB and prefix let db: number; @@ -37,6 +38,8 @@ export class ServiceCache implements CacheProvider { ...redisConfig, db, }, + shared: options.shared ?? true, + ...(options.ttl === undefined ? {} : { ttl: options.ttl }), keyPrefix: prefix + ':', logger, }; @@ -45,6 +48,10 @@ export class ServiceCache implements CacheProvider { this.prefix = prefix; } + async disconnect(): Promise { + await this.cache.disconnect?.(); + } + // Implement CacheProvider interface async get(key: string): Promise { return this.cache.get(key); @@ -173,7 +180,7 @@ export class ServiceCache implements CacheProvider { export function createServiceCache( serviceName: string, redisConfig: RedisConfig, - options: { global?: boolean; logger?: LoggerLike } = {} + options: { global?: boolean; logger?: LoggerLike; shared?: boolean; ttl?: number } = {} ): ServiceCache { - return new ServiceCache(serviceName, redisConfig, options.global, options.logger); + return new ServiceCache(serviceName, redisConfig, options.global, options.logger, options); } diff --git a/libs/core/queue/src/types.ts b/libs/core/queue/src/types.ts index ea473ff5..5f4cfde5 100644 --- a/libs/core/queue/src/types.ts +++ b/libs/core/queue/src/types.ts @@ -44,6 +44,8 @@ export interface RedisConfig { password?: string; username?: string; db?: number; + maxRetriesPerRequest?: number; + retryDelay?: number; } // Extended job options specific to this queue implementation diff --git a/libs/core/queue/src/utils.ts b/libs/core/queue/src/utils.ts index bec0b5e4..477801ac 100644 --- a/libs/core/queue/src/utils.ts +++ b/libs/core/queue/src/utils.ts @@ -9,6 +9,6 @@ export function getRedisConnection(config: RedisConfig) { connectTimeout: 3000, lazyConnect: false, keepAlive: 10000, - retryStrategy: (times: number) => Math.min(times * 100, 3000), + retryStrategy: (times: number) => config.retryDelay ?? Math.min(times * 100, 3000), }; } diff --git a/test/integration/cache-ownership.test.ts b/test/integration/cache-ownership.test.ts new file mode 100644 index 00000000..7eb0183b --- /dev/null +++ b/test/integration/cache-ownership.test.ts @@ -0,0 +1,130 @@ +import { expect, test } from 'bun:test'; + +/** Mock only the socket transport in a child: production factories, wrappers and DI stay real. */ +test('container and queue caches own endpoint-specific transports through shutdown and rollback', async () => { + const child = Bun.spawn( + [ + process.execPath, + '-e', + String.raw` + import { mock } from 'bun:test'; + import { EventEmitter } from 'node:events'; + const sockets = []; + class Redis { + constructor(options) { this.options = options; this.closed = 0; this.status = 'ready'; sockets.push(this); } + on() { return this; } + disconnect() { this.closed++; this.status = 'end'; } + async quit() { this.disconnect(); } + async setex(key, ttl) { this.lastWrite = {key,ttl}; } + async get(key) { if (this.closed) throw new Error('closed socket'); return JSON.stringify({host:this.options.host, username:this.options.username, key}); } + scanStream() { const stream = new EventEmitter(); queueMicrotask(() => this.failClear ? stream.emit('error',new Error('fixture clear failed')) : stream.emit('end')); return stream; } + pipeline() { return { del() {}, async exec() {} }; } + } + mock.module('ioredis', () => ({ default: Redis, Redis, Cluster: Redis })); + const { ServiceContainerBuilder } = await import('./libs/core/di/src/container/builder.ts'); + const { ProxyManager } = await import('@stock-bot/proxy'); + const { QueueManager } = await import('@stock-bot/queue'); + const { createCache } = await import('@stock-bot/cache'); + const options = {enableMongoDB:false,enablePostgres:false,enableQuestDB:false,enableQueue:false,enableBrowser:false,enableProxy:true}; + const config = (name) => ({ + name:'cache-owner', version:'1.0.0', service:{name:'cache-owner',port:3000}, log:{level:'fatal'}, + database:{dragonfly:{enabled:true,host:name+'.fixture.test',port:16379,username:name,password:'fixture-only',maxRetries:7,retryDelay:456,ttl:123}, + mongodb:{enabled:false,uri:'mongodb://unused/test',database:'test'}, + postgres:{enabled:false,database:'test',user:'test',password:'fixture-only'},questdb:{enabled:false}}, + }); + const builder = name => new ServiceContainerBuilder().withConfig(config(name)).withOptions(options); + const first = await builder('first').buildOwned(); + const firstSockets = sockets.slice(); + const firstCache = first.container.resolve('cache'); + const keys = await Promise.all([ + firstCache.get('x'), first.container.resolve('globalCache').get('x'), first.container.resolve('proxyCache').get('x') + ]); + await firstCache.set('x',1); + await first.container.resolve('globalCache').set('x',1); + await first.container.resolve('proxyCache').set('x',1); + const ttl = firstSockets.map(s=>s.lastWrite.ttl); + const second = await builder('second').buildOwned(); + const secondSockets = sockets.slice(firstSockets.length); + await first.shutdown(); await first.shutdown(); + const isolated = { first:firstSockets.map(s=>s.closed), second:secondSockets.map(s=>s.closed), read:await second.container.resolve('cache').get('x') }; + const third = await builder('first').buildOwned(); + const thirdSockets = sockets.slice(firstSockets.length + secondSockets.length); + const fresh = await third.container.resolve('cache').get('x'); + const beforeRollback = sockets.length; + const originalInitialize = ProxyManager.prototype.initialize; + const failure = new Error('fixture proxy initialization failed'); + ProxyManager.prototype.initialize = async () => { throw failure; }; + let originalFailure = false; + try { await builder('rollback').buildOwned(); } catch (error) { originalFailure = error === failure; } + finally { ProxyManager.prototype.initialize = originalInitialize; } + const rollback = sockets.slice(beforeRollback).map(s=>s.closed); + const disposed = await builder('dispose').skipInitialization().buildOwned(); + const beforeDispose = sockets.length; + disposed.container.resolve('serviceContainer'); + await disposed.container.dispose(); await disposed.container.dispose(); + const directDispose = sockets.slice(beforeDispose).map(s=>s.closed); + const queue = new QueueManager({serviceName:'cache-owner',redis:{host:'queue.fixture.test',port:16379,username:'queue',password:'fixture-only',maxRetriesPerRequest:7,retryDelay:456},autoDiscoverHandlers:false},undefined,first.container.resolve('logger')); + const beforeQueueCache = sockets.length; + const batch = queue.getCache('same-name'); + const batchRead = await batch.get('x'); + const workerPolicy = {maxRetriesPerRequest:queue.redisConnection.maxRetriesPerRequest,retryDelay:queue.redisConnection.retryStrategy(99)}; + sockets.at(-1).failClear = true; + await queue.shutdown(); + const queueClosed = sockets.slice(beforeQueueCache-1).map(s=>s.closed); + const shared = createCache({keyPrefix:'borrowed:',redisConfig:{host:'shared.fixture.test',port:16379}}); + const sharedAgain = createCache({keyPrefix:'borrowed:',redisConfig:{host:'shared.fixture.test',port:16379}}); + const sharedSocket = sockets.at(-1); + await shared.disconnect?.(); + await second.shutdown(); await third.shutdown(); + const wire = sockets.filter(s=>s.options.host!=='shared.fixture.test').map(s=>({host:s.options.host,username:s.options.username,db:s.options.db,retries:s.options.maxRetriesPerRequest,delay:s.options.retryStrategy?.(99)})); + process.stdout.write('__cache_ownership__'+JSON.stringify({keys,ttl,isolated,fresh,thirdClosed:thirdSockets.map(s=>s.closed),originalFailure,rollback,directDispose,batchRead,workerPolicy,queueClosed,sharedSame:shared===sharedAgain,sharedClosed:sharedSocket.closed,wire})+'\n'); + `, + ], + { stdout: 'pipe', stderr: 'pipe' } + ); + const [stdout, stderr, code] = await Promise.all([ + new Response(child.stdout).text(), + new Response(child.stderr).text(), + child.exited, + ]); + if (code !== 0) { + throw new Error(`Cache ownership probe failed: ${stderr}`); + } + const line = stdout.split('\n').find(value => value.startsWith('__cache_ownership__')); + expect(line).toBeDefined(); + const result = JSON.parse(line!.slice('__cache_ownership__'.length)); + expect(result.keys.map((value: { key: string }) => value.key)).toEqual([ + 'cache:cache-owner:x', + 'stock-bot:shared:x', + 'cache:proxy:x', + ]); + expect(result.ttl).toEqual([123, 123, 86400]); + expect(result.isolated).toEqual({ + first: [1, 1, 1], + second: [0, 0, 0], + read: { host: 'second.fixture.test', username: 'second', key: 'cache:cache-owner:x' }, + }); + expect(result.fresh).toEqual({ + host: 'first.fixture.test', + username: 'first', + key: 'cache:cache-owner:x', + }); + expect(result.thirdClosed).toEqual([1, 1, 1]); + expect(result.originalFailure).toBe(true); + expect(result.rollback).toEqual([1, 1, 1]); + expect(result.directDispose).toEqual([1, 1, 1]); + expect(result.batchRead).toEqual({ + host: 'queue.fixture.test', + username: 'queue', + key: 'batch:same-name:x', + }); + expect(result.queueClosed).toEqual([1, 1]); + expect(result.workerPolicy).toEqual({ maxRetriesPerRequest: null, retryDelay: 456 }); + expect(result.sharedSame).toBe(true); + expect(result.sharedClosed).toBe(0); + for (const wire of result.wire) { + expect(wire.retries).toBe(7); + expect(wire.delay).toBe(456); + expect(wire.db).toBe(wire.host === 'queue.fixture.test' ? 0 : 1); + } +}, 15_000); diff --git a/test/integration/store-configuration.test.ts b/test/integration/store-configuration.test.ts index b1160ba2..863d4440 100644 --- a/test/integration/store-configuration.test.ts +++ b/test/integration/store-configuration.test.ts @@ -1,7 +1,11 @@ -import { expect, test } from 'bun:test'; +import { asValue, createContainer } from 'awilix'; +import { expect, mock, test } from 'bun:test'; import type { PoolConfig } from 'pg'; import { baseAppSchema } from '@stock-bot/config'; +import { appConfigSchema } from '../../libs/core/di/src/config/schemas'; import { ServiceContainerBuilder } from '../../libs/core/di/src/container/builder'; +import type { ServiceDefinitions } from '../../libs/core/di/src/container/types'; +import { registerCacheServices } from '../../libs/core/di/src/registrations/cache.registration'; function configuration(enabled = true) { return baseAppSchema.parse({ @@ -42,8 +46,9 @@ for (const enabled of [true, false]) { .skipInitialization() .build(); try { - for (const name of ['cache', 'mongoClient', 'postgresClient']) + for (const name of ['cache', 'mongoClient', 'postgresClient']) { expect(c.resolve(name)).toBeNull(); + } const config = c.resolve('config'); expect(config.redis.enabled).toBe(false); expect(config.mongodb.enabled).toBe(false); @@ -61,8 +66,9 @@ test('enable options do not override disabled configurations', async () => { .skipInitialization() .build(); try { - for (const name of ['cache', 'mongoClient', 'postgresClient']) + for (const name of ['cache', 'mongoClient', 'postgresClient']) { expect(c.resolve(name)).toBeNull(); + } } finally { await c.dispose(); } @@ -106,7 +112,7 @@ test('PostgreSQL nondefault fields reach wire configuration and Mongo retains UR } }); -test('flat QuestDB alias takes precedence without discarding credentials or schema settings', async () => { +test('flat QuestDB alias and credentials reach the client; unsupported tuning is diagnosed', async () => { const c = await new ServiceContainerBuilder() .withConfig({ ...configuration(false), @@ -123,6 +129,9 @@ test('flat QuestDB alias takes precedence without discarding credentials or sche } as never) .skipInitialization() .build(); + const logger = c.resolve('logger'); + const originalWarn = logger.warn; + logger.warn = mock(() => {}); try { expect(c.resolve('config').questdb).toMatchObject({ influxPort: 29009, @@ -131,7 +140,34 @@ test('flat QuestDB alias takes precedence without discarding credentials or sche user: 'fixture', password: 'fixture', }); + expect(c.resolve('questdbClient')!.configuration).toMatchObject({ + influxPort: 29009, + user: 'fixture', + password: 'fixture', + }); + expect(logger.warn).toHaveBeenCalledWith( + 'QuestDB bufferSize/flushInterval are deprecated and have no effect; configure explicit writer batch options instead' + ); + expect(logger.warn).toHaveBeenCalledTimes(1); } finally { + logger.warn = originalWarn; + await c.dispose(); + } +}); + +test('default QuestDB compatibility settings do not produce tuning diagnostics', async () => { + const c = await new ServiceContainerBuilder() + .withConfig({ ...configuration(false), questdb: { enabled: true } } as never) + .skipInitialization() + .build(); + const logger = c.resolve('logger'); + const originalWarn = logger.warn; + logger.warn = mock(() => {}); + try { + expect(c.resolve('questdbClient')).not.toBeNull(); + expect(logger.warn).not.toHaveBeenCalled(); + } finally { + logger.warn = originalWarn; await c.dispose(); } }); @@ -150,8 +186,9 @@ test('all-disabled default composition needs neither store settings nor connecti }) .build(); try { - for (const name of ['cache', 'mongoClient', 'postgresClient', 'questdbClient']) + for (const name of ['cache', 'mongoClient', 'postgresClient', 'questdbClient']) { expect(c.resolve(name)).toBeNull(); + } } finally { await c.dispose(); } @@ -193,11 +230,13 @@ test('Redis ACL username reaches cache and both queue connection settings withou new Response(child.stderr).text(), child.exited, ]); - if (code !== 0) throw new Error(`Redis transport probe failed: ${stderr}`); + if (code !== 0) { + throw new Error(`Redis transport probe failed: ${stderr}`); + } const line = stdout.split('\n').find(line => line.startsWith('__redis_capture__')); expect(line).toBeDefined(); const result = JSON.parse(line!.slice('__redis_capture__'.length)); - expect(result.captured).toHaveLength(2); + expect(result.captured).toHaveLength(3); for (const config of [...result.captured, result.queue]) { expect(config).toMatchObject({ host: 'redis.fixture.test', @@ -206,3 +245,20 @@ test('Redis ACL username reaches cache and both queue connection settings withou }); } }); + +test('deprecated DI cache prefixes produce a diagnostic without echoing supplied values', () => { + const logger = { warn: mock(() => {}) }; + // Registration validates the compatibility setting without constructing Redis transports. + const container = createContainer(); + container.register('logger', asValue(logger as unknown as ServiceDefinitions['logger'])); + const config = appConfigSchema.parse({ + redis: { enabled: true, keyPrefix: 'private-operator-prefix' }, + mongodb: { enabled: false, uri: 'mongodb://unused/test', database: 'test' }, + postgres: { enabled: false, database: 'test', user: 'test', password: 'fixture-only' }, + }); + registerCacheServices(container, config); + expect(logger.warn).toHaveBeenCalledTimes(1); + expect(logger.warn).toHaveBeenCalledWith( + 'Redis keyPrefix is deprecated at the DI boundary; service/global/proxy namespaces remain fixed' + ); +});