diff --git a/apps/stock/config/src/contracts/canonical-research.ts b/apps/stock/config/src/contracts/canonical-research.ts index a3dd0d9c..44ac4bde 100644 --- a/apps/stock/config/src/contracts/canonical-research.ts +++ b/apps/stock/config/src/contracts/canonical-research.ts @@ -5,6 +5,7 @@ import type { CanonicalBacktestAnalytics, financialDecimal, FinancialDecimal, + HistoricalDatasetInputV2, HistoricalDatasetManifestV2, } from '@stock-bot/types'; import { parseFinancialDecimal } from '@stock-bot/types'; @@ -184,6 +185,12 @@ export interface CanonicalDatasetPreparation { reason: string | null; } +/** One materialized storage read; retention must use this input without requerying. */ +export interface CanonicalStoredSourcePreparation { + input: HistoricalDatasetInputV2; + preparation: CanonicalDatasetPreparation; +} + /** Validate the authoritative financial envelope without legacy metric conversion. */ export function parseCanonicalFinancialResult(input: unknown, request: CanonicalRunRequest) { return parseReplayReportValue( diff --git a/apps/stock/orchestrator/src/data/historical-dataset-v2.ts b/apps/stock/orchestrator/src/data/historical-dataset-v2.ts index a82a16d6..da196bc2 100644 --- a/apps/stock/orchestrator/src/data/historical-dataset-v2.ts +++ b/apps/stock/orchestrator/src/data/historical-dataset-v2.ts @@ -278,6 +278,11 @@ function parseMetadata(input: unknown) { return metadata; } +/** Validate and detach complete operator declarations before a stored-source read. */ +export function parseHistoricalDatasetMetadataV2(input: unknown): HistoricalDatasetMetadataV2 { + return parseMetadata(input); +} + function assess(metadata: HistoricalDatasetMetadataV2, parentDatasetHash: string | null) { const limitations = [ 'Open liquidity must use previously available volume; intraday partial bars are unsupported', diff --git a/apps/stock/web-api/src/routes/datasets.routes.ts b/apps/stock/web-api/src/routes/datasets.routes.ts index 771d99f9..80bc249c 100644 --- a/apps/stock/web-api/src/routes/datasets.routes.ts +++ b/apps/stock/web-api/src/routes/datasets.routes.ts @@ -2,6 +2,7 @@ import { Hono } from 'hono'; import { getLogger } from '@stock-bot/logger'; import { requireServices, type IServiceContainer } from '@stock-bot/services'; import { HistoricalDataRequestError } from '@stock-bot/types'; +import { StorageService } from '../../../orchestrator/src/services/StorageService'; import { canonicalDatasetEntry } from '../services/canonical-research.service'; import { DatasetCatalogService } from '../services/dataset-catalog.service'; import { @@ -9,6 +10,10 @@ import { previewDatasetPreparation, retainDatasetPreparation, } from '../services/dataset-preparation.service'; +import { + prepareStoredDataset, + StoredDatasetPreparationError, +} from '../services/stored-dataset-preparation'; const logger = getLogger('dataset-catalog-routes'); @@ -23,6 +28,32 @@ export function createDatasetRoutes(container: IServiceContainer) { throw new DatasetPreparationError(400, 'Invalid JSON request'); } }; + app.post('/api/v2/datasets/canonical/stored-source', async c => { + c.header('Cache-Control', 'no-store'); + try { + const body = await readBody(c.req.raw); + // Request-local read adapter: no initialization, mode changes or shared trading runtime. + const storage = new StorageService(container, container.mongodb, null, null); + const prepared = await prepareStoredDataset(body, storage, c.req.raw.signal); + c.req.raw.signal.throwIfAborted(); + return c.json(prepared); + } catch (error) { + if (c.req.raw.signal.aborted) { + return Response.json( + { error: 'Stored source preparation cancelled' }, + { status: 499, headers: { 'Cache-Control': 'no-store' } } + ); + } + if ( + error instanceof StoredDatasetPreparationError || + error instanceof DatasetPreparationError + ) { + return c.json({ error: error.message }, error.status); + } + logger.error('Failed to prepare stored source dataset', error); + return c.json({ error: 'Stored source preparation unavailable' }, 500); + } + }); app.post('/api/v2/datasets/canonical/preview', async c => { c.header('Cache-Control', 'no-store'); try { diff --git a/apps/stock/web-api/src/services/stored-dataset-preparation.ts b/apps/stock/web-api/src/services/stored-dataset-preparation.ts new file mode 100644 index 00000000..a24f40f6 --- /dev/null +++ b/apps/stock/web-api/src/services/stored-dataset-preparation.ts @@ -0,0 +1,136 @@ +import { z } from 'zod'; +import type { CanonicalStoredSourcePreparation } from '@stock-bot/stock-config/canonical-research'; +import type { HistoricalDatasetInputV2, HistoricalDatasetMetadataV2 } from '@stock-bot/types'; +import { parseHistoricalDatasetMetadataV2 } from '../../../orchestrator/src/data/historical-dataset-v2'; +import { + HistoricalStorageError, + type StorageService, +} from '../../../orchestrator/src/services/StorageService'; +import { DatasetPreparationError, previewDatasetPreparation } from './dataset-preparation.service'; + +export class StoredDatasetPreparationError extends Error { + constructor( + readonly status: 400 | 404 | 422 | 503, + message: string + ) { + super(message); + } +} +const bodySchema = z.object({ metadata: z.unknown() }).strict(); +function freeze(value: T): T { + if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) { + Object.values(value).forEach(freeze); + Object.freeze(value); + } + return value; +} +function metadataFromBody(body: unknown): HistoricalDatasetMetadataV2 { + try { + const parsed = bodySchema.parse(body); + return freeze(parseHistoricalDatasetMetadataV2(parsed.metadata)); + } catch (error) { + const path = error instanceof z.ZodError ? error.issues[0]?.path.join('.') : undefined; + throw new StoredDatasetPreparationError( + 400, + path + ? `Invalid complete source metadata at ${path}` + : 'Stored source requires valid complete v2 metadata' + ); + } +} + +/** Materialize one explicit stored EOD query. Captured bytes, not this mutable query, are retained. */ +export async function prepareStoredDataset( + body: unknown, + storage: Pick, + signal: AbortSignal +): Promise { + signal.throwIfAborted(); + const metadata = metadataFromBody(body); + const series = metadata.series[0]; + if ( + !series || + metadata.series.length !== 1 || + metadata.executionSeries.length !== 1 || + metadata.universe.instrumentIds.length !== 1 || + series.source.provider !== 'eod' || + !['1m', '5m', '1h'].includes(series.interval) || + series.adjustment !== 'raw' || + series.timestamp !== 'interval-start' || + series.availability !== 'interval-end-assumption' + ) { + throw new StoredDatasetPreparationError( + 400, + 'Stored source supports one EOD raw 1m/5m/1h series with interval-start timestamps and declared interval-end-assumption availability' + ); + } + let rows; + try { + rows = await storage.getHistoricalBars( + series.instrumentId, + new Date(metadata.bounds.warmupStart), + new Date(metadata.bounds.tradeEnd), + series.interval, + { adjustment: 'raw', timestamp: 'utc-instant' }, + signal, + 'eod' + ); + } catch (error) { + signal.throwIfAborted(); + if (error instanceof HistoricalStorageError && error.code === 'missing-range') { + throw new StoredDatasetPreparationError(404, 'No stored EOD bars in the requested range'); + } + if (error instanceof HistoricalStorageError && error.code === 'provider-unavailable') { + throw new StoredDatasetPreparationError(503, 'EOD historical storage is unavailable'); + } + throw error; + } + signal.throwIfAborted(); + if (!rows.length) { + throw new StoredDatasetPreparationError(404, 'No stored EOD bars in the requested range'); + } + for (const row of rows) { + if ( + row.symbol !== series.instrumentId || + row.source !== 'eod' || + row.interpolated === true || + !(row.timestamp instanceof Date) || + !Number.isSafeInteger(row.timestamp.getTime()) || + row.timestamp.getTime() < metadata.bounds.warmupStart || + row.timestamp.getTime() >= metadata.bounds.tradeEnd + ) { + throw new Error('Stored source returned inconsistent bar identity or range'); + } + } + const input: HistoricalDatasetInputV2 = freeze({ + metadata, + // Ordinal is deterministic adapter ordering, not a vendor publication sequence. + bars: [...rows] + .sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime()) + .map((row, sourceSequence) => ({ + seriesId: series.id, + timestamp: row.timestamp.getTime(), + sourceSequence, + open: row.open, + high: row.high, + low: row.low, + close: row.close, + volume: row.volume, + ...(row.vwap === undefined ? {} : { vwap: row.vwap }), + })), + }); + let preparation; + try { + preparation = previewDatasetPreparation({ input }); + } catch (error) { + if (error instanceof DatasetPreparationError) { + throw new StoredDatasetPreparationError( + 422, + 'Stored bars do not match the declared complete dataset metadata and interval policy' + ); + } + throw error; + } + signal.throwIfAborted(); + return freeze({ input, preparation }); +} diff --git a/apps/stock/web-app/src/features/backtest/components/DatasetPreparation.tsx b/apps/stock/web-app/src/features/backtest/components/DatasetPreparation.tsx index f6a4e318..7a776167 100644 --- a/apps/stock/web-app/src/features/backtest/components/DatasetPreparation.tsx +++ b/apps/stock/web-app/src/features/backtest/components/DatasetPreparation.tsx @@ -18,8 +18,11 @@ interface Retention { input: unknown; preview: CanonicalDatasetPreparation; } +type InputMode = 'export' | 'stored-eod'; const instant = (value: number) => new Date(value).toISOString(); export function DatasetPreparation({ disabled, begin, onStateChange, onRetained }: Props) { + const [mode, setMode] = useState('export'); + const modeRef = useRef('export'); const [input, setInput] = useState<{ value: unknown; filename: string } | null>(null); const [preview, setPreview] = useState(null); const [retained, setRetained] = useState(false), @@ -65,6 +68,20 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained } state(false, false); }; + const changeMode = (next: string) => { + if ( + (next !== 'export' && next !== 'stored-eod') || + next === modeRef.current || + disabled || + captured.current || + !callbacks.current.begin() + ) { + return; + } + reset(); + modeRef.current = next; + setMode(next); + }; const loadFile = async (file: File | undefined) => { if (disabled || captured.current || !callbacks.current.begin()) { return; @@ -107,6 +124,7 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained }; const inspect = async () => { const selectedSource = source.current; + const selectedMode = modeRef.current; if ( disabled || pending.current || @@ -127,10 +145,16 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained setRetained(false); state(true, true); try { - const result = await backtestApiV2.previewDataset(selectedSource.value, abort.signal); + const result = + selectedMode === 'stored-eod' + ? await backtestApiV2.previewStoredDataset(selectedSource.value, abort.signal) + : { + input: selectedSource.value, + preparation: await backtestApiV2.previewDataset(selectedSource.value, abort.signal), + }; if (active.current && revision === generation.current) { - prepared.current = { input: selectedSource.value, preview: result }; - setPreview(result); + prepared.current = { input: result.input, preview: result.preparation }; + setPreview(result.preparation); } } catch (cause) { if (active.current && revision === generation.current) { @@ -197,7 +221,9 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained prepared.current = null; setIntent(null); setPreview(null); - setError(`${cause.message} Preview again or choose a corrected source export.`); + setError( + `${cause.message} Preview again or choose a corrected ${modeRef.current === 'export' ? 'source export' : 'metadata file'}.` + ); } else { setError( `${cause instanceof Error ? cause.message : 'Dataset retention response was lost'} Retry the exact same input and hash; retention may already have succeeded.` @@ -215,25 +241,53 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained return (

- Supply a complete source export with metadata and bars. Sessions, source revisions, - universe, corporate actions and publication availability must be explicit. Declared - provenance is not independent provider certification. Preview writes nothing; retention does - not save settings or start a run. + Supply complete metadata with exported bars or explicitly selected stored EOD intraday bars. + Sessions, source revisions, universe, corporate actions and publication availability must be + explicit. Declared provenance is not independent provider certification. Preview writes + nothing; retention does not save settings or start a run.

+ {mode === 'stored-eod' && ( +

+ Load one EOD instrument from existing storage using raw 1m, 5m or 1h interval-start bars. + Supply complete metadata with interval-end-assumption availability. Source sequence is a + deterministic sorted row ordinal, not a vendor sequence. The current store, history and + declared revision are not independently certified. Preview reads a new snapshot; retention + uses that captured snapshot without querying storage again. +

+ )} + - {!input && !phase && !error &&

No source export selected.

} - {input &&

Selected export: {input.filename}

} + {!input && !phase && !error && ( +

{mode === 'export' ? 'No source export selected.' : 'No source metadata selected.'}

+ )} + {input && ( +

+ Selected {mode === 'export' ? 'export' : 'metadata'}: {input.filename} +

+ )} {phase && (

{phase === 'reading' @@ -295,6 +349,13 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained )} {preview && (

+ {mode === 'stored-eod' && ( +

+ Stored source: EOD · Query bounds (UTC, end exclusive):{' '} + {instant(preview.manifest.bounds.warmupStart)} —{' '} + {instant(preview.manifest.bounds.tradeEnd)} +

+ )}

Dataset hash: {preview.hash}

{preview.manifest.barCount} bars · Eligibility: {preview.manifest.eligibility} ·{' '} diff --git a/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts b/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts index 561749eb..84bccb17 100644 --- a/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts +++ b/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts @@ -6,8 +6,10 @@ import type { CanonicalReproductionComparison, CanonicalReproductionPreview, CanonicalRunCapability, + CanonicalStoredSourcePreparation, ResearchRunResult, } from '@stock-bot/stock-config/canonical-research'; +import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; import type { BacktestRunDatasetSelection, BacktestRunResult, @@ -260,6 +262,118 @@ export function parseDatasetPreparation( } return value; } +const preparationMetadata = preparationManifest.pick({ + calendars: true, + series: true, + executionSeries: true, + bounds: true, + universe: true, + corporateActions: true, +}); +const storedSourceInput = z + .object({ + metadata: preparationMetadata, + bars: z + .array( + z + .object({ + seriesId: preparationText, + timestamp: preparationInstant, + sourceSequence: z.number().int().nonnegative().safe(), + open: z.number().finite().positive(), + high: z.number().finite().positive(), + low: z.number().finite().positive(), + close: z.number().finite().positive(), + volume: z.number().finite().nonnegative(), + vwap: z.number().finite().positive().nullable().optional(), + }) + .strict() + ) + .min(1), + }) + .strict(); +type PreparationMetadata = z.infer; +const compareText = (left: string, right: string) => (left < right ? -1 : left > right ? 1 : 0); +/** Compare declarations across server-normalized collection order; never normalize bars or calculate hashes. */ +function metadataIdentity(value: PreparationMetadata) { + return canonicalStrategyJson({ + ...value, + calendars: value.calendars + .map(calendar => ({ + ...calendar, + sessions: [...calendar.sessions].sort((a, b) => compareText(a.date, b.date)), + })) + .sort((a, b) => compareText(a.id, b.id)), + series: [...value.series].sort((a, b) => compareText(a.id, b.id)), + executionSeries: [...value.executionSeries].sort((a, b) => + compareText(a.instrumentId, b.instrumentId) + ), + universe: { + ...value.universe, + instrumentIds: [...value.universe.instrumentIds].sort(compareText), + }, + corporateActions: value.corporateActions + .map(coverage => ({ + ...coverage, + actions: [...coverage.actions].sort( + (a, b) => a.effectiveAt - b.effectiveAt || compareText(a.reference, b.reference) + ), + })) + .sort((a, b) => compareText(a.instrumentId, b.instrumentId)), + }); +} +export function parseStoredDatasetPreparation( + raw: unknown, + suppliedMetadata: unknown +): CanonicalStoredSourcePreparation { + const envelope = z + .object({ input: storedSourceInput, preparation: z.unknown() }) + .strict() + .parse(raw); + const preparation = parseDatasetPreparation(envelope.preparation); + const expected = preparationMetadata.parse(suppliedMetadata); + const { calendars, series, executionSeries, bounds, universe, corporateActions } = + preparation.manifest; + const retainedMetadata = { + calendars, + series, + executionSeries, + bounds, + universe, + corporateActions, + }; + const input = envelope.input, + metadata = input.metadata, + selected = metadata.series[0]; + if ( + !selected || + metadata.series.length !== 1 || + metadata.executionSeries.length !== 1 || + metadata.universe.instrumentIds.length !== 1 || + selected.source.provider !== 'eod' || + !['1m', '5m', '1h'].includes(selected.interval) || + selected.adjustment !== 'raw' || + selected.timestamp !== 'interval-start' || + selected.availability !== 'interval-end-assumption' || + metadata.executionSeries[0]?.seriesId !== selected.id || + metadata.executionSeries[0]?.instrumentId !== selected.instrumentId || + metadata.universe.instrumentIds[0] !== selected.instrumentId || + metadataIdentity(metadata) !== metadataIdentity(expected) || + metadataIdentity(metadata) !== metadataIdentity(preparationMetadata.parse(retainedMetadata)) || + input.bars.length !== preparation.manifest.barCount || + input.bars.some( + (bar, index) => + bar.seriesId !== selected.id || + bar.sourceSequence !== index || + bar.timestamp < metadata.bounds.warmupStart || + bar.timestamp >= metadata.bounds.tradeEnd || + (index > 0 && bar.timestamp <= (input.bars[index - 1]?.timestamp ?? Infinity)) + ) + ) { + throw new Error('The stored source response does not match its metadata and prepared dataset.'); + } + return { input, preparation }; +} export class DatasetPreparationRequestError extends Error { constructor( message: string, @@ -305,6 +419,28 @@ export const backtestApiV2 = { prepareDatasetRequest({ input }, signal), retainDataset: (input: unknown, expectedHash: string, signal?: AbortSignal) => prepareDatasetRequest({ input, expectedHash }, signal), + async previewStoredDataset( + metadata: unknown, + signal?: AbortSignal + ): Promise { + const response = await fetch(`${API_BASE_URL}/api/v2/datasets/canonical/stored-source`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ metadata }), + signal, + }); + if (!response.ok) { + throw await requestError(response, 'Could not load stored EOD bars'); + } + try { + if (response.status !== 200) { + throw new Error('Unexpected stored source status'); + } + return parseStoredDatasetPreparation(await response.json(), metadata); + } catch { + throw new Error('The stored source response could not be verified.'); + } + }, async reproductionPreview( id: string, signal?: AbortSignal diff --git a/docs/development/ROADMAP.md b/docs/development/ROADMAP.md index b8a4305b..f3c44dde 100644 --- a/docs/development/ROADMAP.md +++ b/docs/development/ROADMAP.md @@ -1,8 +1,8 @@ # Revised development roadmap -**First thirty-four waves committed; R05 explicit source-export preparation is validated and ready to commit.** R09 is committed as `06039d1`; **37 of 45 scheduled tasks are fully committed (82% by count)**. Full R05 remains partial, and R07 retains its paused table measurement. +**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. -Authorization update: the owner requested “commit and continue”. R09 citations were committed as `06039d1`; the R05 explicit source-export preparation slice 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”. 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. ## Strategy and review outcome @@ -711,3 +711,17 @@ Final validation passed: **1077 integration /150 Rust** tests, plus 93 tooling, Independent review accepted all eleven agent-owned files plus root contract/transport/browser composition. Review fixed synchronous retry-state clearing, non-strict manifest response parsing and definitive-rejection handling. Exact 16-file archive SHA256 `029dd93e14ee7a9fa72f7b06118c708ce1ecad6711fa6d0411bc0fe2e0ada7fa`, file hashes, reviewer evidence and logs are recorded in `manifest.json` → `thirty_fifth_wave_validation`, under `/tmp/stock-bot-wave35.fQycky/`. The unchanged release engine was restored before final database/browser gates. Both exact disposable containers were stopped; development services were untouched. Source metadata is supplied evidence, not independently certified provider truth. V1 conversion and automatic provider preparation remain outside this slice. R07 performance measurement and other performance work remain paused; default/multiasset/candidate/AI/paper/live gates are unchanged. No new-wave commit, push or PR occurred. + +## Thirty-sixth-wave handoff — 2026-10-24 + +The owner accepted explicit export preparation, committed as `366bee8`. R05's stored EOD intraday preparation component is independently reviewed and validated, with new changes uncommitted. There are still **37/45 scheduled tasks committed**: two partial (R05/R07), six blocked (S06/P04/A01–A04), six additional deferred and four merged IDs. Counts measure task closure, not remaining effort. + +- **Real storage adapter:** The existing preparation panel now accepts complete metadata for one stored EOD raw1m/5m/1h series. The server validates and detaches declarations before querying the existing StorageService with exact bounds and explicit EOD selection. No initialization, shared paper state, external provider request, synthetic/auto fallback or inferred metadata. The row ordinal is deterministic adapter ordering, not a vendor publication sequence; missing VWAP stays null and interval-end availability is explicitly an assumption. +- **Captured data:** Preparation returns the full materialized input and the existing normalized manifest/hash. Retention submits those captured bytes through the unchanged endpoint. Source edits can change a fresh preview but cannot change the original retention/retry or admitted run. The export mode remains intact, invalid/unavailable evidence remains visible, and stale mode/file/parent responses cannot replace the active selection. Cancellation fences late data; the underlying Mongo request may finish in flight without producing a successful cancelled preview. +- **Simpler admission:** The original pending-source-query/first-binding run proposal is intentionally superseded. Canonical data is prepared, reviewed and retained before existing atomic request/hash admission, which the worker verifies before decisions. No new run kind, SQL, scheduler, result schema, financial semantics or runner path. Wider cutover/default/multiasset policy gates remain, so R05 and S06 are not declared complete. + +All final gates passed: **1126 integration /150 Rust** tests, plus93 tooling/43 utility/44 calculation tests; build, secret audit, types, contracts and lint. Final release **PostgreSQL/Redis:242 tests /2196 assertions**; **Chromium:16 workflows /612 assertions**. Root strict affected/new-test types and all11-file lint/format/hash/DAG/diff checks pass without exceptions. Four existing manual Rust cases remain ignored. The browser preserves source-export coverage, materializes EOD through the actual adapter, changes stored prices, proves a fresh hash differs, retains/retries the original without another source read, and verifies the existing hand-calculated Rust economics plus reopening. Mongo transport is replaced in fixtures; real MongoDB-server conformance and vendor coverage certification are not claimed. + +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. diff --git a/docs/development/architecture/research-product.md b/docs/development/architecture/research-product.md index 6ba2aac0..22530735 100644 --- a/docs/development/architecture/research-product.md +++ b/docs/development/architecture/research-product.md @@ -59,7 +59,7 @@ Keep `/api/v2` and current operator sessions. New APIs follow the task-specific - Results distinguish financial engine, strategy execution mode, metrics/economics policy versions and provenance completeness. Maintain compatibility fields for old clients. - Reproduce-original pins original inputs; rerun-current creates a new request. Missing original code/dataset/model is a clear failure, not a fallback. - Comparison must surface mismatched costs, datasets, windows, engines and failed candidates; default ranking uses comparable completed project-gated runs. -- Batch submission requires a resolved frozen dataset hash shared by its candidates. A single run may first prepare a new source request; individual sweep trials must not independently reload provider history. +- Canonical single and batch submissions require a resolved retained dataset hash. Prepare sources before admission; individual sweep trials must not independently reload provider history. - Retention is archive-first. Referenced runs/versions/datasets/artifacts cannot disappear through an existing cascade. - UI/API do not calculate competing equity, fees or fills. Display-only formatting/downsampling never changes financial results. @@ -75,7 +75,7 @@ Keep `/api/v2` and current operator sessions. New APIs follow the task-specific Do not delay M1/M2 for the entire Rust migration. Conversely, delivering those screens does not make old financial results trustworthy. M1 release requires C06 runtime isolation; exploratory labels never excuse interference with paper state. -Dataset selection R11 lists retained manifests without loading bar payloads. A selected existing hash is recorded in the immutable submission and is bound by the runner after retained-content validation. A new source request freezes query parameters then prepares asynchronously through the existing runner; only after a fenced atomic dataset binding is it reproducible input. No strategy execution occurs before that binding. Retries reuse the pinned dataset, not a fresh provider query. The UI must distinguish these phases. +Canonical source preparation is explicit and precedes run admission. Preview returns materialized source bytes and their normalized identity; retention captures those exact bytes through the existing immutable store. A subsequent source read may differ and must be requested explicitly. Canonical admission validates the retained content and atomically freezes its hash with the executable and policies; the worker verifies the binding before decisions. Retention retries reuse the captured input, and run retries reuse the retained dataset. This 2026-10-24 refinement supersedes the original asynchronous source-preparation-inside-run proposal, avoiding another run lifecycle without weakening frozen-input guarantees. Legacy v1 source preparation/readers retain their existing behavior. ## Example: bounded AI-assisted multi-strategy research @@ -96,7 +96,7 @@ Reuse current Card/Dialog/DataTable/layout/chart/metric components and responsiv Existing [analytics-ui tests](../../../test/integration/analytics-ui.test.tsx#L1) use server rendering. W04 now supplies the shared [Playwright workflow harness](../../../test/e2e/workbench.test.ts), real authenticated Hono routes, disposable SQL/Redis, durable dispatch and native smoke coverage. Extend it for research-product flows instead of creating a second harness. -R11 exposes retained v1 metadata and exact hash selection in both backtest forms. Catalog coverage is unknown and full content integrity is not verified by metadata inspection; the runner validates retained bytes before binding/execution. The current web runner remains legacy/v1, so v2 entries are visibly unsupported until R05. Source requests remain unpinned until prepared asynchronously. These product capabilities do not remove the existing economics qualifications. +R11 exposes retained v1 metadata and exact hash selection in both backtest forms. Catalog coverage is unknown and full content integrity is not verified by metadata inspection; the runner validates retained bytes before binding/execution. That R11 milestone was legacy/v1 only. R05 subsequently added a separate fully validated v2 canonical picker and retained-input runner. Legacy source requests retain their original asynchronous behavior and economics qualifications; new canonical source preparation follows the before-admission sequence above. ## Review clarifications diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index 99f34df7..563b2313 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -1,6 +1,6 @@ # Canonical development backlog -**First thirty-four waves committed; R05 explicit source-export preparation is validated and ready to commit.** R09 is committed as `06039d1`; **37 of 45 scheduled tasks are fully committed (82% by count)**. Full R05 remains partial, and R07 retains its paused table measurement. +**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. ## One source of truth diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index e463d21d..810ca2a0 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -1,14 +1,14 @@ { "schema_version": 1, - "plan_revision": "2026-10-24.72", + "plan_revision": "2026-10-24.73", "repository_base": "b7aeca4", - "plan_status": "thirty_fifth_wave_validated_awaiting_commit", + "plan_status": "thirty_sixth_wave_validated_awaiting_commit", "execution_authorized": true, "execution_scope": { - "authorized_by": "User: commit and continue; accepted R09 committed 06039d17bac7220d8504e68d1d4f66896eb13b91", + "authorized_by": "User: how far in backlog, commit and continue; wave35 accepted and committed 366bee810b8c1881172fe5553a1a61a2242ffbe5", "tasks": ["R05"], "permissions": [ - "R05 partial explicit source-export web preparation: read-only normalization preview, exact content-addressed retention and existing canonical dataset selection." + "R05 explicit stored EOD intraday source materialization before existing retained-data admission; reuse source preview/retention and canonical setup, no inferred metadata." ], "excluded": [ "performance_profiling_or_optimization", @@ -1304,33 +1304,36 @@ "Explicit owner disposition of the simultaneous multi-asset mark/risk policy before canonical default activation" ], "integration_state": "partial_validated_uncommitted", - "integration_base": "06039d17bac7220d8504e68d1d4f66896eb13b91", + "integration_base": "366bee810b8c1881172fe5553a1a61a2242ffbe5", "worktree": "/home/boki/repos/stock-bot", "implementation_slices": [ { "owner": "/root/r12_backend", - "worktree": "/tmp/stock-bot-wave35.fQycky/backend", - "scope": "Preparation routes/service, shared retention and existing eligibility reuse, focused integration/PostgreSQL tests" + "worktree": "/tmp/stock-bot-wave36.3Ntmmj/backend", + "scope": "Existing metadata validator export, request-local stored EOD adapter/routes and focused integration/PostgreSQL tests" }, { "owner": "/root/r12_frontend", - "worktree": "/tmp/stock-bot-wave35.fQycky/frontend", - "scope": "Canonical setup source-file panel, existing API client, focused UI tests" + "worktree": "/tmp/stock-bot-wave36.3Ntmmj/frontend", + "scope": "Stored metadata input mode in existing preparation panel/client; strict response capture and state/retry regressions" }, { "owner": "/root", - "scope": "Shared DTO, actual native browser lifecycle, integrated gates and planning" + "scope": "Shared DTO, actual adapter/native browser proof, combined gates and deliberate before-admission planning simplification" } ], "reviewed_by": "/root/r04_review", - "verification_reference": "ROADMAP.md#thirty-fifth-wave-handoff--2026-10-24", - "review_notes": "Independent exact-source review accepted explicit source-export preparation component; all integrated gates pass. Existing retained execution remains; full R05 remains partial for provider-query preparation/first binding and broader cutover. No inferred source evidence or activation.", - "partial_commit": "618fb9e33cebc1fde4869eb1f975a12c55bd9b94", - "execution_component": "Explicit source-export JSON preview and content-addressed retention through the existing web canonical setup", + "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", + "execution_component": "Explicit stored EOD intraday metadata + raw bars materialized once before existing content retention and canonical admission", "component_exclusions": [ - "No automatic provider-query preparation, durable pending source request/first-run binding, default or multiasset activation; source metadata is supplied evidence, not independently certified.", - "Performance and AI/paper/live activation remain paused or separately gated." - ] + "No default/multiasset/candidate/AI/paper/live activation, new run kind, SQL/runner mutation, source-query receipt or scheduler.", + "Source-query-inside-run proposal intentionally superseded by prepare-and-retain before canonical admission; not claimed implemented.", + "Stored-source scope1m/5m/1h EOD raw interval-start and explicitly assumed interval-end availability. No daily/QuestDB/auto/synthetic path or inferred evidence.", + "Performance and R07 measurement remain paused." + ], + "source_preparation_disposition": "Canonical source inputs are materialized, reviewed and retained before admission. Existing atomic request/hash admission and worker binding verification remain authoritative. This replaces earlier pending-query/fenced-first-binding work with fewer states and no loss of frozen-input correctness; wider cutover remains incomplete." }, { "id": "R06", @@ -3379,7 +3382,7 @@ "files": 1153, "scope": "Tracked and nonignored untracked file paths/content, including dirty changes; generated ignored artifacts excluded." }, - "workload": "1k/10k total bars;1asset/1owner or10assets/2owners;2fresh processes ×2fresh native sessions, second reverses callback evaluation. Alternating unit targets,1% fee,initialcapital1000000,600bars/session with retained gaps. No randomness, storage, queue, indicators or parallel simulation.", + "workload": "1k/10k total bars;1asset/1owner or10assets/2owners;2fresh processes \u00d72fresh native sessions, second reverses callback evaluation. Alternating unit targets,1% fee,initialcapital1000000,600bars/session with retained gaps. No randomness, storage, queue, indicators or parallel simulation.", "equality": "Exact complete normalized result hashes match every repeat and debug/release profile. Independent integer-cent cash/equity/remaining basis/owner fees/fill count oracle passes. Economically different results invalidate measurement.", "timing": "Report separates imports, detached D01 verify, once-per-child prepared-JS mapping, fresh native load, actual advance/submit/decision/finalize and validation/hash. Native call timers include JS encoding/schema/immutable projection plus Rust work/serialization, not pure crossing cost. Trial wall includes load+replay+finalization+oracle/hash, excludes one-time preparation/import and parent aggregation. No explicit warmup or OS-cache flush; means only, not latency distributions. Shared host; release focused checks briefly overlapped initial measurement, so not an isolated performance SLA.", "workloads": [ @@ -5266,7 +5269,7 @@ "Two separate processes per mode, two fresh timed sessions each, counterbalanced mode order. Second SMA session reverses owner callback order and must preserve financial and diagnostic hashes. This checks fresh whole-attempt recomputation, not native checkpoint resume.", "Shared host, no timing assertion, confidence interval, cold-start SLA, or cross-artifact performance attribution. Root must freeze source and use the matching release addon before execution." ], - "interpretation": "Verified aggregate host/strategy/state overhead, not per-function attribution. Long-window decision phase is about51–62%of total owner-dense wall. Profiles in P08 must distinguish schema parsing, copying/freezing, trailing calculations and allocation before optimization. No cross-shape scaling or S02 speedup claim." + "interpretation": "Verified aggregate host/strategy/state overhead, not per-function attribution. Long-window decision phase is about51\u201362%of total owner-dense wall. Profiles in P08 must distinguish schema parsing, copying/freezing, trailing calculations and allocation before optimization. No cross-shape scaling or S02 speedup claim." }, "cleanup": { "stopped_exact_containers": [ @@ -7064,10 +7067,10 @@ "thirty_first_wave_notes": [ "Walk-forward only: cost scenarios change financial-policy admission and stay a separate next slice. No template mutation or cost-as-strategy-parameter workaround.", "Focused research_walk_forwards header plus train-root membership columns; every member remains an existing standalone chronological validation. Avoid overloading first-window cancellation.", - "Freeze 2–10 recipes/common source/grid/build/policies before any execution; total promised training plus future holdouts<=100. Nondecreasing training starts, strictly increasing train cutoffs and previous test.end<=next validation.start.", + "Freeze 2\u201310 recipes/common source/grid/build/policies before any execution; total promised training plus future holdouts<=100. Nondecreasing training starts, strictly increasing train cutoffs and previous test.end<=next validation.start.", "Atomic all-training admission with exact deferred membership/run/outbox guards. Existing member select/finalize/retry paths reused; no scheduler or automatic advancement.", "Historical series finalization verifies full canonical evidence and every sealed member report, copying ordered validation/test reset segments without compounding or new analytics. Accepted receipts replay before current eligibility.", - "Whole-series cancellation propagates downward to every member; local member cancellation remains local and blocks series completion. SQL22–24 files remain unchanged.", + "Whole-series cancellation propagates downward to every member; local member cancellation remains local and blocks series completion. SQL22\u201324 files remain unchanged.", "Performance remains paused. Full R08 stays partial for cost sensitivity; R09 and candidate/AI/multi-asset/default/trading activation gates unchanged." ], "thirty_first_wave_validation": { @@ -7173,7 +7176,7 @@ "note": "Unchanged financial engine. Release restored before final PostgreSQL and browser suites." }, "limits": [ - "2–10 explicit windows; at most 100 planned runs including both future holdouts per window.", + "2\u201310 explicit windows; at most 100 planned runs including both future holdouts per window.", "Deterministic registered built-ins and zero label horizon only; no trained models, candidate execution or AI authorization.", "Training may overlap earlier historical holdouts; frozen recipes and own-training-only selection do not certify globally unseen data.", "Separate reset-account validation/test segments, not compounded equity or averaged Sharpe/CAGR; execution completeness is not statistical adequacy.", @@ -7189,9 +7192,9 @@ "thirty_second_wave_base": "3ed7b98f7cf0e7e1da8f00fc990c3511bd875ce9", "thirty_second_wave_notes": [ "One existing research_experiments row with cost-sensitivity-preview/v1; no new table, run column, report lifecycle or scheduler.", - "Source is current approved template through ordinary empty-grid preview. Automatic unchanged-cost baseline plus1–99 explicit normalized distinct fee/slippage pairs; fixed parameters and every other financial/data/build policy.", + "Source is current approved template through ordinary empty-grid preview. Automatic unchanged-cost baseline plus1\u201399 explicit normalized distinct fee/slippage pairs; fixed parameters and every other financial/data/build policy.", "Existing Rust engine reruns each scenario; costs can change funding/fills/decisions. No adjusted-P&L shortcut, ranking or universal monotonicity claim.", - "SQL26 preserves v1 callable and old SQL22–25 files; one expected-request helper used by existing run/retry guards. All other ordinary/reproduction guards preserved.", + "SQL26 preserves v1 callable and old SQL22\u201325 files; one expected-request helper used by existing run/retry guards. All other ordinary/reproduction guards preserved.", "Web cost mode shares ordinary editor owner, list/detail/retry/history and exact receipt flow. Strict v1 chronological/walkforward decoders remain separate.", "R08 completion subject to native cost/funding/baseline parity, SQL/adversarial/upgrade, retry/reproduction and real browser gates. R09 also depends on partial R07; no blanket readiness claim.", "Performance and candidate/AI/multiasset/default/paper/live activation remain paused or gated." @@ -7278,7 +7281,7 @@ "frontend_archive": "/tmp/stock-bot-wave32.Dg3iwI/frontend-final.tar.gz", "frontend_archive_sha256": "d7eae27357a7c5bdcb55d051ab2f403ddf17c5b96953ed4a88b53873810a411e", "root": "Read-only integration review caught two missing SQL26 fixture-chain entries, corrected before final full gates. Shared DTO and actual native browser approved, including exact native financial policy/identity after template edits.", - "task_completion": "Reviewer checked all R08 acceptance across waves29–32; no completed-source selector, joint cost/window optimizer or trainable-model framework is required to close supported scope." + "task_completion": "Reviewer checked all R08 acceptance across waves29\u201332; no completed-source selector, joint cost/window optimizer or trainable-model framework is required to close supported scope." }, "engine": { "debug_sha256": "75e33ffdd1e2738537879e62243a9d8f63665864835a58c46087bb4b78f274ff", @@ -7286,8 +7289,8 @@ "note": "Existing authoritative Rust engine unchanged; release restored before final database/browser gates." }, "limits": [ - "One current-approved saved template, fixed parameters and retained dataset; automatic original-cost baseline plus1–99 explicit normalized distinct fee/slippage pairs.", - "Template diagnostics only; not a completed-source-run study or heldout/OOS validation. No joint cost×parameter/window search, ranking or best-cost selection.", + "One current-approved saved template, fixed parameters and retained dataset; automatic original-cost baseline plus1\u201399 explicit normalized distinct fee/slippage pairs.", + "Template diagnostics only; not a completed-source-run study or heldout/OOS validation. No joint cost\u00d7parameter/window search, ranking or best-cost selection.", "Only feeRate and slippageRate vary. Spread, latency, participation, all other risk/capital/ownership, seed, package/build/data and analytics policy remain fixed.", "Costs can alter affordability, fills and future strategy decisions; no general monotonic-profit claim or TS adjusted-P&L calculation.", "Chronological/walk-forward models remain deterministic-unfitted with zero label horizon. Unsupported nonzero/missing horizon/trainable inputs reject; no purge/fitting infrastructure is claimed.", @@ -7397,7 +7400,7 @@ "Existing result/sample/phase/warmup/reset/cost display retained. Add one optional exact source to each immutable artifact revision, existing run/metric references unchanged.", "Source variants standalone experiment/chrono report/walk-forward report; no copied metric store or new API/entity. Omitted revision source preserves old; explicit null detaches new revision only.", "Same-client historical full retained-result verification, complete report/member facts, readonly snapshot reads; no current approval/build/cancel gate or operational row locks.", - "SQL27 additive nullable JSONB+source membership guard, existingSQL20/22–26 unchanged. Sources/results retain existing deletion guards.", + "SQL27 additive nullable JSONB+source membership guard, existingSQL20/22\u201326 unchanged. Sources/results retain existing deletion guards.", "Generic detail exposes optional server standalone boolean, absent fails closed for source action. Existing single-run finding behavior/ambiguous response handling remains.", "No retained as-of regime annotations exist; explicit unavailable counts/coverage. No classifier, inferred labels, current analytics API or fabricated sample counts.", "No performance, native financial changes, candidate/AI/default/multiasset/paper/live activation or new-wave commits/push/PR." @@ -7471,7 +7474,7 @@ }, { "command": "git diff --check; manifest references/dependency DAG; exact overlay/source SHA256 and historical SQL verification", - "result": "Passed: 55 unique task references, acyclic implementation DAG, 20 exact accepted agent files and all 30 integrated source hashes. SQL20/22–26 byte-for-byte unchanged." + "result": "Passed: 55 unique task references, acyclic implementation DAG, 20 exact accepted agent files and all 30 integrated source hashes. SQL20/22\u201326 byte-for-byte unchanged." } ], "review": { @@ -7508,7 +7511,7 @@ "completed_commit": "06039d17bac7220d8504e68d1d4f66896eb13b91" }, "thirty_fifth_wave_validation": { - "state": "validated_uncommitted", + "state": "validated_committed", "integration_base": "06039d17bac7220d8504e68d1d4f66896eb13b91", "log_directory": "/tmp/stock-bot-wave35.fQycky", "scope": "Partial R05 explicit source-export web normalization preview and content-addressed retention; existing canonical selection and Rust execution unchanged.", @@ -7571,7 +7574,7 @@ "frontend_archive_sha256": "f4136bb6e3cd8f8590c60cc623fdd2162eee30ffadbd7230a9fa456ecf2a5a44", "frontend": "Accepted all four exact integrated files. Focused45/166, combined existing/new UI132/662. New tests cover unknown-response exact retries, definitive rejection repair, source/parent stale responses, different-hash selection, disabled/save races and metadata display. Root strict affected-test check passes without the owner local inherited noUnusedParameters exception.", "root": "Shared DTO, web-only transport setting and fixture, actual existing native browser oracle extended with file preview/retention/reopen accepted. Focused browser1/119,15 unselected workflows skipped; actual >1MiB JSON consumption preserves identical normalized content and zero preview writes. Final full repository, database and browser suites passed on the frozen integrated source.", - "corrections": "Review closed same-event Retain→Clear retry-state loss, response parser unknown-field stripping/direct-source lineage gap, and distinguished definitive400/409 from uncertain retention. First browser failures were exact hash/overbroad calendar selectors; scoped visible metadata selectors fixed them with unchanged application behavior." + "corrections": "Review closed same-event Retain\u2192Clear retry-state loss, response parser unknown-field stripping/direct-source lineage gap, and distinguished definitive400/409 from uncertain retention. First browser failures were exact hash/overbroad calendar selectors; scoped visible metadata selectors fixed them with unchanged application behavior." }, "engine": { "debug_sha256": "75e33ffdd1e2738537879e62243a9d8f63665864835a58c46087bb4b78f274ff", @@ -7586,11 +7589,95 @@ "Existing mounted operator/service/admin and browser-origin authorization retained, including existing local AUTH_DISABLED development semantics. No new research-agent credentials.", "Performance/R07 measurement paused; candidate/AI/multiasset/paper/live/default activation gates unchanged." ], - "commits": "R09 committed06039d1 at owner request. Wave35 changes uncommitted; no push or PR.", + "commits": "Wave35 accepted and committed 366bee810b8c1881172fe5553a1a61a2242ffbe5 at owner request; no push or PR.", "fixture_cleanup": { "result": "Both exact disposable --rm containers stopped after final suites passed; development services untouched.", "postgres": "cd8467b474238ca03f14fc2a0d24a0ff9d400e87c5161957c78b5847f81e42c8", "redis": "3acb7f10faa1bfe77c0ca72fe58f5a2251770a73f8ed080fc9982571ab4f354d" + }, + "completed_commit": "366bee810b8c1881172fe5553a1a61a2242ffbe5" + }, + "thirty_sixth_wave_validation": { + "state": "validated_uncommitted", + "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.", + "source_archive": "/tmp/stock-bot-wave36.3Ntmmj/validated-source.tar.gz", + "source_archive_sha256": "0fd200ae1a1a27eb919ca7326ced5c9e89c25f1c4d729124b3386fd36ea5ea0d", + "source_hashes": { + "apps/stock/config/src/contracts/canonical-research.ts": "97532f726c37a8ab71bc98bb4c0f2f3e2fa182b1b6331eb45a8bfcc619d5a4e0", + "apps/stock/orchestrator/src/data/historical-dataset-v2.ts": "af17314b6fe2492199f4f2902bbd80247de9df71dd855dcc6f90cf7b19b9e456", + "apps/stock/web-api/src/routes/datasets.routes.ts": "034d2bf7c80deb3e96e4e2abeb306a5dbacbeef49c54f28bdd4d47ca0040678c", + "apps/stock/web-api/src/services/stored-dataset-preparation.ts": "1082fbbacc6c56cb6c8eded37d1cf1eb0cefff045d7537e42ac9aab874aa1699", + "apps/stock/web-app/src/features/backtest/components/DatasetPreparation.tsx": "202c92f0b8b8447ff08cad2a2a004cbb521306ab7e3e937b137a728b6b2c11cb", + "apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts": "885287eb8d73fdeb6c6641806187ae8016f7f1850699f95f7fb9656682fd0955", + "test/e2e/fixture.ts": "0c6348ad5a587596990b29fecb2f497eb0464b76074350c8fbe1b038156d9239", + "test/e2e/workbench.test.ts": "59a0ed6c3ca181d20acc72995616edb8e8cb1174bd4b17ec2467fc5c97a7927e", + "test/integration/dataset-source-preparation-ui.test.tsx": "5467eb7e41878450a3f56575d0bacc1d03e3073e51851218126a986488ab1a32", + "test/integration/stored-dataset-preparation.test.ts": "82dab9a017843597afb551cfab27adc466f7565e2f50ab9dd4d96ef61a701dc7", + "test/postgres/stored-dataset-preparation.test.ts": "4e5c9c19de219f6c25f153999a7ba78a9ac799bd7de3d7e6f62073da1d50858d" + }, + "commands": [ + { + "command": "CARGO_BUILD_JOBS=2 bun run check", + "log": "integration-check-final.log", + "result": "Passed build/secret audit/types/contracts/lint; 93 tooling, 43 utility, 44 calculation, 1126 integration and 150 Rust tests; zero failures. Four preexisting manual Rust cases remain ignored." + }, + { + "command": "bun run test:postgres", + "log": "integration-postgres-final.log", + "result": "Passed final release PostgreSQL/Redis: 242 tests /2196 assertions across29 files; zero failures." + }, + { + "command": "bun run test:e2e", + "log": "integration-browser-final.log", + "result": "Passed final production Chromium: 16 workflows /612 assertions; zero failures. Preserves export workflow and adds stored-source mutation/retention/native execution/reopen proof." + }, + { + "command": "Strict all affected/new test TypeScript; all eleven source/test files ESLint/Prettier", + "logs": [ + "root-tests-types-final.log", + "authored-lint-final.log", + "source-format-final.log" + ], + "result": "Passed without local exceptions." + }, + { + "command": "git diff --check; source/archive/native hashes; manifest task references/DAG", + "result": "Passed:11 frozen source hashes/archive/release native hash,55 unique task files and acyclic dependencies; SQL, Rust engine and backtest runner sources unchanged." + } + ], + "review": { + "independent_reviewer": "/root/r04_review", + "backend_archive": "/tmp/stock-bot-wave36.3Ntmmj/backend-final.tar", + "backend_archive_sha256": "41135c4e89589c528e4a213141dfc36bb591a752e48a3c6cc94ca0ef9270f3c6", + "backend": "Accepted five-file overlay. Focused integration/native/auth9/156; PostgreSQL2/39; compatibility42/423. Full source/scoped-test types, lint and format pass. Native-worker compatibility needed escalation after sandbox timeout; fully green rerun recorded, no test omitted.", + "frontend_archive": "/tmp/stock-bot-wave36.3Ntmmj/frontend-final.tar", + "frontend_archive_sha256": "56fa1a072537172e813a7c979b12b57f01be53b8752db4e1a49007b933da83da", + "frontend": "Accepted three-file overlay. Focused85/283; combined172/779; whole-app and scoped types/lint/format pass. Root strict affected-test check passes without owner local inherited noUnusedParameters exception.", + "root": "Shared DTO and existing native browser/fixture composition accepted. Focused1/141 pass,15 unselected workflows intentionally skipped; prior export flow preserved. Actual EOD StorageService uses test-only Mongo transport, not a second reader. Mutated store makes fresh preview hash differ; captured retention/retry and actual native economics/reopen remain unchanged, without requery.", + "notes": "No review source blocker. Thin metadata-validator export preserves existing semantics. Standard Response.json499 carries explicit no-store because Hono typed helper excludes499. Frontend final cleanup only replaced non-null prior-row assertion with fail-closed optional lookup.", + "planning": "Independent reviewer verified current before-admission contracts, 37 done + 2 partial + 6 blocked scheduled counts, final source/archive hashes and all validation log totals. Active R05 API/state wording was corrected; dated handoffs remain historical." + }, + "engine": { + "debug_sha256": "75e33ffdd1e2738537879e62243a9d8f63665864835a58c46087bb4b78f274ff", + "release_sha256": "ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103", + "note": "Rust/runner source unchanged; verified unchanged release restored after fullcheck before database/browser gates." + }, + "limits": [ + "One EOD raw1m/5m/1h interval-start execution series with explicitly assumed interval-end availability. No daily/QuestDB/auto/synthetic fallback or external provider request.", + "Calendar, action coverage, source revision and point-in-time universe remain operator declarations, not independently certified. Adapter sequence is sorted row ordinal, not vendor publication sequence; missing VWAP remains null.", + "Source preparation reads once and writes nothing. The complete returned input/hash is reused by existing retention; only a new explicit preview rereads mutable storage.", + "Prepare-and-retain before admission intentionally replaces old R05 pending-query/first-binding run proposal. Existing immutable admission/lease verification remains; no claim that deferred preparation was implemented.", + "Abort checked before and after reads and normalization; existing Mongo transport may finish its in-flight read after cancellation. No durable job or successful cancelled source response is created.", + "Real PostgreSQL/Redis and Chromium gates; Mongo transport is replaced for deterministic adapter tests. No real MongoDB-server conformance or actual vendor coverage certification claimed.", + "Full R05/default cutover and S06 remain incomplete; AI ADR007 and multiasset risk policy decisions remain gated. Performance/R07 measurement paused." + ], + "commits": "Wave35 committed366bee8 at owner request. Wave36 uncommitted; no push or PR.", + "fixture_cleanup": { + "result": "Both exact disposable --rm containers stopped after final suites passed; development services untouched.", + "postgres": "4589bf23f51696e5f77709b10c694e17cacde84809681ac31cc201ae3edb8b7c", + "redis": "9c85c66fb68a91a34affc3a3cc2d9f0ed86bd1fb3bb777e9ab35239f1da93439" } } } diff --git a/docs/development/backlog/tasks/R05.md b/docs/development/backlog/tasks/R05.md index bed4a7e8..1d9c645d 100644 --- a/docs/development/backlog/tasks/R05.md +++ b/docs/development/backlog/tasks/R05.md @@ -12,7 +12,7 @@ Scheduling source of truth: [manifest entry R05](../manifest.json). No task is a ## Intended behavior and implementation scope -Freeze strategy/model artifact IDs, parameters, seed, code/lockfile/build hashes and execution policies at submission. For a selected frozen dataset, pin its hash immediately; for a source request, retain the immutable query and atomically attach the first prepared dataset/hash before replay begins. Expose preparing versus reproducibility-finalized state. Wire the canonical Rust session with existing registered TS strategies into the durable runner and versioned result DTO. Exact reproduction API/UI is R12. +Freeze strategy/model artifact IDs, parameters, seed, code/lockfile/build hashes and execution policies at submission. For canonical research, prepare and retain source data before submission, then atomically pin its exact verified hash with the immutable run request. A preparation query is not a run or frozen dataset. Expose read-only preparation, retained data and admitted run as separate actions. This explicitly supersedes the original proposal for preparation inside an admitted run; see the 2026-10-24 disposition below. Wire the canonical Rust session with existing registered TS strategies into the durable runner and versioned result DTO. Exact reproduction API/UI is R12. Consume F08's additive canonical analytics/report contract here. Version the persisted/public projection so canonical fractions, genuine zero exposure and null reasons bypass legacy percentage conversion/placeholder suppression. Preserve owner books and distinguish fills from round trips. Additional position valuations needed by the UI must come from Rust or be explicitly unavailable; do not invent marks, average-price basis or unrealized P&L in TypeScript merely to satisfy the old DTO. Keep historical readers unchanged and prove reopen/render compatibility during this cutover. @@ -44,7 +44,7 @@ Parallel eligibility: only with disjoint actual files and reserved write locks; ## Acceptance criteria - Changing template, strategy source or provider history after dataset freezing cannot alter an admitted run. A source query alone is not labelled a frozen dataset. -- No strategy decision executes before artifact verification and atomic dataset binding; failed preparation remains diagnosed and retry-safe. +- No canonical run is admitted before source data is retained and verified; artifact verification and atomic dataset binding precede decisions. Failed preparation creates no run. Retention retries reuse captured input/hash, while an explicitly requested fresh source preview may observe changed provider history. - A retained-version/current-build mismatch rejects before execution; successful provenance identifies the executable that actually ran. Changing the current built-in implementation cannot silently change a retained version's behavior. - New results declare financialEngine=rust and strategyExecution separately; correctness-gate evidence requires approved engine/data gates, not a UI flag. - Before making canonical multi-asset research the default, obtain explicit owner disposition of sequential equal-time mark risk: either accept the disclosed versioned approximation or approve a coordinated atomic-mark policy/implementation with independent fixtures. F04/F05 currently evaluate each ordered mark; F06 demonstrates offsetting simultaneous moves can latch intermediate loss/drawdown halts. A passing deterministic replay suite alone does not resolve this material modeling issue. Single-asset component work and additive native integration need not wait for this decision. @@ -66,9 +66,9 @@ Keep migrations additive and previous results readable. Do not add a switch that ## Web/API contract and user states -- API: Run/results expose immutable request plus resolved dataset binding, provenance and preparation state. No exact-reproduce endpoint until R12. +- API: Preparation returns captured source input plus its normalized descriptor without creating a run. Retention verifies that input/hash; run/results expose the immutable request, retained dataset binding and provenance. Existing R12 owns exact reproduction. - Backend/data dependencies: Existing request_snapshot/dataset_hash/results extended with retained provenance and engine correctness-gate evidence metadata. -- Loading/error/empty behavior: API distinguishes preparing, dataset-pinned, running, failed and completed. W02/R11 render these fields without fabricated provenance. +- Loading/error/empty behavior: The preparation panel distinguishes reading, previewing, unavailable evidence, retaining and uncertain retention; exact captured retries preserve identity. Admitted runs keep the existing durable queued/running/terminal lifecycle. Preparation is not a run status. W02/R11 render retained evidence without fabricated provenance. - User-facing completion is demonstrated by the acceptance criteria and interaction tests above; a backend-only implementation is insufficient where a UI is in scope. ## Handoff @@ -121,3 +121,21 @@ The above slice is independently reviewed and `partial_validated_uncommitted` on Final gates: repository check 1077 integration /150 Rust plus93 tooling/43 utility/44 calculation tests; PostgreSQL240/2157; Chromium16/590; strict affected-test types, all16-file lint/format/hash/DAG/diff checks. Independent agent overlays and root browser/transport changes are accepted. Four prior manual Rust cases remain ignored. Logs/hashes/limits are in `manifest.json` → `thirty_fifth_wave_validation` and the [roadmap handoff](../../ROADMAP.md#thirty-fifth-wave-handoff--2026-10-24). Both disposable containers were removed. Full R05 stays `in_progress`: automatic provider-query preparation/first binding and default cutover are not delivered. No performance work or candidate/multiasset/paper/live/AI activation occurred. Changes await the next authorized commit. + +## Accepted export and stored-source continuation — 2026-10-24 + +Wave35 export preparation is accepted and committed as `366bee8`. Continue with operator metadata plus existing stored EOD intraday bars; one asset/series, raw1m/5m/1h, interval-start and explicit interval-end assumption only. Read through the actual request-local StorageService adapter without initialize/runtime mutation or provider fallback. Return complete captured input plus existing descriptor; the existing Retain action uses those exact bytes/hash. Source edits after preview affect only a new preview. + +**Deliberate simplification:** source preparation is completed before canonical admission. This replaces (does not claim to implement) the earlier pending-query run kind, preparing run phase and first-binding lifecycle. Existing admission already atomically freezes the full immutable request and verified retained hash; the worker checks them under its lease before executing. No second lifecycle is needed to satisfy reproducibility. Asynchronous preparation jobs require a demonstrated product need before reconsideration. + +Acceptance adds metadata/scope validation before IO; exact EOD routing, source identity and range; deterministic adapter ordinal (not provider sequence); no invented availability or VWAP; abort before/after reads; valid unavailable evidence preserved; source changes after materialization cannot alter retention/retry or native execution; fresh reads can change identity. Provider connection, missing range, invalid metadata and malformed stored data have distinct failure paths. Actual browser coverage retains the export path, loads EOD via existing adapter, edits underlying rows, and proves stored identity/economics survive save/run/reopen without requery. + +Full cutover/default activation remains incomplete, and S06 stays blocked. Daily/QuestDB preparation, v1 conversion, generalized query history, new SQL/runner states and performance work are excluded from this slice. Do not add optional adapters solely to avoid the remaining real owner policy decisions. + +## Validated stored-source handoff — 2026-10-24 + +The stored EOD component is independently reviewed and `partial_validated_uncommitted` on `366bee8`. One raw1m/5m/1h EOD source with complete explicit metadata can be materialized through the existing adapter, inspected and retained before unchanged canonical admission. Existing export mode remains. Source mutations after preview change only a fresh preview; retention/retry and actual Rust execution preserve captured bytes and expected economics. Unsupported or unknown evidence cannot become an executable selection. + +Final gates: fullcheck1126 integration/150 Rust (+93 tooling/43 utility/44 calculation); PostgreSQL242/2196; Chromium16/612; strict affected/new-test types and all11-file lint/format/hash/DAG/diff checks. Four preexisting Rust cases remain ignored. Both disposable containers removed. Exact evidence: `manifest.json` → `thirty_sixth_wave_validation`, [roadmap handoff](../../ROADMAP.md#thirty-sixth-wave-handoff--2026-10-24). + +The before-admission disposition above replaces deferred preparation rather than claiming to implement it. Full R05 stays `in_progress` for wider cutover/default policy; S06 remains blocked. Daily/QuestDB/v1 adapters are optional, not mandatory work to postpone owner decisions. No performance or AI/paper/live activation. New changes await the next authorized commit. diff --git a/test/e2e/fixture.ts b/test/e2e/fixture.ts index a7384b48..ce9c674e 100644 --- a/test/e2e/fixture.ts +++ b/test/e2e/fixture.ts @@ -39,6 +39,17 @@ import { seedBuiltinCatalog } from '../../scripts/seed-builtin-strategies'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); const logger = getLogger('browser-fixture'); +interface StoredEodBar { + eodSearchCode: string; + symbol: string; + exchange: string; + timestamp: number; + open: number; + high: number; + low: number; + close: number; + volume: number; +} export function gate() { let resolve!: () => void; const promise = new Promise(done => { @@ -395,7 +406,35 @@ export async function fixture(browser: Browser, native = false) { } }); cleanup.push(() => dispatcher.shutdown()); - const container = { postgres, logger } as IServiceContainer; + // Replace only Mongo transport; HTTP preparation exercises the real EOD + // StorageService adapter, while retained execution must never read it. + const storedEodBars = new Map(); + const storedSourceReads: { + collection: string; + filter: { eodSearchCode: string; timestamp: { $gte: number; $lt: number } }; + }[] = []; + const mongodb = { + async find( + collection: string, + filter: { eodSearchCode: string; timestamp: { $gte: number; $lt: number } } + ) { + if (!['eodIntraday1M', 'eodIntraday5M', 'eodIntraday1H'].includes(collection)) { + throw new Error('Unexpected stored-source collection'); + } + storedSourceReads.push({ collection, filter: structuredClone(filter) }); + return structuredClone( + (storedEodBars.get(collection) ?? []) + .filter( + bar => + bar.eodSearchCode === filter.eodSearchCode && + bar.timestamp >= filter.timestamp.$gte && + bar.timestamp < filter.timestamp.$lt + ) + .sort((a, b) => a.timestamp - b.timestamp) + ); + }, + } as unknown as NonNullable; + const container = { postgres, mongodb, logger } as IServiceContainer; const token = randomUUID() + randomUUID(); const security = createHttpSecurity({ adminToken: token, @@ -602,6 +641,10 @@ export async function fixture(browser: Browser, native = false) { close, unexpectedNetwork, historicalDataReads, + storedSourceReads, + setStoredEodBars: (collection: string, bars: StoredEodBar[]) => { + storedEodBars.set(collection, structuredClone(bars)); + }, seedCatalog: () => seedBuiltinCatalog(new StrategyCatalogService(container)), }; } catch (error) { diff --git a/test/e2e/workbench.test.ts b/test/e2e/workbench.test.ts index cdc124d6..b8f01279 100644 --- a/test/e2e/workbench.test.ts +++ b/test/e2e/workbench.test.ts @@ -5,6 +5,7 @@ import { canonicalResearchSettingsSchema, type CanonicalDatasetPreparation, type CanonicalRunResult, + type CanonicalStoredSourcePreparation, } from '@stock-bot/stock-config/canonical-research'; import type { ChronologicalValidationActionResult, @@ -34,6 +35,7 @@ import type { ResearchArtifact, ResearchFindingSource, } from '@stock-bot/types'; +import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2'; import { retainResearchDataset } from '../../scripts/import-research-dataset'; import { canonicalSettings } from '../fixtures/canonical-research'; import { canonicalSmaFixture } from '../fixtures/canonical-sma'; @@ -2114,7 +2116,7 @@ test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_ f.page.on('dialog', dialog => void dialog.accept()); try { const oracle = canonicalSmaFixture(); - const retained = oracle.dataset.manifest; + let retained = oracle.dataset.manifest; const { calendars, series, executionSeries, bounds, universe, corporateActions } = retained; // Explicit synthetic source export, with the same reviewed next-open oracle. // The browser submits raw source rows; only the server normalizes/hashes them. @@ -2326,6 +2328,107 @@ test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_ expect(await f.page.getByLabel('Initial capital (USD)', { exact: true }).inputValue()).toBe( '10000' ); + // Materialize an actual stored EOD source through the same panel, then edit + // the mutable store. Retention and execution must keep the displayed bytes. + const storedMetadata = { + ...source.metadata, + series: source.metadata.series.map(series => ({ + ...series, + source: { provider: 'eod', revision: 'declared-browser-source-v1' }, + availability: 'interval-end-assumption' as const, + })), + }; + const storedRows = oracle.dataset.bars.map(bar => ({ + eodSearchCode: 'X0.US', + symbol: 'X0', + exchange: 'US', + timestamp: bar.intervalStart / 1000, + open: bar.open, + high: bar.high, + low: bar.low, + close: bar.close, + volume: bar.volume, + })); + f.setStoredEodBars('eodIntraday1M', storedRows); + await f.page.getByLabel('Dataset input', { exact: true }).selectOption('stored-eod'); + await f.page.getByLabel('Source metadata JSON', { exact: true }).setInputFiles({ + name: 'declared-stored-eod-metadata.json', + mimeType: 'application/json', + buffer: Buffer.from(JSON.stringify(storedMetadata)), + }); + const loadingStored = f.page.waitForResponse(response => + response.url().endsWith('/api/v2/datasets/canonical/stored-source') + ); + await f.page.getByRole('button', { name: 'Preview dataset', exact: true }).click(); + const storedResponse = await loadingStored; + expect(storedResponse.status()).toBe(200); + expect(storedResponse.headers()['cache-control']).toBe('no-store'); + expect(storedResponse.request().postDataJSON()).toEqual({ metadata: storedMetadata }); + const materialized = (await storedResponse.json()) as CanonicalStoredSourcePreparation; + expect(materialized.input.metadata).toEqual(storedMetadata); + expect(materialized.input.bars).toHaveLength(oracle.dataset.bars.length); + expect(materialized.input.bars.every(bar => bar.availableAt === undefined)).toBe(true); + const expectedStored = createDatasetV2(materialized.input); + expect(materialized.preparation.manifest).toEqual(expectedStored.manifest); + expect(expectedStored.bars).toEqual(oracle.dataset.bars); + expect(materialized.preparation.hash).not.toBe(retained.hash); + expect(f.storedSourceReads).toEqual([ + { + collection: 'eodIntraday1M', + filter: { + eodSearchCode: 'X0.US', + timestamp: { $gte: bounds.warmupStart / 1000, $lt: bounds.tradeEnd / 1000 }, + }, + }, + ]); + await visible(f.page, `Dataset hash: ${materialized.preparation.hash}`); + await visible(f.page, /Availability is explicitly assumed at interval end/); + expect(await preparationCounts()).toEqual({ datasets: 1, runs: 0, dispatch: 0 }); + // A fresh preview observes corrected provider history; the current UI + // preview and its retention payload must remain the previously captured one. + f.setStoredEodBars( + 'eodIntraday1M', + storedRows.map(row => ({ + ...row, + open: row.open + 100, + high: row.high + 100, + low: row.low + 100, + close: row.close + 100, + })) + ); + const refreshedSource = (await f.request('/api/v2/datasets/canonical/stored-source', 'POST', { + metadata: storedMetadata, + })) as CanonicalStoredSourcePreparation; + expect(refreshedSource.preparation.hash).not.toBe(materialized.preparation.hash); + expect(f.storedSourceReads).toHaveLength(2); + const retainingStored = f.page.waitForResponse(response => + response.url().endsWith('/api/v2/datasets/canonical/retain') + ); + await f.page.getByRole('button', { name: 'Retain dataset', exact: true }).click(); + const storedRetention = await retainingStored; + expect(storedRetention.status()).toBe(200); + const capturedRequest = storedRetention.request().postDataJSON(); + expect(capturedRequest).toEqual({ + input: materialized.input, + expectedHash: materialized.preparation.hash, + }); + expect(await storedRetention.json()).toEqual({ preparation: materialized.preparation }); + expect(await f.request('/api/v2/datasets/canonical/retain', 'POST', capturedRequest)).toEqual({ + preparation: materialized.preparation, + }); + expect(f.storedSourceReads).toHaveLength(2); + expect(await preparationCounts()).toEqual({ datasets: 2, runs: 0, dispatch: 0 }); + expect(await f.request(`/api/v2/backtests/${backtestId}`)).toEqual(templateBeforePreparation); + retained = expectedStored.manifest; + await until( + async () => + (await f.page.getByLabel('Canonical dataset', { exact: true }).inputValue()) === + retained.hash, + 'captured stored source selected for canonical execution' + ); + expect(await f.page.getByLabel('Initial capital (USD)', { exact: true }).inputValue()).toBe( + '10000' + ); await visible(f.page, new Date(retained.bounds.tradeStart).toISOString()); await visible(f.page, new Date(retained.bounds.tradeEnd).toISOString()); await f.page.getByLabel('Initial capital (USD)', { exact: true }).fill('10000'); @@ -2662,6 +2765,7 @@ test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_ ).toBe(run.id); expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(3); expect(f.historicalDataReads).toEqual([]); + expect(f.storedSourceReads).toHaveLength(2); expect(f.unexpectedNetwork).toEqual([]); } finally { await f.close(); diff --git a/test/integration/dataset-source-preparation-ui.test.tsx b/test/integration/dataset-source-preparation-ui.test.tsx index 7e204a64..91ffd860 100644 --- a/test/integration/dataset-source-preparation-ui.test.tsx +++ b/test/integration/dataset-source-preparation-ui.test.tsx @@ -5,8 +5,10 @@ import type { Root } from 'react-dom/client'; import type { CanonicalDatasetCatalogEntry, CanonicalDatasetPreparation, + CanonicalStoredSourcePreparation, } from '@stock-bot/stock-config/canonical-research'; import type { + HistoricalDatasetMetadataV2, StrategyParameterSchema, StrategyRecord, StrategyVersionPackage, @@ -15,6 +17,7 @@ import type { import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2'; import type { CreateBacktestRequest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2'; import { datasetInput } from '../fixtures/historical-v2/dataset'; +import { metadata as intradayMetadata, intradayResponse } from '../fixtures/intraday/eod'; const browser = new GlobalWindow({ url: 'http://localhost:5173' }); const keys = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT', 'ResizeObserver'] as const; @@ -24,6 +27,7 @@ let router: typeof import('react-router-dom'); let CanonicalSetup: typeof import('../../apps/stock/web-app/src/features/backtest/components/CanonicalSetup').CanonicalSetup; let DatasetPreparation: typeof import('../../apps/stock/web-app/src/features/backtest/components/DatasetPreparation').DatasetPreparation; let parseDatasetPreparation: typeof import('../../apps/stock/web-app/src/features/backtest/services/backtestApiV2').parseDatasetPreparation; +let parseStoredDatasetPreparation: typeof import('../../apps/stock/web-app/src/features/backtest/services/backtestApiV2').parseStoredDatasetPreparation; function confirmWith(value: () => boolean) { Object.defineProperty(browser, 'confirm', { configurable: true, writable: true, value }); } @@ -114,13 +118,13 @@ function upload(value: unknown = datasetInput(), name = 'source.json', read?: Pr if (read) { Object.defineProperty(file, 'text', { value: () => read }); } - Object.defineProperty(field('Source dataset JSON'), 'files', { + const label = + field('Dataset input').value === 'stored-eod' ? 'Source metadata JSON' : 'Source dataset JSON'; + Object.defineProperty(field(label), 'files', { configurable: true, value: [file], }); - field('Source dataset JSON').dispatchEvent( - new browser.Event('change', { bubbles: true }) as unknown as Event - ); + field(label).dispatchEvent(new browser.Event('change', { bubbles: true }) as unknown as Event); } async function mount(element: ReactElement) { root = createRoot(host); @@ -271,7 +275,7 @@ beforeAll(async () => { ({ DatasetPreparation } = await import( '../../apps/stock/web-app/src/features/backtest/components/DatasetPreparation' )); - ({ parseDatasetPreparation } = await import( + ({ parseDatasetPreparation, parseStoredDatasetPreparation } = await import( '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2' )); }); @@ -880,3 +884,445 @@ describe('canonical setup coordination', () => { expect(button('Save canonical setup').disabled).toBe(false); }); }); + +const storedPath = '/api/v2/datasets/canonical/stored-source'; +function storedFixture( + metadata: HistoricalDatasetMetadataV2 = intradayMetadata() +): CanonicalStoredSourcePreparation { + const input = { + metadata, + bars: intradayResponse().map((bar, sourceSequence) => ({ + seriesId: metadata.series[0]!.id, + timestamp: bar.timestamp * 1000, + sourceSequence, + open: bar.open, + high: bar.high, + low: bar.low, + close: bar.close, + volume: bar.volume, + })), + }; + const normalized = createDatasetV2(input); + const { calendars, series, executionSeries, bounds, universe, corporateActions } = + normalized.manifest; + return { + input: { + ...input, + metadata: { calendars, series, executionSeries, bounds, universe, corporateActions }, + }, + preparation: { + version: 'canonical-dataset-preparation/v1', + hash: normalized.manifest.hash, + manifest: normalized.manifest, + available: normalized.manifest.eligibility === 'eligible', + reason: + normalized.manifest.eligibility === 'eligible' + ? null + : 'Declared coverage is unavailable for execution', + }, + }; +} +const storedMetadata: HistoricalDatasetMetadataV2 = { + ...intradayMetadata(), + universe: { + ...intradayMetadata().universe, + selection: 'point-in-time', + asOf: intradayMetadata().bounds.warmupStart, + }, + corporateActions: intradayMetadata().corporateActions.map(item => ({ + ...item, + status: 'action-free', + })), +}; +const stored = storedFixture(storedMetadata); +async function storedPreview(value: CanonicalStoredSourcePreparation = stored) { + await flush(() => edit('Dataset input', 'stored-eod')); + await flush(() => upload(value.input.metadata, 'metadata.json')); + await flush(() => click('Preview dataset')); + await flush(() => reply(request(storedPath), value)); +} + +describe('stored source response contract', () => { + test('validates the captured complete input without inventing optional VWAP or availability', () => { + const result = parseStoredDatasetPreparation(stored, storedMetadata); + expect(result).toEqual(stored); + expect(result.input.bars.every(bar => !('vwap' in bar) && !('availableAt' in bar))).toBe(true); + }); + test('accepts the normalizer collection order while preserving all declared values', () => { + const base = intradayMetadata(); + const calendar = base.calendars[0]!; + const metadata: HistoricalDatasetMetadataV2 = { + ...base, + calendars: [ + { + ...calendar, + id: 'z-extra', + startDate: '2024-03-10', + sessions: [ + calendar.sessions[0]!, + { + date: '2024-03-10', + open: calendar.sessions[0]!.open - 86400000, + close: calendar.sessions[0]!.close - 86400000, + }, + ], + }, + calendar, + ], + corporateActions: base.corporateActions.map(item => ({ + ...item, + status: 'known-actions', + actions: [ + { effectiveAt: item.start + 1, kind: 'dividend', reference: 'z-later' }, + { effectiveAt: item.start, kind: 'split', reference: 'a-earlier' }, + ], + })), + }; + const result = storedFixture(metadata); + expect(result.input.metadata.calendars[0]!.id).toBe(calendar.id); + expect(parseStoredDatasetPreparation(result, metadata)).toEqual(result); + expect(metadata.calendars[0]!.id).toBe('z-extra'); + expect(metadata.corporateActions[0]!.actions[0]!.reference).toBe('z-later'); + }); + type Mutable = { -readonly [K in keyof T]: T[K] extends object ? Mutable : T[K] }; + const changes: { + name: string; + change: (value: Mutable) => unknown; + }[] = [ + { name: 'unknown envelope property', change: v => Object.assign(v, { certified: true }) }, + { name: 'unknown input property', change: v => Object.assign(v.input, { requestId: 'other' }) }, + { + name: 'unknown metadata property', + change: v => Object.assign(v.input.metadata, { certified: true }), + }, + { + name: 'unknown bar property', + change: v => Object.assign(v.input.bars[0]!, { instrumentId: 'wrong' }), + }, + { + name: 'invented availability', + change: v => Object.assign(v.input.bars[0]!, { availableAt: v.input.bars[0]!.timestamp }), + }, + { name: 'wrong preparation hash', change: v => (v.preparation.hash = 'a'.repeat(64)) }, + { name: 'wrong bar count', change: v => v.preparation.manifest.barCount++ }, + { name: 'wrong series identity', change: v => (v.input.bars[0]!.seriesId = 'another-series') }, + { name: 'wrong row ordinal', change: v => (v.input.bars[1]!.sourceSequence = 15) }, + { + name: 'duplicate timestamp', + change: v => (v.input.bars[1]!.timestamp = v.input.bars[0]!.timestamp), + }, + { + name: 'out-of-range timestamp', + change: v => (v.input.bars[0]!.timestamp = v.input.metadata.bounds.tradeEnd), + }, + { name: 'non-finite price', change: v => (v.input.bars[0]!.open = Infinity) }, + { name: 'malformed VWAP', change: v => (v.input.bars[0]!.vwap = -1) }, + { name: 'empty bars', change: v => (v.input.bars = []) }, + { + name: 'changed source revision', + change: v => (v.input.metadata.series[0]!.source.revision = 'unexpected revision'), + }, + { + name: 'changed manifest revision', + change: v => (v.preparation.manifest.calendars[0]!.revision = 'changed-calendar'), + }, + { + name: 'changed source provider', + change: v => (v.input.metadata.series[0]!.source.provider = 'questdb'), + }, + { + name: 'unsupported daily interval', + change: v => (v.input.metadata.series[0]!.interval = '1d'), + }, + { + name: 'unsupported adjusted prices', + change: v => (v.input.metadata.series[0]!.adjustment = 'provider-adjusted'), + }, + { + name: 'unsupported explicit availability', + change: v => (v.input.metadata.series[0]!.availability = 'explicit'), + }, + ]; + for (const { name, change } of changes) { + test(`rejects ${name}`, () => { + const value = structuredClone(stored) as Mutable; + change(value); + expect(() => parseStoredDatasetPreparation(value, storedMetadata)).toThrow(); + }); + } + test('rejects a valid response bound to different caller metadata', () => { + expect(() => + parseStoredDatasetPreparation(stored, { + ...storedMetadata, + bounds: { ...storedMetadata.bounds, tradeStart: storedMetadata.bounds.tradeStart + 1 }, + }) + ).toThrow(); + }); +}); + +describe('stored source panel', () => { + test('defaults to the existing export mode and selecting stored mode performs no IO', async () => { + await mountPanel(); + expect(field('Dataset input').value).toBe('export'); + await flush(() => edit('Dataset input', 'stored-eod')); + expect(field('Source metadata JSON')).toBeDefined(); + expect(host.textContent).toContain('No source metadata selected.'); + expect(host.textContent).toContain('not a vendor sequence'); + expect(host.textContent).toContain('not independently certified'); + expect(requests).toHaveLength(0); + expect(button('Preview dataset').disabled).toBe(true); + }); + test('stored preview sends only declared metadata, displays snapshot and retains returned full input without requery', async () => { + await mountPanel(); + await storedPreview(); + expect(requests.filter(item => item.path === storedPath)).toHaveLength(1); + expect(requests.find(item => item.path === storedPath)!.body).toEqual({ + metadata: stored.input.metadata, + }); + expect(host.textContent).toContain('Stored source: EOD'); + expect(host.textContent).toContain('FIXTURE.TEST / 5m'); + expect(host.textContent).toContain('2024-03-11T13:30:00.000Z'); + expect(host.textContent).toContain('2024-03-11T20:00:00.000Z'); + expect(host.textContent).toContain('Availability: interval-end-assumption'); + await flush(() => { + click('Retain dataset'); + click('Retain dataset'); + }); + const first = request(retainPath); + expect(first.body).toEqual({ input: stored.input, expectedHash: stored.preparation.hash }); + await flush(() => fail(first)); + expect(field('Dataset input').disabled).toBe(true); + expect(field('Source metadata JSON').disabled).toBe(true); + await flush(() => { + edit('Dataset input', 'export'); + upload({ replacement: true }); + }); + expect(field('Dataset input').value).toBe('stored-eod'); + expect(host.textContent).toContain('Selected metadata: metadata.json'); + await flush(() => click('Retry retaining same dataset')); + expect(request(retainPath).body).toEqual(first.body); + expect(requests.filter(item => item.path === storedPath)).toHaveLength(1); + expect(requests.filter(item => item.path === previewPath)).toHaveLength(0); + await flush(() => reply(request(retainPath), { preparation: stored.preparation })); + expect(retained).toEqual([{ hash: stored.preparation.hash, available: true }]); + expect(states.at(-1)).toEqual({ busy: false, blocking: false }); + }); + test('same-event retain then mode change cannot discard or retarget the captured snapshot', async () => { + await mountPanel(); + await storedPreview(); + await flush(() => { + click('Retain dataset'); + edit('Dataset input', 'export'); + click('Clear source preparation'); + }); + expect(request(retainPath).body).toEqual({ + input: stored.input, + expectedHash: stored.preparation.hash, + }); + expect(field('Dataset input').value).toBe('stored-eod'); + await flush(() => fail(request(retainPath))); + expect(button('Retry retaining same dataset').disabled).toBe(false); + confirmWith(() => false); + await flush(() => click('Clear source preparation')); + expect(field('Dataset input').disabled).toBe(true); + confirmWith(() => true); + await flush(() => click('Clear source preparation')); + await flush(() => edit('Dataset input', 'export')); + expect(field('Dataset input').value).toBe('export'); + expect(host.textContent).toContain('No source export selected.'); + }); + test('same-event mode change invalidates old retain and preview handlers', async () => { + await mountPanel(); + await storedPreview(); + await flush(() => { + edit('Dataset input', 'export'); + click('Retain dataset'); + click('Preview dataset'); + }); + expect(requests.filter(item => item.path === retainPath)).toHaveLength(0); + expect(requests.filter(item => item.path === previewPath)).toHaveLength(0); + expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull(); + }); + test('mode switching fences a late stored response and a late export response', async () => { + await mountPanel(); + await flush(() => edit('Dataset input', 'stored-eod')); + await flush(() => upload(storedMetadata)); + await flush(() => click('Preview dataset')); + const oldStored = request(storedPath); + await flush(() => edit('Dataset input', 'export')); + expect(oldStored.signal?.aborted).toBe(true); + await flush(() => reply(oldStored, stored)); + expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull(); + await flush(() => upload()); + await flush(() => click('Preview dataset')); + const oldExport = request(previewPath); + await flush(() => edit('Dataset input', 'stored-eod')); + await flush(() => reply(oldExport, { preparation })); + expect(host.textContent).toContain('No source metadata selected.'); + expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull(); + }); + test('mode switching fences a late file read', async () => { + await mountPanel(); + const read = deferred(); + await flush(() => upload({}, 'old-export.json', read.promise)); + await flush(() => edit('Dataset input', 'stored-eod')); + await flush(() => read.resolve(JSON.stringify(datasetInput()))); + expect(host.textContent).toContain('No source metadata selected.'); + expect(button('Preview dataset').disabled).toBe(true); + }); + test('file replacement fences the previous stored read without discarding the new file', async () => { + await mountPanel(); + await flush(() => edit('Dataset input', 'stored-eod')); + await flush(() => upload(storedMetadata)); + await flush(() => click('Preview dataset')); + const old = request(storedPath); + const next = { + ...storedMetadata, + universe: { ...storedMetadata.universe, revision: 'next declaration' }, + }; + await flush(() => upload(next, 'next.json')); + await flush(() => reply(old, stored)); + expect(host.textContent).toContain('Selected metadata: next.json'); + expect(button('Retain dataset').disabled).toBe(true); + await flush(() => click('Preview dataset')); + expect(request(storedPath).body).toEqual({ metadata: next }); + }); + test('explicit fresh preview replaces materialized data only after its response', async () => { + await mountPanel(); + await storedPreview(); + await flush(() => click('Preview dataset')); + expect(button('Retain dataset').disabled).toBe(true); + expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull(); + const input = { + ...stored.input, + bars: stored.input.bars.map(bar => ({ ...bar, volume: bar.volume + 1 })), + }; + const nextDataset = createDatasetV2(input); + const next = { + input, + preparation: { + ...stored.preparation, + hash: nextDataset.manifest.hash, + manifest: nextDataset.manifest, + }, + }; + await flush(() => reply(request(storedPath), next)); + await flush(() => click('Retain dataset')); + expect(request(retainPath).body).toEqual({ + input: next.input, + expectedHash: next.preparation.hash, + }); + expect(requests.filter(item => item.path === storedPath)).toHaveLength(2); + }); + for (const [status, message] of [ + [400, 'Unsupported metadata'], + [404, 'No stored bars'], + [503, 'EOD store unavailable'], + [500, 'Stored source unavailable'], + ] as const) { + test(`stored ${status} exposes repair or retry without retention`, async () => { + await mountPanel(); + await flush(() => edit('Dataset input', 'stored-eod')); + await flush(() => upload(storedMetadata)); + await flush(() => click('Preview dataset')); + await flush(() => reply(request(storedPath), { error: message }, status)); + expect(host.textContent).toContain(message); + expect(button('Preview dataset').disabled).toBe(false); + expect(button('Retain dataset').disabled).toBe(true); + expect(field('Source metadata JSON').disabled).toBe(false); + expect(retained).toHaveLength(0); + }); + } + test('malformed stored success fails closed and keeps the metadata draft available for retry', async () => { + await mountPanel(); + await flush(() => edit('Dataset input', 'stored-eod')); + await flush(() => upload(storedMetadata)); + await flush(() => click('Preview dataset')); + await flush(() => + reply(request(storedPath), { + input: { metadata: storedMetadata, bars: [] }, + preparation: stored.preparation, + }) + ); + expect(host.textContent).toContain('stored source response could not be verified'); + expect(host.textContent).toContain('Selected metadata: source.json'); + expect(button('Retain dataset').disabled).toBe(true); + expect(button('Preview dataset').disabled).toBe(false); + }); + test('stored exploratory evidence remains visible and retainable without canonical selection', async () => { + await mountPanel(); + const exploratory = storedFixture(); + await storedPreview(exploratory); + expect(host.textContent).toContain('Unavailable for canonical setup'); + expect(host.textContent).toContain('Universe: unknown'); + await flush(() => click('Retain dataset')); + await flush(() => reply(request(retainPath), { preparation: exploratory.preparation })); + expect(retained).toEqual([{ hash: exploratory.preparation.hash, available: false }]); + expect(states.at(-1)).toEqual({ busy: false, blocking: true }); + }); + test('unmount ignores stored materialization that completes after an aborted request', async () => { + await mountPanel(); + await flush(() => edit('Dataset input', 'stored-eod')); + await flush(() => upload(storedMetadata)); + await flush(() => click('Preview dataset')); + const old = request(storedPath); + await flush(() => root!.unmount()); + root = undefined; + await flush(() => reply(old, stored)); + expect(old.signal?.aborted).toBe(true); + expect(retained).toHaveLength(0); + expect(states.at(-1)).toEqual({ busy: false, blocking: false }); + }); + test('parent saves are synchronously blocked while stored source is pending; drafts remain intact', async () => { + let saves = 0; + await readySetup(async () => { + saves++; + }); + await flush(() => { + edit('Backtest name', 'Stored draft'); + edit('Fee rate', '0.02'); + edit('Dataset input', 'stored-eod'); + }); + await flush(() => { + upload(storedMetadata); + host + .querySelector('form')! + .dispatchEvent( + new browser.Event('submit', { bubbles: true, cancelable: true }) as unknown as Event + ); + }); + expect(saves).toBe(0); + expect(button('Save canonical setup').disabled).toBe(true); + await flush(() => click('Preview dataset')); + await flush(() => reply(request(storedPath), stored)); + expect(field('Backtest name').value).toBe('Stored draft'); + expect(field('Fee rate').value).toBe('0.02'); + expect(field('Canonical dataset').value).toBe(entry.hash); + await flush(() => click('Retain dataset')); + await flush(() => reply(request(retainPath), { preparation: stored.preparation })); + expect(field('Canonical dataset').value).toBe(stored.preparation.hash); + expect(saves).toBe(0); + expect(field('Fee rate').value).toBe('0.02'); + }); + test('authoritative parent reset fences late stored response and restores export mode', async () => { + const onSave = async () => {}; + await readySetup(onSave); + await flush(() => edit('Dataset input', 'stored-eod')); + await flush(() => upload(storedMetadata)); + await flush(() => click('Preview dataset')); + const old = request(storedPath); + await flush(() => + root!.render( + createElement( + router.MemoryRouter, + null, + createElement(CanonicalSetup, { backtest: { ...definition, name: 'Reset' }, onSave }) + ) + ) + ); + await flush(() => reply(old, stored)); + expect(field('Dataset input').value).toBe('export'); + expect(field('Backtest name').value).toBe('Reset'); + expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull(); + }); +}); diff --git a/test/integration/stored-dataset-preparation.test.ts b/test/integration/stored-dataset-preparation.test.ts new file mode 100644 index 00000000..58e81c76 --- /dev/null +++ b/test/integration/stored-dataset-preparation.test.ts @@ -0,0 +1,472 @@ +import { describe, expect, mock, test } from 'bun:test'; +import { Hono } from 'hono'; +import { createHttpSecurity } from '@stock-bot/di'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import type { IServiceContainer, MongoDBClient, QuestDBClient } from '@stock-bot/services'; +import { parseFinancialDecimal, type HistoricalDatasetMetadataV2 } from '@stock-bot/types'; +import { + NativeReplaySession, + prepareReplayLoad, + runReplayConformance, +} from '../../apps/stock/orchestrator/src/backtest/native-replay'; +import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2'; +import { + StorageService, + type HistoricalBar, +} from '../../apps/stock/orchestrator/src/services/StorageService'; +import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes'; +import { previewDatasetPreparation } from '../../apps/stock/web-api/src/services/dataset-preparation.service'; +import { prepareStoredDataset } from '../../apps/stock/web-api/src/services/stored-dataset-preparation'; +import { nativeReplayFixture } from '../fixtures/native-replay'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('stored-source-test'); +const token = 'stored-source-admin-fixture-not-a-real-secret'; +type Mutable = { -readonly [K in keyof T]: T[K] extends object ? Mutable : T[K] }; +type Row = { + symbol: string; + exchange: string; + eodSearchCode: string; + timestamp: number; + open: number; + high: number; + low: number; + close: number; + volume: number; +}; +function at(values: readonly T[], index = 0): T { + const value = values[index]; + if (value === undefined) { + throw new Error('Missing fixture row'); + } + return value; +} +function source(interval: '1m' | '5m' | '1h' = '1m') { + const f = nativeReplayFixture(3), + duration = { '1m': 60000, '5m': 300000, '1h': 3600000 }[interval]; + const { calendars, series, executionSeries, bounds, universe, corporateActions } = + f.dataset.manifest; + const metadata = structuredClone({ + calendars, + series, + executionSeries, + bounds, + universe, + corporateActions, + }) as Mutable; + const declared = at(metadata.series); + declared.interval = interval; + declared.source = { provider: 'eod', revision: 'operator-declared-source-v1' }; + declared.availability = 'interval-end-assumption'; + metadata.bounds.tradeStart = f.start + duration; + metadata.bounds.tradeEnd = f.start + 3 * duration; + at(metadata.corporateActions).end = metadata.bounds.tradeEnd; + const rows: Row[] = f.dataset.bars.map((bar, index) => ({ + symbol: 'X0', + exchange: 'US', + eodSearchCode: 'X0.US', + timestamp: (f.start + index * duration) / 1000, + open: bar.open, + high: bar.high, + low: bar.low, + close: bar.close, + volume: bar.volume, + })); + return { metadata, rows, f, duration }; +} +function fixture( + find: ( + collection: string, + filter: Record, + options: Record + ) => Promise = async () => source().rows, + mongoAvailable = true +) { + const query = mock(async () => { + throw new Error('Preparation must not reach PostgreSQL'); + }); + const read = mock(find); + const mongodb = mongoAvailable ? ({ find: read } as unknown as MongoDBClient) : undefined; + const questdb = { + query: mock(async () => { + throw new Error('Unexpected provider fallback'); + }), + } as unknown as QuestDBClient; + const container = { + logger, + mongodb, + questdb, + postgres: { query }, + } as unknown as IServiceContainer; + const app = new Hono(); + createHttpSecurity({ + adminToken: token, + serviceToken: 'stored-source-service-fixture-not-a-real-secret', + readToken: 'stored-source-read-fixture-not-a-real-secret', + environment: 'test', + browserSessions: true, + }).mount(app); + app.route('/', createDatasetRoutes(container)); + const request = (body: unknown, signal?: AbortSignal) => + app.request('/api/v2/datasets/canonical/stored-source', { + method: 'POST', + headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + signal, + }); + return { + request, + app, + read, + query, + questdb, + storage: new StorageService(container, mongodb, null, questdb), + container, + }; +} + +describe('stored EOD preparation', () => { + test('all supported intraday intervals use the actual strict EOD adapter once, exact UTC query bounds and unchanged raw observations', async () => { + for (const interval of ['1m', '5m', '1h'] as const) { + const input = source(interval); + const f = fixture(async () => [...input.rows].reverse()); + const reply = await f.request({ metadata: input.metadata }); + expect(reply.status).toBe(200); + expect(reply.headers.get('Cache-Control')).toBe('no-store'); + const body = await reply.json(); + expect(f.read).toHaveBeenCalledTimes(1); + expect(f.read.mock.calls[0]).toEqual([ + { '1m': 'eodIntraday1M', '5m': 'eodIntraday5M', '1h': 'eodIntraday1H' }[interval], + { + eodSearchCode: 'X0.US', + timestamp: { + $gte: input.metadata.bounds.warmupStart / 1000, + $lt: input.metadata.bounds.tradeEnd / 1000, + }, + }, + { + sort: { timestamp: 1 }, + projection: { + symbol: 1, + exchange: 1, + eodSearchCode: 1, + timestamp: 1, + open: 1, + high: 1, + low: 1, + close: 1, + volume: 1, + }, + }, + ]); + expect(body.input.metadata).toEqual(input.metadata); + expect(body.input.bars.map((bar: { sourceSequence: number }) => bar.sourceSequence)).toEqual([ + 0, 1, 2, + ]); + expect(body.input.bars.map((bar: { timestamp: number }) => bar.timestamp)).toEqual( + input.rows.map(row => row.timestamp * 1000) + ); + expect( + body.input.bars.every( + (bar: Record) => + !Object.hasOwn(bar, 'vwap') && !Object.hasOwn(bar, 'availableAt') + ) + ).toBe(true); + expect(body.preparation).toEqual(previewDatasetPreparation({ input: body.input })); + const normalized = createDatasetV2(body.input); + expect( + normalized.bars.every(bar => bar.vwap === null && bar.availableAt === bar.intervalEnd) + ).toBe(true); + expect(normalized.manifest.parentDatasetHash).toBeNull(); + expect(f.query).not.toHaveBeenCalled(); + expect(f.questdb.query).not.toHaveBeenCalled(); + } + }); + + test('complete metadata and supported scope reject before every provider read', async () => { + const f = fixture(); + const bodies: unknown[] = [ + null, + {}, + { metadata: {} }, + { metadata: source().metadata, extra: true }, + ]; + const changes: Array<(metadata: Mutable) => void> = [ + metadata => { + at(metadata.series).source.provider = 'auto'; + }, + metadata => { + at(metadata.series).source.provider = 'questdb'; + }, + metadata => { + at(metadata.series).source.revision = ''; + }, + metadata => { + at(metadata.series).interval = '15m'; + }, + metadata => { + at(metadata.series).interval = '1d'; + at(metadata.series).timestamp = 'session-date'; + }, + metadata => { + at(metadata.series).adjustment = 'provider-adjusted'; + }, + metadata => { + at(metadata.series).timestamp = 'interval-end'; + }, + metadata => { + at(metadata.series).availability = 'explicit'; + }, + metadata => { + metadata.corporateActions = []; + }, + metadata => { + at(metadata.calendars).timeZone = 'private-invalid-timezone'; + }, + metadata => { + metadata.bounds.tradeStart = metadata.bounds.tradeEnd; + }, + metadata => { + metadata.series.push({ ...at(metadata.series), id: 'X1.US:1m', instrumentId: 'X1.US' }); + metadata.executionSeries.push({ instrumentId: 'X1.US', seriesId: 'X1.US:1m' }); + metadata.universe.instrumentIds.push('X1.US'); + metadata.corporateActions.push({ ...at(metadata.corporateActions), instrumentId: 'X1.US' }); + }, + ]; + for (const change of changes) { + const { metadata } = source(); + change(metadata); + bodies.push({ metadata }); + } + for (const body of bodies) { + const reply = await f.request(body); + expect(reply.status).toBe(400); + expect(reply.headers.get('Cache-Control')).toBe('no-store'); + expect(await reply.text()).not.toContain('private-invalid-timezone'); + } + expect(f.read).not.toHaveBeenCalled(); + expect(f.query).not.toHaveBeenCalled(); + expect(f.questdb.query).not.toHaveBeenCalled(); + }); + + test('empty, unavailable, corrupt and transport failure cases stay distinct without fallback or private errors', async () => { + const body = { metadata: source().metadata }; + const cases: Array<[ReturnType, number]> = [ + [fixture(async () => []), 404], + [fixture(undefined, false), 503], + [ + fixture(async () => { + throw new Error('private database connection details'); + }), + 500, + ], + [ + fixture(async () => + source().rows.map((row, index) => (index === 0 ? { ...row, high: 0 } : row)) + ), + 500, + ], + [fixture(async () => source().rows.map(row => ({ ...row, exchange: 'WRONG' }))), 500], + [fixture(async () => [...source().rows, at(source().rows)]), 500], + ]; + for (const [f, status] of cases) { + const reply = await f.request(body); + expect(reply.status).toBe(status); + expect(reply.headers.get('Cache-Control')).toBe('no-store'); + expect(await reply.text()).not.toContain('private database connection details'); + expect(f.query).not.toHaveBeenCalled(); + expect(f.questdb.query).not.toHaveBeenCalled(); + } + }); + + test('valid unavailable declarations remain inspectable; partial intervals and declared session mismatches fail422', async () => { + const input = source(); + input.metadata.universe.selection = 'unknown'; + input.metadata.universe.asOf = null; + const reply = await fixture().request({ metadata: input.metadata }); + expect(reply.status).toBe(200); + expect((await reply.json()).preparation).toMatchObject({ + available: false, + manifest: { eligibility: 'exploratory' }, + }); + const partial = source(); + partial.metadata.bounds.tradeEnd -= 30000; + const partialReply = await fixture().request({ metadata: partial.metadata }); + expect(partialReply.status).toBe(422); + const wrongSession = source(); + at(at(wrongSession.metadata.calendars).sessions).open += 30000; + const sessionReply = await fixture().request({ metadata: wrongSession.metadata }); + expect(sessionReply.status).toBe(422); + expect(await sessionReply.text()).toContain('declared complete dataset metadata'); + }); + + test('metadata is detached and deeply frozen before await; later caller/store mutations cannot alter returned captured bytes', async () => { + const initial = source(), + expectedMetadata = structuredClone(initial.metadata); + let release: (() => void) | undefined; + const gate = new Promise(resolve => { + release = resolve; + }); + const f = fixture(async () => { + await gate; + return initial.rows; + }); + const promise = prepareStoredDataset( + { metadata: initial.metadata }, + f.storage, + new AbortController().signal + ); + expect(f.read).toHaveBeenCalledTimes(1); + at(initial.metadata.series).source.revision = 'later source revision'; + initial.metadata.bounds.tradeEnd += initial.duration; + if (!release) { + throw new Error('Missing fixture barrier'); + } + release(); + const prepared = await promise; + expect(prepared.input.metadata).toEqual(expectedMetadata); + expect(Object.isFrozen(prepared)).toBe(true); + expect(Object.isFrozen(prepared.input.metadata.calendars[0]?.sessions)).toBe(true); + expect(Object.isFrozen(prepared.input.bars[0])).toBe(true); + at(initial.rows).close = 10.5; + expect(prepared.input.bars[0]?.close).toBe(11); + expect(prepared.preparation).toEqual(previewDatasetPreparation({ input: prepared.input })); + }); + + test('initial and late cancellation return499 even when underlying Mongo finishes; cancelled calls write nothing', async () => { + const initial = new AbortController(); + initial.abort(new Error('private abort reason')); + const f = fixture(); + const early = await f.request({ metadata: source().metadata }, initial.signal); + expect(early.status).toBe(499); + expect(early.headers.get('Cache-Control')).toBe('no-store'); + expect(f.read).not.toHaveBeenCalled(); + const controller = new AbortController(); + let release: (() => void) | undefined; + const gate = new Promise(resolve => { + release = resolve; + }); + let entered: (() => void) | undefined; + const started = new Promise(resolve => { + entered = resolve; + }); + const slow = fixture(async () => { + entered?.(); + await gate; + return source().rows; + }); + const pending = slow.request({ metadata: source().metadata }, controller.signal); + await started; + controller.abort(new Error('private abort reason')); + if (!release) { + throw new Error('Missing fixture barrier'); + } + release(); + const late = await pending; + expect(late.status).toBe(499); + expect(late.headers.get('Cache-Control')).toBe('no-store'); + expect(await late.text()).not.toContain('private abort reason'); + expect(slow.read).toHaveBeenCalledTimes(1); + expect(slow.query).not.toHaveBeenCalled(); + }); + + test('the focused adapter independently refuses wrong source, symbol, interpolation and out-of-range rows', async () => { + const input = source(); + const f = fixture(); + const baseline = await f.storage.getHistoricalBars( + 'X0.US', + new Date(input.metadata.bounds.warmupStart), + new Date(input.metadata.bounds.tradeEnd), + '1m', + { adjustment: 'raw', timestamp: 'utc-instant' }, + undefined, + 'eod' + ); + const changes: Array<(row: HistoricalBar) => HistoricalBar> = [ + row => ({ ...row, source: 'questdb' }), + row => ({ ...row, symbol: 'WRONG.US' }), + row => ({ ...row, interpolated: true }), + row => ({ ...row, timestamp: new Date(input.metadata.bounds.tradeEnd) }), + ]; + for (const change of changes) { + await expect( + prepareStoredDataset( + { metadata: input.metadata }, + { getHistoricalBars: async () => [change(at(baseline))] }, + new AbortController().signal + ) + ).rejects.toThrow('inconsistent bar identity or range'); + } + }); + + test('actual stored adapter output preserves native next-open costs/equity and never reveals observations before interval end', async () => { + const input = source(), + f = fixture(async () => input.rows); + const captured = await prepareStoredDataset( + { metadata: input.metadata }, + f.storage, + new AbortController().signal + ); + const dataset = createDatasetV2(captured.input); + let decisions = 0; + const { result } = runReplayConformance( + new NativeReplaySession(prepareReplayLoad(dataset, input.f.config)), + (_owner, context, observations) => { + decisions++; + expect( + observations.every( + bar => bar.available_at === bar.interval_end && bar.available_at <= context.barrier.at + ) + ).toBe(true); + return context.barrier.at === input.f.start + input.f.minute + ? { + mode: 'target', + targets: [{ instrumentId: 'X0.US', quantity: parseFinancialDecimal('2') }], + } + : { mode: 'target', targets: [] }; + } + ); + expect(decisions).toBe(2); + expect(String(result.view.portfolio.cash)).toBe('9975.76000000'); + expect(String(result.view.equity)).toBe('10005.76000000'); + expect(result.view.portfolio.fees).toEqual([{ ownerId: 'A', amount: '0.24000000' }]); + }); + + test('mounted security denies read-token writes and untrusted browser origins', async () => { + const f = fixture(); + const payload = JSON.stringify({ metadata: source().metadata }); + const denied = await f.app.request('/api/v2/datasets/canonical/stored-source', { + method: 'POST', + headers: { + Authorization: 'Bearer stored-source-read-fixture-not-a-real-secret', + 'Content-Type': 'application/json', + }, + body: payload, + }); + expect(denied.status).toBe(403); + const login = await f.app.request('/api/auth/session', { + method: 'POST', + headers: { 'Content-Type': 'application/json', Origin: 'http://localhost' }, + body: JSON.stringify({ token }), + }); + const cookie = login.headers.get('Set-Cookie')?.split(';')[0]; + if (!cookie) { + throw new Error('Missing authenticated session'); + } + const browser = (origin?: string) => + f.app.request('/api/v2/datasets/canonical/stored-source', { + method: 'POST', + headers: { + Cookie: cookie, + 'Content-Type': 'application/json', + ...(origin ? { Origin: origin } : {}), + }, + body: payload, + }); + expect((await browser()).status).toBe(403); + expect((await browser('https://foreign.invalid')).status).toBe(403); + expect(f.read).not.toHaveBeenCalled(); + expect((await browser('http://localhost')).status).toBe(200); + expect(f.read).toHaveBeenCalledTimes(1); + }); +}); diff --git a/test/postgres/stored-dataset-preparation.test.ts b/test/postgres/stored-dataset-preparation.test.ts new file mode 100644 index 00000000..657814e4 --- /dev/null +++ b/test/postgres/stored-dataset-preparation.test.ts @@ -0,0 +1,276 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Hono } from 'hono'; +import { Pool } from 'pg'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient } from '@stock-bot/postgres'; +import type { MongoDBClient } from '@stock-bot/services'; +import type { CanonicalStoredSourcePreparation } from '@stock-bot/stock-config/canonical-research'; +import { + createDatasetV2, + validateDatasetV2, +} from '../../apps/stock/orchestrator/src/data/historical-dataset-v2'; +import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes'; +import { readCanonicalDataset } from '../../apps/stock/web-api/src/services/canonical-research.service'; +import { nativeReplayFixture } from '../fixtures/native-replay'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('stored-source-postgres'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const cleanup: Array<() => Promise> = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); +function at(values: readonly T[], index = 0): T { + const value = values[index]; + if (value === undefined) { + throw new Error('Missing fixture item'); + } + return value; +} +function source() { + const { dataset } = nativeReplayFixture(3); + const { calendars, series, executionSeries, bounds, universe, corporateActions } = + dataset.manifest; + const metadata = { + calendars, + series: series.map(value => ({ + ...value, + source: { provider: 'eod', revision: 'operator-declared-v1' }, + availability: 'interval-end-assumption' as const, + })), + executionSeries, + bounds, + universe, + corporateActions, + }; + const rows = dataset.bars.map(bar => ({ + symbol: 'X0', + exchange: 'US', + eodSearchCode: 'X0.US', + timestamp: bar.intervalStart / 1000, + open: bar.open, + high: bar.high, + low: bar.low, + close: bar.close, + volume: bar.volume, + })); + return { metadata, rows }; +} +async function fixture() { + if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Dedicated stock_bot_safety database required'); + } + const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; + const admin = new Pool({ connectionString: url }); + await admin.query(`CREATE SCHEMA ${schema}`); + const pool = new Pool({ + connectionString: url, + max: 4, + application_name: schema, + options: `-c search_path=${schema} -c statement_timeout=10000`, + }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + for (const name of [ + '06-create-backtest-tables.sql', + '08-create-runs-table.sql', + '09-backtest-run-contract.sql', + '10-durable-backtest-dispatch.sql', + '12-historical-datasets.sql', + '14-backtest-submission.sql', + '16-strategy-catalog.sql', + '17-research-retention.sql', + '18-backtest-strategy-versions.sql', + '19-canonical-research.sql', + '20-research-workspace.sql', + '21-run-reproduction.sql', + '22-experiments.sql', + '23-experiment-retries.sql', + '24-chronological-validation.sql', + '25-walk-forward.sql', + '26-cost-sensitivity.sql', + '27-research-evidence-sources.sql', + ]) { + await pool.query( + readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') + ); + } + await pool.query(`INSERT INTO backtests(name,strategy,symbols,start_date,end_date,initial_capital,config) + VALUES('untouched legacy draft','sma-crossover','["A.US"]','2024-03-01','2024-04-01',1000,'{"fastPeriod":2,"slowPeriod":3}')`); + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + let queryCount = 0; + Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); + Object.defineProperty(postgres, 'query', { + value: async (sql: string, values?: unknown[]) => { + queryCount++; + return pool.query(sql, values); + }, + }); + const input = source(); + let reads = 0; + const mongodb = { + async find() { + reads++; + return structuredClone(input.rows); + }, + } as unknown as MongoDBClient; + const routes = new Hono().route('/', createDatasetRoutes({ postgres, mongodb, logger })); + const post = (operation: 'stored-source' | 'preview' | 'retain', body: unknown) => + routes.request(`/api/v2/datasets/canonical/${operation}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }); + const snapshot = async (includeDatasets = true) => { + const tables = ( + await pool.query<{ tablename: string }>( + 'SELECT tablename FROM pg_tables WHERE schemaname=$1 ORDER BY tablename', + [schema] + ) + ).rows; + const rows: Record = {}; + for (const { tablename } of tables) { + if (includeDatasets || tablename !== 'backtest_datasets') { + rows[tablename] = ( + await pool.query( + `SELECT to_jsonb(t) AS row FROM "${tablename}" t ORDER BY to_jsonb(t)::text` + ) + ).rows; + } + } + return rows; + }; + const defaults = async () => + ( + await pool.query( + `SELECT table_name,column_name,column_default FROM information_schema.columns WHERE table_schema=$1 ORDER BY table_name,column_name`, + [schema] + ) + ).rows; + return { + input, + get reads() { + return reads; + }, + pool, + schema, + post, + routes, + snapshot, + defaults, + get queryCount() { + return queryCount; + }, + }; +} + +describe.skipIf(!url)('stored source materialization and immutable retention on PostgreSQL', () => { + test('source read writes nothing; edits after capture cannot change exact retention/retry, and a fresh read has a different identity', async () => { + const f = await fixture(); + const before = await f.snapshot(), + defaults = await f.defaults(); + const initial = await f.post('stored-source', { metadata: f.input.metadata }); + expect(initial.status).toBe(200); + expect(initial.headers.get('Cache-Control')).toBe('no-store'); + const captured = (await initial.json()) as CanonicalStoredSourcePreparation; + expect(f.reads).toBe(1); + expect(f.queryCount).toBe(0); + expect(await f.snapshot()).toEqual(before); + expect(captured.preparation.hash).toBe(createDatasetV2(captured.input).manifest.hash); + at(f.input.rows).close = 10.5; + const newer = await f.post('stored-source', { metadata: f.input.metadata }); + expect(newer.status).toBe(200); + const refreshed = (await newer.json()) as CanonicalStoredSourcePreparation; + expect(f.reads).toBe(2); + expect(refreshed.preparation.hash).not.toBe(captured.preparation.hash); + expect(at(refreshed.input.bars).close).toBe(10.5); + expect(at(captured.input.bars).close).toBe(11); + expect(await f.snapshot()).toEqual(before); + const retainBody = { input: captured.input, expectedHash: captured.preparation.hash }; + for (const response of await Promise.all([ + f.post('retain', retainBody), + f.post('retain', retainBody), + ])) { + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ preparation: captured.preparation }); + } + const rows = (await f.pool.query('SELECT * FROM backtest_datasets')).rows; + expect(rows).toHaveLength(1); + const saved = validateDatasetV2(at(rows).payload); + expect(saved).toEqual(createDatasetV2(captured.input)); + expect(saved.manifest.hash).toBe(captured.preparation.hash); + expect(saved.bars.every(bar => bar.vwap === null && bar.availableAt === bar.intervalEnd)).toBe( + true + ); + expect(f.reads).toBe(2); + const retry = await f.post('retain', retainBody); + expect(retry.status).toBe(200); + expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toEqual(rows); + expect(f.reads).toBe(2); + const lookup = await f.routes.request( + `/api/v2/datasets/canonical/${captured.preparation.hash}` + ); + expect((await lookup.json()).dataset).toMatchObject({ + available: true, + hash: captured.preparation.hash, + manifest: captured.preparation.manifest, + }); + expect(await readCanonicalDataset(f.pool, captured.preparation.hash)).toEqual(saved); + const { backtest_datasets: _datasets, ...untouched } = before; + expect(await f.snapshot(false)).toEqual(untouched); + expect(await f.defaults()).toEqual(defaults); + expect((await f.pool.query('SELECT count(*) AS n FROM runs')).rows).toEqual([{ n: '0' }]); + expect((await f.pool.query('SELECT count(*) AS n FROM backtest_dispatch')).rows).toEqual([ + { n: '0' }, + ]); + }); + + test('stored previews cannot bypass scope/hash validation or overwrite corrupt retained custody', async () => { + const f = await fixture(); + const initial = await f.post('stored-source', { metadata: f.input.metadata }); + const captured = (await initial.json()) as CanonicalStoredSourcePreparation; + const before = await f.snapshot(); + const wrong = { + ...f.input.metadata, + series: f.input.metadata.series.map(value => ({ + ...value, + source: { ...value.source, provider: 'auto' }, + })), + }; + expect((await f.post('stored-source', { metadata: wrong })).status).toBe(400); + expect(f.reads).toBe(1); + expect( + (await f.post('retain', { input: captured.input, expectedHash: '0'.repeat(64) })).status + ).toBe(409); + expect(await f.snapshot()).toEqual(before); + const dataset = createDatasetV2(captured.input); + const corrupt = { + ...dataset, + bars: dataset.bars.map((bar, index) => (index === 0 ? { ...bar, close: 10.5 } : bar)), + }; + expect(corrupt).not.toEqual(dataset); + await f.pool.query('INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2)', [ + dataset.manifest.hash, + corrupt, + ]); + const damaged = await f.snapshot(); + const response = await f.post('retain', { + input: captured.input, + expectedHash: captured.preparation.hash, + }); + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ error: 'Source dataset retention unavailable' }); + expect(await f.snapshot()).toEqual(damaged); + expect(f.reads).toBe(1); + }); +});