feat(research): inspect scoped stored market data (RP01)

This commit is contained in:
Boki 2026-10-27 00:25:19 -04:00
parent b4ac6460ef
commit 5bfaf37d08
12 changed files with 1592 additions and 3 deletions

View file

@ -64,6 +64,10 @@
"./paper-deployments": {
"types": "./dist/contracts/paper-deployments.d.ts",
"import": "./dist/contracts/paper-deployments.js"
},
"./stored-source": {
"types": "./dist/contracts/stored-source.d.ts",
"default": "./dist/contracts/stored-source.js"
}
},
"scripts": {

View file

@ -0,0 +1,89 @@
/** Read-only source diagnostics. These do not certify a dataset or retain source evidence. */
import { z } from 'zod';
import { parseInstrumentId } from '@stock-bot/types';
const count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
const instant = z.number().int().nonnegative().max(8_640_000_000_000_000);
export const storedSourceIntervalSchema = z.enum(['1m', '5m', '1h']);
const instrument = z.string().refine(value => {
try {
return parseInstrumentId(value).id === value;
} catch {
return false;
}
}, 'Expected a provider instrument identity, for example AAPL.US');
export const storedSourceSelectionSchema = z
.object({ instrumentId: instrument, interval: storedSourceIntervalSchema })
.strict();
export type StoredSourceSelection = z.infer<typeof storedSourceSelectionSchema>;
export const storedSourceQuerySchema = storedSourceSelectionSchema
.extend({
start: instant,
end: instant,
})
.strict()
.refine(value => value.start < value.end, 'End must be after start');
export type StoredSourceQuery = z.infer<typeof storedSourceQuerySchema>;
export const storedSourceCoverageSchema = z
.object({
version: z.literal('stored-eod-coverage/v1'),
observedAt: instant,
query: storedSourceSelectionSchema,
series: z
.array(
z
.object({
instrumentId: instrument,
interval: storedSourceIntervalSchema,
rowCount: count,
firstTimestamp: instant.nullable(),
lastTimestamp: instant.nullable(),
invalidTimestampRows: count,
})
.strict()
)
.max(1),
})
.strict();
export type StoredSourceCoverage = z.infer<typeof storedSourceCoverageSchema>;
export const storedSourceIssueSchema = z.enum([
'identity-mismatch',
'invalid-timestamp',
'outside-range',
'invalid-prices',
'null-volume',
'invalid-volume',
'duplicate-timestamp',
]);
export const storedSourceInspectionSchema = z
.object({
version: z.literal('stored-eod-inspection/v1'),
observedAt: instant,
query: storedSourceQuerySchema,
rowCount: count,
invalidRows: count,
nullVolumeRows: count,
duplicateRows: count,
firstTimestamp: instant.nullable(),
lastTimestamp: instant.nullable(),
days: z.array(
z
.object({
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
rowCount: count,
invalidRows: count,
})
.strict()
),
issues: z.array(
z
.object({
code: storedSourceIssueSchema,
rowCount: count,
timestamps: z.array(instant.nullable()),
})
.strict()
),
})
.strict();
export type StoredSourceInspection = z.infer<typeof storedSourceInspectionSchema>;

View file

@ -14,6 +14,11 @@ import {
prepareStoredDataset,
StoredDatasetPreparationError,
} from '../services/stored-dataset-preparation';
import {
inspectStoredSource,
storedSourceCoverage,
StoredSourceInspectionError,
} from '../services/stored-source-inspection';
const logger = getLogger('dataset-catalog-routes');
@ -28,6 +33,47 @@ export function createDatasetRoutes(container: IServiceContainer) {
throw new DatasetPreparationError(400, 'Invalid JSON request');
}
};
app.get('/api/v2/datasets/stored-eod/coverage', async c => {
c.header('Cache-Control', 'no-store');
try {
return c.json(await storedSourceCoverage(container.mongodb, c.req.query(), c.req.raw.signal));
} catch (error) {
if (c.req.raw.signal.aborted) {
return Response.json(
{ error: 'Stored source inspection cancelled' },
{ status: 499, headers: { 'Cache-Control': 'no-store' } }
);
}
if (error instanceof StoredSourceInspectionError) {
return c.json({ error: error.message }, error.status);
}
logger.error('Failed to inspect stored source coverage', error);
return c.json({ error: 'Stored source coverage unavailable' }, 500);
}
});
app.post('/api/v2/datasets/stored-eod/inspect', async c => {
c.header('Cache-Control', 'no-store');
try {
return c.json(
await inspectStoredSource(container.mongodb, await readBody(c.req.raw), c.req.raw.signal)
);
} catch (error) {
if (c.req.raw.signal.aborted) {
return Response.json(
{ error: 'Stored source inspection cancelled' },
{ status: 499, headers: { 'Cache-Control': 'no-store' } }
);
}
if (
error instanceof StoredSourceInspectionError ||
error instanceof DatasetPreparationError
) {
return c.json({ error: error.message }, error.status);
}
logger.error('Failed to inspect stored source quality', error);
return c.json({ error: 'Stored source inspection unavailable' }, 500);
}
});
app.post('/api/v2/datasets/canonical/stored-source', async c => {
c.header('Cache-Control', 'no-store');
try {

View file

@ -0,0 +1,269 @@
import type { MongoDBClient } from '@stock-bot/services';
import {
storedSourceCoverageSchema,
storedSourceInspectionSchema,
storedSourceQuerySchema,
storedSourceSelectionSchema,
type StoredSourceCoverage,
type StoredSourceInspection,
} from '@stock-bot/stock-config/stored-source';
import { parseInstrumentId } from '@stock-bot/types';
import {
PREPARATION_BATCH_SIZE,
preparationCheckpoint,
} from '../../../orchestrator/src/data/preparation';
const collections = {
'1m': 'eodIntraday1M',
'5m': 'eodIntraday5M',
'1h': 'eodIntraday1H',
} as const;
type Store = Pick<MongoDBClient, 'find' | 'aggregate'>;
type Row = Record<string, unknown>;
type Code = StoredSourceInspection['issues'][number]['code'];
export class StoredSourceInspectionError extends Error {
constructor(
readonly status: 400 | 503,
message: string
) {
super(message);
}
}
function required(store: Store | null | undefined): Store {
if (!store) {
throw new StoredSourceInspectionError(503, 'Stored EOD data is unavailable');
}
return store;
}
function timestamp(value: unknown): number | null {
return typeof value === 'number' &&
Number.isSafeInteger(value) &&
value >= 0 &&
Number.isSafeInteger(value * 1000) &&
Number.isFinite(new Date(value * 1000).getTime())
? value * 1000
: null;
}
/** Inspect one indexed source series; first/last rows do not establish complete sessions. */
export async function storedSourceCoverage(
store: Store | null | undefined,
input: unknown,
signal: AbortSignal
): Promise<StoredSourceCoverage> {
signal.throwIfAborted();
const parsed = storedSourceSelectionSchema.safeParse(input);
if (!parsed.success) {
throw new StoredSourceInspectionError(
400,
'Select one qualified instrument and supported timeframe'
);
}
const query = parsed.data;
const groups = await required(store).aggregate<Row>(collections[query.interval], [
{ $match: { eodSearchCode: query.instrumentId } },
{
$project: {
_id: 0,
validTimestamp: {
$cond: [
// Decimal128 remains an object in the JS reader. Only these BSON types
// can become its finite integer Unix-seconds number.
{ $in: [{ $type: '$timestamp' }, ['double', 'int', 'long']] },
{
$cond: [
{
$and: [
{ $gte: ['$timestamp', 0] },
{ $lte: ['$timestamp', 8_640_000_000_000] },
{ $eq: ['$timestamp', { $trunc: '$timestamp' }] },
],
},
'$timestamp',
null,
],
},
null,
],
},
},
},
{
$group: {
_id: null,
rowCount: { $sum: 1 },
firstTimestamp: { $min: '$validTimestamp' },
lastTimestamp: { $max: '$validTimestamp' },
invalidTimestampRows: { $sum: { $cond: [{ $eq: ['$validTimestamp', null] }, 1, 0] } },
},
},
]);
signal.throwIfAborted();
const series = groups.map(group => {
if (
!Number.isSafeInteger(group.rowCount) ||
Number(group.rowCount) < 0 ||
!Number.isSafeInteger(group.invalidTimestampRows) ||
Number(group.invalidTimestampRows) < 0 ||
Number(group.invalidTimestampRows) > Number(group.rowCount)
) {
throw new Error('Invalid stored source coverage');
}
return {
...query,
rowCount: Number(group.rowCount),
firstTimestamp: timestamp(group.firstTimestamp),
lastTimestamp: timestamp(group.lastTimestamp),
invalidTimestampRows: Number(group.invalidTimestampRows),
};
});
return storedSourceCoverageSchema.parse({
version: 'stored-eod-coverage/v1',
observedAt: Date.now(),
query,
series,
});
}
/** Explain raw field problems without changing rows or making financial eligibility decisions. */
export async function inspectStoredSource(
store: Store | null | undefined,
input: unknown,
signal: AbortSignal
): Promise<StoredSourceInspection> {
signal.throwIfAborted();
const parsed = storedSourceQuerySchema.safeParse(input);
if (!parsed.success) {
throw new StoredSourceInspectionError(
400,
'Select an instrument, supported timeframe and valid UTC start/end range'
);
}
const query = parsed.data;
const identity = parseInstrumentId(query.instrumentId);
const rows = await required(store).find<Row>(
collections[query.interval],
{
eodSearchCode: identity.id,
timestamp: { $gte: query.start / 1000, $lt: query.end / 1000 },
},
{
sort: { timestamp: 1 },
projection: {
_id: 0,
eodSearchCode: 1,
symbol: 1,
exchange: 1,
timestamp: 1,
open: 1,
high: 1,
low: 1,
close: 1,
volume: 1,
},
}
);
signal.throwIfAborted();
const bad = new Set<number>();
const issues = new Map<Code, { rowCount: number; timestamps: Array<number | null> }>();
const byTimestamp = new Map<number, number[]>();
const instants: Array<number | null> = [];
const issue = (code: Code, index: number, at: number | null) => {
bad.add(index);
const existing = issues.get(code) ?? { rowCount: 0, timestamps: [] };
existing.rowCount++;
existing.timestamps.push(at);
issues.set(code, existing);
};
const numeric = (value: unknown) =>
typeof value === 'number'
? value
: typeof value === 'string' && value.trim()
? Number(value)
: NaN;
let nullVolumeRows = 0;
for (const [index, row] of rows.entries()) {
const at = timestamp(row.timestamp);
instants.push(at);
if (
row.eodSearchCode !== identity.id ||
row.symbol !== identity.symbol ||
row.exchange !== identity.exchange
) {
issue('identity-mismatch', index, at);
}
if (at === null) {
issue('invalid-timestamp', index, at);
} else {
if (at < query.start || at >= query.end) {
issue('outside-range', index, at);
}
const same = byTimestamp.get(at) ?? [];
same.push(index);
byTimestamp.set(at, same);
}
const open = numeric(row.open);
const high = numeric(row.high);
const low = numeric(row.low);
const close = numeric(row.close);
if (
![open, high, low, close].every(
value => typeof value === 'number' && Number.isFinite(value) && value > 0
) ||
high < Math.max(open, close) ||
low > Math.min(open, close)
) {
issue('invalid-prices', index, at);
}
if (row.volume === null || row.volume === undefined) {
nullVolumeRows++;
issue('null-volume', index, at);
} else if (!Number.isFinite(numeric(row.volume)) || numeric(row.volume) < 0) {
issue('invalid-volume', index, at);
}
if ((index + 1) % PREPARATION_BATCH_SIZE === 0) {
await preparationCheckpoint(signal);
}
}
let duplicateRows = 0;
for (const [at, indices] of byTimestamp) {
if (indices.length > 1) {
duplicateRows += indices.length - 1;
for (const index of indices) {
issue('duplicate-timestamp', index, at);
}
}
}
const days = new Map<string, { date: string; rowCount: number; invalidRows: number }>();
let firstTimestamp: number | null = null,
lastTimestamp: number | null = null;
for (let index = 0; index < instants.length; index++) {
const at = instants[index];
if (at === null || at === undefined) {
continue;
}
firstTimestamp = firstTimestamp === null ? at : Math.min(firstTimestamp, at);
lastTimestamp = lastTimestamp === null ? at : Math.max(lastTimestamp, at);
const date = new Date(at).toISOString().slice(0, 10);
const day = days.get(date) ?? { date, rowCount: 0, invalidRows: 0 };
day.rowCount++;
if (bad.has(index)) {
day.invalidRows++;
}
days.set(date, day);
}
signal.throwIfAborted();
return storedSourceInspectionSchema.parse({
version: 'stored-eod-inspection/v1',
observedAt: Date.now(),
query,
rowCount: rows.length,
invalidRows: bad.size,
nullVolumeRows,
duplicateRows,
firstTimestamp,
lastTimestamp,
days: [...days.values()].sort((a, b) => a.date.localeCompare(b.date)),
issues: [...issues].map(([code, detail]) => ({ code, ...detail })),
});
}

View file

@ -3,6 +3,7 @@ import type { CanonicalDatasetPreparation } from '@stock-bot/stock-config/canoni
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import { actionClass, fieldClass } from '@/features/strategies/components/StrategyParameterForm';
import { backtestApiV2, DatasetPreparationRequestError } from '../services/backtestApiV2';
import { StoredSourceInspector } from './StoredSourceInspector';
export interface DatasetPreparationState {
busy: boolean;
@ -268,6 +269,9 @@ export function DatasetPreparation({ disabled, begin, onStateChange, onRetained
uses that captured snapshot without querying storage again.
</p>
)}
{mode === 'stored-eod' && (
<StoredSourceInspector disabled={disabled || Boolean(intent) || Boolean(phase)} />
)}
<label className="block">
{mode === 'export' ? 'Source dataset JSON' : 'Source metadata JSON'}
<input

View file

@ -0,0 +1,364 @@
import { useEffect, useRef, useState } from 'react';
import type {
StoredSourceCoverage,
StoredSourceInspection,
StoredSourceQuery,
} from '@stock-bot/stock-config/stored-source';
import { actionClass, fieldClass } from '@/features/strategies/components/StrategyParameterForm';
import { storedSourceApi } from '../services/storedSourceApi';
const instant = (value: number | null) =>
value === null ? 'Unavailable' : new Date(value).toISOString();
const inputTime = (value: number | null) =>
value === null ? '' : new Date(value).toISOString().slice(0, 19);
const labels: Record<StoredSourceInspection['issues'][number]['code'], string> = {
'identity-mismatch': 'Instrument identity mismatch',
'invalid-timestamp': 'Invalid Unix-seconds timestamp',
'outside-range': 'Returned outside the selected window',
'invalid-prices': 'Invalid OHLC prices',
'null-volume': 'Missing or null volume',
'invalid-volume': 'Invalid volume',
'duplicate-timestamp': 'Duplicate timestamp',
};
/** Read-only diagnostics have their own request lifetime, never a dataset retention receipt. */
export function StoredSourceInspector({ disabled }: { disabled: boolean }) {
const [coverage, setCoverage] = useState<StoredSourceCoverage | null>(null);
const [result, setResult] = useState<StoredSourceInspection | null>(null);
const [draft, setDraft] = useState({
instrumentId: '',
interval: '5m' as StoredSourceQuery['interval'],
start: '',
end: '',
});
const [phase, setPhase] = useState<'coverage' | 'inspection' | null>(null);
const [error, setError] = useState('');
const current = useRef(draft);
const generation = useRef(0),
active = useRef(false),
abort = useRef<AbortController | null>(null);
useEffect(() => {
active.current = true;
return () => {
active.current = false;
generation.current++;
abort.current?.abort();
};
}, []);
const cancel = () => {
generation.current++;
abort.current?.abort();
abort.current = null;
setPhase(null);
};
const change = (next: typeof draft) => {
if (disabled) {
return;
}
cancel();
if (
next.instrumentId !== current.current.instrumentId ||
next.interval !== current.current.interval
) {
setCoverage(null);
}
current.current = next;
setDraft(next);
setResult(null);
setError('');
};
const run = async (kind: 'coverage' | 'inspection') => {
if (disabled) {
return;
}
const selected = { ...current.current };
cancel();
const revision = generation.current;
const controller = new AbortController();
abort.current = controller;
setPhase(kind);
setError('');
if (kind === 'inspection') {
setResult(null);
} else {
setCoverage(null);
}
try {
if (kind === 'coverage') {
const value = await storedSourceApi.coverage(
{ instrumentId: selected.instrumentId, interval: selected.interval },
controller.signal
);
if (active.current && generation.current === revision) {
setCoverage(value);
}
} else {
if (!selected.start || !selected.end) {
throw new Error('Select UTC start and end times');
}
const value = await storedSourceApi.inspect(
{
instrumentId: selected.instrumentId,
interval: selected.interval,
start: Date.parse(`${selected.start}Z`),
end: Date.parse(`${selected.end}Z`),
},
controller.signal
);
if (active.current && generation.current === revision) {
setResult(value);
}
}
} catch (cause) {
if (active.current && generation.current === revision && !controller.signal.aborted) {
setError(cause instanceof Error ? cause.message : 'Source inspection failed');
}
} finally {
if (active.current && generation.current === revision) {
abort.current = null;
setPhase(null);
}
}
};
return (
<section
aria-label="Stored source inspection"
className="space-y-3 rounded border p-3"
onChange={event => event.stopPropagation()}
onKeyDown={event => {
if (event.key === 'Enter' && (event.target as HTMLElement).tagName === 'INPUT') {
event.preventDefault();
}
}}
>
<p>
Choose one qualified instrument and timeframe to inspect its stored coverage and field
problems. Coverage examines only that series. First and last bars do not establish complete
sessions. Unlocatable timestamps are counted in coverage; window diagnostics inspect rows
returned by the time query. These diagnostics do not retain data or establish trading
eligibility.
</p>
<div className="grid gap-2 sm:grid-cols-2">
<label>
Instrument
<input
className={fieldClass}
aria-label="Inspect instrument"
value={draft.instrumentId}
disabled={disabled}
onChange={event => change({ ...current.current, instrumentId: event.target.value })}
placeholder="AAPL.US"
/>
</label>
<label>
Timeframe
<select
className={fieldClass}
aria-label="Inspect timeframe"
value={draft.interval}
disabled={disabled}
onChange={event =>
change({
...current.current,
interval: event.target.value as StoredSourceQuery['interval'],
})
}
>
{['1m', '5m', '1h'].map(value => (
<option key={value}>{value}</option>
))}
</select>
</label>
</div>
<button
type="button"
className={actionClass}
disabled={disabled || phase !== null || !draft.instrumentId}
onClick={() => void run('coverage')}
>
Load selected coverage
</button>
{coverage && (
<>
{coverage.series.length === 0 ? (
<p>
No stored bars found for {coverage.query.instrumentId} {coverage.query.interval}.
</p>
) : (
<div className="overflow-x-auto">
<table className="w-full text-left">
<caption>Stored bar coverage (UTC)</caption>
<thead>
<tr>
<th>Instrument</th>
<th>Timeframe</th>
<th>Rows</th>
<th>First bar</th>
<th>Last bar</th>
<th>Invalid timestamps</th>
<th>Window</th>
</tr>
</thead>
<tbody>
{coverage.series.map(item => (
<tr key={`${item.instrumentId}:${item.interval}`}>
<td>{item.instrumentId}</td>
<td>{item.interval}</td>
<td>{item.rowCount}</td>
<td>{instant(item.firstTimestamp)}</td>
<td>{instant(item.lastTimestamp)}</td>
<td>{item.invalidTimestampRows}</td>
<td>
<button
type="button"
className={actionClass}
disabled={disabled}
onClick={() =>
change({
instrumentId: item.instrumentId,
interval: item.interval,
start: inputTime(item.firstTimestamp),
end: inputTime(
item.lastTimestamp === null
? null
: Math.min(
8_640_000_000_000_000,
item.lastTimestamp +
{ '1m': 60000, '5m': 300000, '1h': 3600000 }[item.interval]
)
),
})
}
>
Use coverage dates
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</>
)}
<div className="grid gap-2 sm:grid-cols-2">
<label>
Start UTC (inclusive)
<input
type="datetime-local"
step="1"
className={fieldClass}
aria-label="Inspect start UTC"
value={draft.start}
disabled={disabled}
onChange={event => change({ ...current.current, start: event.target.value })}
/>
</label>
<label>
End UTC (exclusive)
<input
type="datetime-local"
step="1"
className={fieldClass}
aria-label="Inspect end UTC"
value={draft.end}
disabled={disabled}
onChange={event => change({ ...current.current, end: event.target.value })}
/>
</label>
</div>
<div className="flex gap-2">
<button
type="button"
className={actionClass}
disabled={disabled || phase !== null}
onClick={() => void run('inspection')}
>
Inspect source window
</button>
{phase && (
<button type="button" className={actionClass} onClick={cancel}>
Cancel inspection
</button>
)}
</div>
{phase && (
<p role="status">
{phase === 'coverage' ? 'Loading stored coverage...' : 'Inspecting source window...'}
</p>
)}
{error && <p role="alert">{error}</p>}
{result && (
<div className="space-y-2" aria-label="Source inspection result">
<p>
{result.query.instrumentId} · {result.query.interval} · {instant(result.query.start)} to{' '}
{instant(result.query.end)} (exclusive)
</p>
{result.rowCount === 0 ? (
<p>No stored bars in this window.</p>
) : (
<>
<p>
{result.rowCount} rows · {result.invalidRows} rows with detected problems ·{' '}
{result.nullVolumeRows} missing/null volumes · {result.duplicateRows} extra rows at
duplicate timestamps
</p>
<p>
First bar: {instant(result.firstTimestamp)} · Last bar:{' '}
{instant(result.lastTimestamp)}
</p>
{result.issues.length === 0 ? (
<p>
No listed field problems detected. Calendar, availability, corporate actions and
full dataset validation are still required.
</p>
) : (
<ul>
{result.issues.map(issue => (
<li key={issue.code}>
<details>
<summary>
{labels[issue.code]}: {issue.rowCount} rows
</summary>
<ul>
{issue.timestamps.map((at, index) => (
<li key={index}>{instant(at)}</li>
))}
</ul>
</details>
</li>
))}
</ul>
)}
<details>
<summary>Rows by UTC date</summary>
<table>
<thead>
<tr>
<th>Date</th>
<th>Rows</th>
<th>Rows with problems</th>
</tr>
</thead>
<tbody>
{result.days.map(day => (
<tr key={day.date}>
<td>{day.date}</td>
<td>{day.rowCount}</td>
<td>{day.invalidRows}</td>
</tr>
))}
</tbody>
</table>
</details>
</>
)}
<p>
No rows were changed or excluded. Use reviewed source metadata with the existing preview
below.
</p>
</div>
)}
</section>
);
}

View file

@ -0,0 +1,60 @@
import {
storedSourceCoverageSchema,
storedSourceInspectionSchema,
storedSourceQuerySchema,
storedSourceSelectionSchema,
type StoredSourceQuery,
type StoredSourceSelection,
} from '@stock-bot/stock-config/stored-source';
import { API_BASE_URL, apiFetch } from '@/lib/api';
async function read(path: string, init: RequestInit): Promise<unknown> {
const response = await apiFetch(`${API_BASE_URL}/api/v2/datasets/stored-eod/${path}`, init);
const body: unknown = await response.json().catch(error => {
if (init.signal?.aborted) {
throw error;
}
return null;
});
init.signal?.throwIfAborted();
if (!response.ok) {
throw new Error(
body && typeof body === 'object' && 'error' in body && typeof body.error === 'string'
? body.error
: `Source inspection failed (${response.status})`
);
}
return body;
}
export const storedSourceApi = {
async coverage(input: StoredSourceSelection, signal: AbortSignal) {
const query = storedSourceSelectionSchema.parse(input);
const result = storedSourceCoverageSchema.parse(
await read(`coverage?${new URLSearchParams(query)}`, { signal })
);
if (
JSON.stringify(result.query) !== JSON.stringify(query) ||
result.series.some(
item => item.instrumentId !== query.instrumentId || item.interval !== query.interval
)
) {
throw new Error('Source coverage differs from the selected instrument and timeframe');
}
return result;
},
async inspect(input: StoredSourceQuery, signal: AbortSignal) {
const query = storedSourceQuerySchema.parse(input);
const result = storedSourceInspectionSchema.parse(
await read('inspect', {
method: 'POST',
signal,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(query),
})
);
if (JSON.stringify(result.query) !== JSON.stringify(query)) {
throw new Error('Source inspection differs from the selected window');
}
return result;
},
};

View file

@ -2,15 +2,15 @@
Parent: E12. Priority P1. Complexity M. Authorized by the owner's request to implement the real-data research workflow.
Outcome: the stored-EOD preparation UI shows available instruments/timeframes/date coverage and diagnostics for an explicit UTC window before requiring complete dataset metadata.
Outcome: the stored-EOD preparation UI looks up one explicitly selected instrument/timeframe, shows date coverage, and diagnoses an explicit UTC window before requiring complete dataset metadata.
Evidence: `DatasetPreparation.tsx` currently begins with metadata JSON; `prepareStoredDataset` calls the strict historical reader, which rejects an invalid row before returning a preview. The read-only October 26 pilot again found 22 null-volume rows in 1,816 AAPL five-minute records. Quality inspection must not weaken execution admission.
Scope: browser-safe shared contracts, fixed EOD Mongo collection coverage and window inspection, existing dataset routes, separate stored-mode inspector, focused API/domain/UI regressions. Show unknown identity/timestamps, malformed OHLCV and duplicates truthfully. No implicit filtering, metadata inference, row caps, writes, cache, financial changes or research-agent permission expansion. Existing strict preview/retain remains authoritative.
Scope: browser-safe shared contracts, one fixed EOD Mongo collection per selected timeframe, an exact indexed instrument match and window inspection, existing dataset routes, separate stored-mode inspector, focused API/domain/UI regressions. Show unknown identity/timestamps, malformed OHLCV and duplicates truthfully. No whole-archive scan or automatic lookup on mount. No implicit filtering, metadata inference, row caps, writes, cache, financial changes or research-agent permission expansion. Existing strict preview/retain remains authoritative.
Dependencies: accepted CL05/CL06/CL17. Agent lock: stored-source contracts/service/routes/UI and new tests. Can run beside cache corrections and pilot preparation.
Acceptance: actual stored coverage is inspectable; empty/error/loading/cancel states work; changing input fences late responses; full requested range is diagnosed; no source or research records are written; a clean diagnostic never implies execution eligibility. In-flight Mongo cancellation limitations are explicit.
Acceptance: actual selected-series coverage is inspectable; empty/error/loading/cancel states work; changing input fences late responses; full requested range is diagnosed; inspector edits/Enter do not dirty or submit the enclosing setup; no source or research records are written; a clean diagnostic never implies execution eligibility. In-flight Mongo cancellation limitations are explicit.
Tests: source inspection domain/HTTP and production component tests; existing stored/prepared dataset suites; shared contract/browser bundle tests; read-only actual Mongo smoke; typecheck/lint; repository and browser integration gates. Independent backend and frontend review before completion.

View file

@ -2341,6 +2341,133 @@ test('browser_catalog_version_parameters_clone_and_saved_draft', async () => {
}
});
test('stored_source_inspection_browser_keeps_utc_scope_and_research_state_unchanged', async () => {
const f = await fixture();
try {
await f.login();
const { id, dataset } = await createCanonicalInBrowser(f, 'Stored source inspection');
const rows = dataset.bars.map((bar, index) => ({
eodSearchCode: 'X0.US',
symbol: 'X0',
exchange: 'US',
timestamp: bar.intervalStart / 1000,
open: bar.open,
high: bar.high,
low: bar.low,
close: bar.close,
volume: index === 0 ? -1 : bar.volume,
}));
f.setStoredEodBars('eodIntraday1M', rows);
const first = Math.min(...rows.map(row => row.timestamp)) * 1000;
const last = Math.max(...rows.map(row => row.timestamp)) * 1000;
const coverageRequests: URL[] = [];
// Mongo aggregation has separate real-server coverage. This response fixture
// drives the browser picker; the following inspection uses the real HTTP API.
await f.page.route(/\/api\/v2\/datasets\/stored-eod\/coverage(?:\?.*)?$/, route => {
coverageRequests.push(new URL(route.request().url()));
return route.fulfill({
json: {
version: 'stored-eod-coverage/v1',
observedAt: first,
query: { instrumentId: 'X0.US', interval: '1m' },
series: [
{
instrumentId: 'X0.US',
interval: '1m',
rowCount: rows.length,
firstTimestamp: first,
lastTimestamp: last,
invalidTimestampRows: 0,
},
],
},
});
});
const template = await f.request(`/api/v2/backtests/${id}`);
const templateWrites: string[] = [];
f.page.on('request', request => {
if (
request.method() === 'PUT' &&
new URL(request.url()).pathname === `/api/v2/backtests/${id}`
) {
templateWrites.push(request.url());
}
});
const counts = async () =>
(
await f.pool.query(`SELECT
(SELECT count(*)::int FROM backtest_datasets) AS datasets,
(SELECT count(*)::int FROM runs) AS runs,
(SELECT count(*)::int FROM backtest_dispatch) AS dispatch`)
).rows[0];
const before = await counts();
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
await f.page.getByText('Prepare dataset from source export', { exact: true }).click();
await f.page.getByLabel('Dataset input', { exact: true }).selectOption('stored-eod');
const inspector = f.page.getByRole('region', { name: 'Stored source inspection', exact: true });
await inspector.waitFor();
expect(coverageRequests).toHaveLength(0);
await inspector.getByLabel('Inspect instrument', { exact: true }).fill('X0.US');
await inspector.getByLabel('Inspect timeframe', { exact: true }).selectOption('1m');
await inspector.getByLabel('Inspect instrument', { exact: true }).press('Enter');
expect(coverageRequests).toHaveLength(0);
await inspector.getByRole('button', { name: 'Load selected coverage', exact: true }).click();
await inspector.getByRole('button', { name: 'Use coverage dates', exact: true }).waitFor();
expect(coverageRequests).toHaveLength(1);
expect(Object.fromEntries(coverageRequests[0]!.searchParams)).toEqual({
instrumentId: 'X0.US',
interval: '1m',
});
expect(await inspector.getByLabel('Inspect start UTC', { exact: true }).inputValue()).toBe('');
expect(await inspector.getByLabel('Inspect end UTC', { exact: true }).inputValue()).toBe('');
await inspector.getByRole('button', { name: 'Use coverage dates', exact: true }).click();
expect(await inspector.getByLabel('Inspect instrument', { exact: true }).inputValue()).toBe(
'X0.US'
);
expect(await inspector.getByLabel('Inspect timeframe', { exact: true }).inputValue()).toBe(
'1m'
);
const inspecting = f.page.waitForResponse(response =>
response.url().endsWith('/api/v2/datasets/stored-eod/inspect')
);
await inspector.getByRole('button', { name: 'Inspect source window', exact: true }).click();
const response = await inspecting;
expect(response.status()).toBe(200);
expect(response.request().postDataJSON()).toEqual({
instrumentId: 'X0.US',
interval: '1m',
start: first,
end: last + 60000,
});
const inspected = await response.json();
expect(inspected.invalidRows).toBe(1);
expect(inspected.rowCount).toBe(rows.length);
await inspector.getByText('Invalid volume: 1 rows', { exact: true }).waitFor();
await visible(f.page, /No rows were changed or excluded/);
expect(
await f.page.getByRole('button', { name: 'Retain dataset', exact: true }).isDisabled()
).toBe(true);
expect(await f.page.getByLabel('Canonical dataset', { exact: true }).inputValue()).toBe(
dataset.manifest.hash
);
expect(await counts()).toEqual(before);
expect(await f.request(`/api/v2/backtests/${id}`)).toEqual(template);
expect(templateWrites).toEqual([]);
expect(f.storedSourceReads).toEqual([
{
collection: 'eodIntraday1M',
filter: {
eodSearchCode: 'X0.US',
timestamp: { $gte: first / 1000, $lt: (last + 60000) / 1000 },
},
},
]);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});
test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_reopen', async () => {
const f = await fixture(true);
f.page.on('dialog', dialog => void dialog.accept());

View file

@ -0,0 +1,295 @@
import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from 'bun:test';
import { GlobalWindow } from 'happy-dom';
import { act, createElement } from 'react';
import type { Root } from 'react-dom/client';
import type {
StoredSourceCoverage,
StoredSourceInspection,
} from '@stock-bot/stock-config/stored-source';
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
const keys = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT'] as const;
const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
let createRoot: typeof import('react-dom/client').createRoot;
let Inspector: typeof import('../../apps/stock/web-app/src/features/backtest/components/StoredSourceInspector').StoredSourceInspector;
let root: Root | undefined;
let host: HTMLDivElement;
const start = Date.parse('2024-10-01T13:30:00Z');
const coverage: StoredSourceCoverage = {
version: 'stored-eod-coverage/v1',
observedAt: start,
query: { instrumentId: 'AAPL.US', interval: '5m' },
series: [
{
instrumentId: 'AAPL.US',
interval: '5m',
rowCount: 78,
firstTimestamp: start,
lastTimestamp: start + 385 * 60000,
invalidTimestampRows: 0,
},
],
};
const result: StoredSourceInspection = {
version: 'stored-eod-inspection/v1',
observedAt: start,
query: { instrumentId: 'AAPL.US', interval: '5m', start, end: start + 390 * 60000 },
rowCount: 78,
invalidRows: 1,
nullVolumeRows: 1,
duplicateRows: 0,
firstTimestamp: start,
lastTimestamp: start + 385 * 60000,
days: [{ date: '2024-10-01', rowCount: 78, invalidRows: 1 }],
issues: [{ code: 'null-volume', rowCount: 1, timestamps: [start] }],
};
interface Pending {
path: string;
search: string;
init: RequestInit | undefined;
resolve: (response: Response) => void;
reject: (error: Error) => void;
}
const requests: Pending[] = [];
beforeAll(async () => {
for (const [key, value] of Object.entries({
window: browser,
document: browser.document,
IS_REACT_ACT_ENVIRONMENT: true,
})) {
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
}
({ createRoot } = await import('react-dom/client'));
({ StoredSourceInspector: Inspector } = await import(
'../../apps/stock/web-app/src/features/backtest/components/StoredSourceInspector'
));
});
beforeEach(() => {
requests.length = 0;
host = browser.document.createElement('div') as unknown as HTMLDivElement;
browser.document.body.append(host as never);
browser.fetch = ((url: RequestInfo | URL, init?: RequestInit) =>
new Promise<Response>((resolve, reject) =>
requests.push({
path: new URL(String(url)).pathname,
search: new URL(String(url)).search,
init,
resolve,
reject,
})
)) as unknown as typeof browser.fetch;
});
async function flush(fn: () => void = () => {}) {
await act(async () => {
fn();
await Promise.resolve();
});
}
afterEach(async () => {
if (root) {
await flush(() => root!.unmount());
}
root = undefined;
host.remove();
});
afterAll(async () => {
await browser.happyDOM.close();
for (const key of keys) {
const value = originals.get(key);
if (value) {
Object.defineProperty(globalThis, key, value);
} else {
Reflect.deleteProperty(globalThis, key);
}
}
});
function button(label: string) {
const found = [...host.querySelectorAll('button')].find(value => value.textContent === label);
if (!found) {
throw new Error(`Missing ${label}`);
}
return found;
}
function edit(label: string, value: string) {
const input = host.querySelector(`[aria-label="${label}"]`) as HTMLInputElement;
Object.getOwnPropertyDescriptor(browser.HTMLInputElement.prototype, 'value')!.set!.call(
input,
value
);
input.dispatchEvent(new browser.Event('input', { bubbles: true }) as unknown as Event);
}
async function mount(disabled = false) {
root = createRoot(host);
await flush(() => root!.render(createElement(Inspector, { disabled })));
}
async function choose() {
await flush(() => edit('Inspect instrument', 'AAPL.US'));
await flush(() => button('Load selected coverage').click());
await flush(() => requests.at(-1)!.resolve(Response.json(coverage)));
await flush(() => button('Use coverage dates').click());
}
test('coverage selects an explicit UTC window and inspection displays quality without writing or retaining', async () => {
await mount();
expect(requests).toHaveLength(0);
await flush(() => edit('Inspect instrument', 'AAPL.US'));
expect(requests).toHaveLength(0);
await flush(() => button('Load selected coverage').click());
expect(host.textContent).toContain('Loading stored coverage');
expect(requests[0]!.search).toBe('?instrumentId=AAPL.US&interval=5m');
await flush(() => requests[0]!.resolve(Response.json(coverage)));
expect(host.textContent).toContain('78');
await flush(() => button('Use coverage dates').click());
await flush(() => button('Inspect source window').click());
const request = requests[1]!;
expect(request.path).toBe('/api/v2/datasets/stored-eod/inspect');
expect(JSON.parse(String(request.init?.body))).toEqual(result.query);
expect(request.init?.credentials).toBe('include');
await flush(() => request.resolve(Response.json(result)));
expect(host.textContent).toContain('1 missing/null volumes');
expect(host.textContent).toContain('No rows were changed or excluded');
expect(host.textContent).toContain('2024-10-01T13:30:00.000Z');
expect(requests.every(value => value.path.includes('/stored-eod/'))).toBe(true);
});
test('editing or cancelling invalidates late inspection replies and never displays a different window', async () => {
await mount();
await choose();
await flush(() => button('Inspect source window').click());
const old = requests.at(-1)!;
await flush(() => edit('Inspect instrument', 'MSFT.US'));
expect(old.init?.signal?.aborted).toBe(true);
expect(host.textContent).not.toContain('Stored bar coverage (UTC)');
await flush(() => old.resolve(Response.json(result)));
expect(host.querySelector('[aria-label="Source inspection result"]')).toBeNull();
await flush(() => edit('Inspect instrument', 'AAPL.US'));
await flush(() => button('Inspect source window').click());
const cancelled = requests.at(-1)!;
await flush(() => button('Cancel inspection').click());
expect(cancelled.init?.signal?.aborted).toBe(true);
await flush(() => cancelled.resolve(Response.json(result)));
expect(host.querySelector('[aria-label="Source inspection result"]')).toBeNull();
await flush(() => button('Inspect source window').click());
const wrong = requests.at(-1)!;
await flush(() =>
wrong.resolve(Response.json({ ...result, query: { ...result.query, instrumentId: 'MSFT.US' } }))
);
expect(host.querySelector('[role="alert"]')?.textContent).toContain(
'differs from the selected window'
);
});
test('empty/error states are visible and retry is explicit; unmount aborts outstanding work', async () => {
await mount();
await flush(() => edit('Inspect instrument', 'AAPL.US'));
await flush(() => button('Load selected coverage').click());
await flush(() => requests.at(-1)!.resolve(Response.json({ ...coverage, series: [] })));
expect(host.textContent).toContain('No stored bars found for AAPL.US 5m');
await flush(() => button('Load selected coverage').click());
await flush(() =>
requests.at(-1)!.resolve(Response.json({ error: 'Store offline' }, { status: 503 }))
);
expect(host.querySelector('[role="alert"]')?.textContent).toBe('Store offline');
expect(requests).toHaveLength(2);
await choose();
await flush(() => button('Inspect source window').click());
await flush(() =>
requests.at(-1)!.resolve(
Response.json({
...result,
rowCount: 0,
invalidRows: 0,
nullVolumeRows: 0,
duplicateRows: 0,
firstTimestamp: null,
lastTimestamp: null,
days: [],
issues: [],
})
)
);
expect(host.textContent).toContain('No stored bars in this window');
await flush(() => button('Load selected coverage').click());
const pending = requests.at(-1)!;
await flush(() => root!.unmount());
root = undefined;
expect(pending.init?.signal?.aborted).toBe(true);
});
test('disabled preparation cannot start diagnostics', async () => {
await mount(true);
expect(button('Load selected coverage').disabled).toBe(true);
expect(button('Inspect source window').disabled).toBe(true);
await flush(() => button('Load selected coverage').click());
expect(requests).toHaveLength(0);
});
test('coverage scope changes fence stale replies and mismatched coverage is rejected', async () => {
await mount();
await flush(() => edit('Inspect instrument', 'AAPL.US'));
await flush(() => button('Load selected coverage').click());
const stale = requests.at(-1)!;
await flush(() => edit('Inspect instrument', 'MSFT.US'));
expect(stale.init?.signal?.aborted).toBe(true);
await flush(() => stale.resolve(Response.json(coverage)));
expect(host.textContent).not.toContain('Stored bar coverage (UTC)');
await flush(() => button('Load selected coverage').click());
await flush(() => requests.at(-1)!.resolve(Response.json(coverage)));
expect(host.querySelector('[role="alert"]')?.textContent).toContain(
'differs from the selected instrument and timeframe'
);
expect(host.textContent).not.toContain('Stored bar coverage (UTC)');
});
test('diagnostic edits and Enter do not dirty or submit the containing canonical setup form', async () => {
let changes = 0;
let submissions = 0;
root = createRoot(host);
await flush(() =>
root!.render(
createElement(
'form',
{
onChange: () => {
changes++;
},
onSubmit: (event: { preventDefault(): void }) => {
event.preventDefault();
submissions++;
},
},
createElement(Inspector, { disabled: false })
)
)
);
await flush(() => edit('Inspect instrument', 'AAPL.US'));
expect(changes).toBe(0);
const input = host.querySelector('[aria-label="Inspect instrument"]')!;
const enter = new browser.KeyboardEvent('keydown', {
key: 'Enter',
bubbles: true,
cancelable: true,
});
await flush(() => {
input.dispatchEvent(enter as unknown as Event);
});
expect(enter.defaultPrevented).toBe(true);
expect(submissions).toBe(0);
expect(requests).toHaveLength(0);
const buttonEnter = new browser.KeyboardEvent('keydown', {
key: 'Enter',
bubbles: true,
cancelable: true,
});
await flush(() => {
button('Load selected coverage').dispatchEvent(buttonEnter as unknown as Event);
});
expect(buttonEnter.defaultPrevented).toBe(false);
const selectEnter = new browser.KeyboardEvent('keydown', {
key: 'Enter',
bubbles: true,
cancelable: true,
});
await flush(() => {
host
.querySelector('[aria-label="Inspect timeframe"]')!
.dispatchEvent(selectEnter as unknown as Event);
});
expect(selectEnter.defaultPrevented).toBe(false);
});

View file

@ -0,0 +1,240 @@
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 } from '@stock-bot/services';
import {
storedSourceCoverageSchema,
storedSourceInspectionSchema,
} from '@stock-bot/stock-config/stored-source';
import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes';
import {
inspectStoredSource,
storedSourceCoverage,
} from '../../apps/stock/web-api/src/services/stored-source-inspection';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('source-inspection-test');
const start = Date.parse('2024-10-01T13:30:00Z');
const selection = { instrumentId: 'AAPL.US', interval: '5m' } as const;
const coveragePath = 'coverage?instrumentId=AAPL.US&interval=5m';
const query = { ...selection, start, end: start + 900000 };
const row = {
eodSearchCode: 'AAPL.US',
symbol: 'AAPL',
exchange: 'US',
timestamp: start / 1000,
open: 10,
high: 12,
low: 9,
close: 11,
volume: 100,
};
function fixture(rows: Record<string, unknown>[] = [row]) {
const find = mock(async () => structuredClone(rows));
const aggregate = mock(async (collection: string, _pipeline: Record<string, unknown>[]) =>
collection === 'eodIntraday5M'
? [
{
_id: null,
rowCount: 4,
firstTimestamp: start / 1000,
lastTimestamp: start / 1000 + 600,
invalidTimestampRows: 1,
},
]
: []
);
const database = mock(async () => {
throw new Error('No PostgreSQL writes or reads allowed');
});
const store = { find, aggregate } as unknown as MongoDBClient;
const app = new Hono();
createHttpSecurity({
adminToken: 'source-admin-fixture-not-a-real-secret',
serviceToken: 'source-service-fixture-not-a-real-secret',
readToken: 'source-read-fixture-not-a-real-secret',
environment: 'test',
browserSessions: true,
}).mount(app);
app.route(
'/',
createDatasetRoutes({
logger,
mongodb: store,
postgres: { query: database },
} as unknown as IServiceContainer)
);
const request = (
path: string,
body?: unknown,
token: string | null = 'source-admin-fixture-not-a-real-secret',
signal?: AbortSignal
) =>
app.request(`/api/v2/datasets/stored-eod/${path}`, {
method: body === undefined ? 'GET' : 'POST',
headers: {
...(token ? { Authorization: `Bearer ${token}` } : {}),
'Content-Type': 'application/json',
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
signal,
});
return { store, app, find, aggregate, database, request };
}
describe('stored EOD source discovery and diagnostics', () => {
test('coverage reads only the explicitly selected instrument and collection with an indexable first match', async () => {
const f = fixture();
const response = await f.request(coveragePath);
expect(response.status).toBe(200);
expect(response.headers.get('Cache-Control')).toBe('no-store');
const value = storedSourceCoverageSchema.parse(await response.json());
expect(value.series).toEqual([
{
instrumentId: 'AAPL.US',
interval: '5m',
rowCount: 4,
firstTimestamp: start,
lastTimestamp: start + 600000,
invalidTimestampRows: 1,
},
]);
expect(value.query).toEqual(selection);
expect(f.aggregate).toHaveBeenCalledTimes(1);
expect(f.aggregate.mock.calls[0]?.[0]).toBe('eodIntraday5M');
expect(f.aggregate.mock.calls[0]?.[1]?.[0]).toEqual({ $match: { eodSearchCode: 'AAPL.US' } });
expect(f.find).not.toHaveBeenCalled();
expect(f.database).not.toHaveBeenCalled();
});
test('coverage requires an exact selection before any store access and preserves an empty selected series', async () => {
const f = fixture();
for (const path of [
'coverage',
'coverage?instrumentId=AAPL.US',
'coverage?instrumentId=AAPL&interval=5m',
'coverage?instrumentId=AAPL.US&interval=15m',
'coverage?instrumentId=AAPL.US&interval=5m&all=true',
]) {
expect((await f.request(path)).status).toBe(400);
}
expect(f.aggregate).not.toHaveBeenCalled();
f.aggregate.mockImplementation(async () => []);
expect(await (await f.request(coveragePath)).json()).toMatchObject({
query: selection,
series: [],
});
expect(f.aggregate).toHaveBeenCalledTimes(1);
expect(f.database).not.toHaveBeenCalled();
});
test('field problems, identity and duplicate rows remain visible without altering source prices', async () => {
const rows = [
row,
{ ...row, volume: null },
{ ...row, timestamp: start / 1000 + 300, close: 100 },
{ ...row, timestamp: start / 1000 + 600, exchange: 'OTHER', volume: -1 },
{ ...row, timestamp: 'not-an-instant' },
{ ...row, timestamp: query.end / 1000 },
];
const before = structuredClone(rows);
const f = fixture(rows);
const response = await f.request('inspect', query);
expect(response.status).toBe(200);
const value = storedSourceInspectionSchema.parse(await response.json());
expect(value).toMatchObject({
query,
rowCount: 6,
invalidRows: 6,
nullVolumeRows: 1,
duplicateRows: 1,
firstTimestamp: start,
lastTimestamp: query.end,
});
expect(value.issues.map(issue => issue.code)).toEqual([
'null-volume',
'invalid-prices',
'identity-mismatch',
'invalid-volume',
'invalid-timestamp',
'outside-range',
'duplicate-timestamp',
]);
expect(value.issues.find(issue => issue.code === 'duplicate-timestamp')).toMatchObject({
rowCount: 2,
timestamps: [start, start],
});
expect(value.days).toEqual([{ date: '2024-10-01', rowCount: 5, invalidRows: 5 }]);
expect(rows).toEqual(before);
expect(f.database).not.toHaveBeenCalled();
expect(f.find.mock.calls[0]?.slice(0, 2)).toMatchObject([
'eodIntraday5M',
{ eodSearchCode: 'AAPL.US', timestamp: { $gte: start / 1000, $lt: query.end / 1000 } },
]);
});
test('invalid queries reject before any store access; supported empty windows are explicit', async () => {
const f = fixture([]);
for (const invalid of [
{ ...query, end: start },
{ ...query, interval: '15m' },
{ ...query, instrumentId: 'AAPL' },
{ ...query, start: 1.5 },
{ ...query, extra: true },
]) {
expect((await f.request('inspect', invalid)).status).toBe(400);
}
expect(f.find).not.toHaveBeenCalled();
const empty = await f.request('inspect', query);
expect(await empty.json()).toMatchObject({
rowCount: 0,
invalidRows: 0,
firstTimestamp: null,
lastTimestamp: null,
days: [],
issues: [],
});
});
test('ordinary authentication roles remain enforced and source failures are sanitized', async () => {
const f = fixture();
expect((await f.request(coveragePath, undefined, null)).status).toBe(401);
expect(
(await f.request(coveragePath, undefined, 'source-read-fixture-not-a-real-secret')).status
).toBe(200);
expect(
(await f.request('inspect', query, 'source-read-fixture-not-a-real-secret')).status
).toBe(403);
expect(f.find).not.toHaveBeenCalled();
f.find.mockImplementation(async () => {
throw new Error('private transport detail');
});
const failure = await f.request('inspect', query);
expect(failure.status).toBe(500);
expect(await failure.json()).toEqual({ error: 'Stored source inspection unavailable' });
});
test('absent storage is unavailable and cancellation fences queries and returned data', async () => {
const abort = new AbortController();
abort.abort(new Error('cancelled'));
const f = fixture();
await expect(inspectStoredSource(f.store, query, abort.signal)).rejects.toThrow('cancelled');
await expect(storedSourceCoverage(f.store, selection, abort.signal)).rejects.toThrow(
'cancelled'
);
expect(f.find).not.toHaveBeenCalled();
expect(f.aggregate).not.toHaveBeenCalled();
await expect(
inspectStoredSource(null, query, new AbortController().signal)
).rejects.toMatchObject({ status: 503 });
const during = new AbortController();
f.find.mockImplementation(async () => {
during.abort(new Error('during query'));
return [row];
});
await expect(inspectStoredSource(f.store, query, during.signal)).rejects.toThrow(
'during query'
);
const httpAbort = new AbortController();
f.find.mockImplementation(async () => {
httpAbort.abort();
return [row];
});
expect((await f.request('inspect', query, undefined, httpAbort.signal)).status).toBe(499);
});
});

View file

@ -0,0 +1,91 @@
/** Read-only aggregation regression; no collections, source records or credentials are written. */
import { describe, expect, test } from 'bun:test';
import { Decimal128, Double, Int32, Long, MongoClient } from 'mongodb';
import type { MongoDBClient } from '@stock-bot/services';
import { storedSourceCoverage } from '../../apps/stock/web-api/src/services/stored-source-inspection';
const url = process.env.SOURCE_TEST_MONGODB_URL;
describe.skipIf(!url)('stored source BSON timestamp coverage on MongoDB', () => {
test('coverage agrees with the strict JS reader for real BSON types and time bounds', async () => {
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Explicit stock_bot_safety MongoDB test URL required');
}
const client = new MongoClient(url, { serverSelectionTimeoutMS: 5000 });
try {
await client.connect();
const good = [new Int32(1727789400), new Double(1727789700), Long.fromNumber(1727790000)];
const bad = [
Decimal128.fromString('1727789400'),
null,
'1727789400',
new Double(1727789400.5),
new Double(-1),
Long.fromString('8640000000001'),
new Double(NaN),
new Double(Infinity),
];
// A collection-free $documents source runs the exact production aggregation on
// actual BSON values. The adapter seam substitutes only where records originate.
const store: Pick<MongoDBClient, 'aggregate' | 'find'> = {
aggregate: async <T extends Record<string, unknown>>(
collection: string,
pipeline: Record<string, unknown>[]
) => {
const docs =
collection === 'eodIntraday5M'
? [
...good.map(timestamp => ({ eodSearchCode: 'VALID.US', timestamp })),
...bad.map(timestamp => ({ eodSearchCode: 'INVALID.US', timestamp })),
]
: [];
return client
.db()
.aggregate<T>([{ $documents: docs }, ...pipeline])
.toArray();
},
find: async () => {
throw new Error('Coverage must not query source rows');
},
};
const signal = new AbortController().signal;
const invalid = await storedSourceCoverage(
store,
{ instrumentId: 'INVALID.US', interval: '5m' },
signal
);
expect(invalid.series).toEqual([
{
instrumentId: 'INVALID.US',
interval: '5m',
rowCount: bad.length,
firstTimestamp: null,
lastTimestamp: null,
invalidTimestampRows: bad.length,
},
]);
const valid = await storedSourceCoverage(
store,
{ instrumentId: 'VALID.US', interval: '5m' },
signal
);
expect(valid.series).toEqual([
{
instrumentId: 'VALID.US',
interval: '5m',
rowCount: good.length,
firstTimestamp: 1727789400000,
lastTimestamp: 1727790000000,
invalidTimestampRows: 0,
},
]);
const empty = await storedSourceCoverage(
store,
{ instrumentId: 'MISSING.US', interval: '5m' },
signal
);
expect(empty.series).toEqual([]);
} finally {
await client.close();
}
});
});