feat(research): read verified frozen datasets (RP28)
This commit is contained in:
parent
04892a59fe
commit
4b9c642817
9 changed files with 263 additions and 18 deletions
|
|
@ -103,6 +103,13 @@ The client and API share result validation; financial decimal strings and unavai
|
|||
metrics are preserved. Missing results remain read errors so callers can inspect the
|
||||
saved trial status and diagnostics.
|
||||
|
||||
Read the original market data with `ResearchClient.canonicalDataset(result.request.datasetHash)`.
|
||||
The client verifies the complete v2 snapshot and its hash before returning frozen bars
|
||||
and metadata. Research credentials can read exact known-hash exports; dataset discovery,
|
||||
provider preparation and data writes use the operator workflow. Use the predeclared training
|
||||
snapshot for exploration and preserve untouched holdouts until evaluation. Candidate
|
||||
callbacks continue to receive published prefixes through their isolated runtime.
|
||||
|
||||
To save a comparison across studies, call `ResearchClient.saveFinding` with `source: null`
|
||||
or omit `source`. Include a nonempty list of canonical metric references with each run's
|
||||
exact strategy-version ID. The API resolves their values from retained completed runs;
|
||||
|
|
|
|||
|
|
@ -47,7 +47,9 @@ function permitted(request: Request): boolean {
|
|||
return (
|
||||
/^\/api\/v2\/(research-projects|hypotheses|analysis-artifacts|strategies|strategy-versions|experiments|backtests|runs)(\/|$)/.test(
|
||||
path
|
||||
) || path === '/api/v2/research-agent/budget'
|
||||
) ||
|
||||
/^\/api\/v2\/datasets\/canonical\/[a-f0-9]{64}\/export$/.test(path) ||
|
||||
path === '/api/v2/research-agent/budget'
|
||||
);
|
||||
}
|
||||
if (method === 'PUT') {
|
||||
|
|
|
|||
|
|
@ -185,8 +185,9 @@ export function ResearchAgentsPage() {
|
|||
<h1 className="text-xl font-semibold">Research agent access</h1>
|
||||
<p>
|
||||
Grant research writes to specific projects and experiments on saved canonical backtests.
|
||||
Research catalog and historical results remain readable. The server freezes each backtest’s
|
||||
financial policy. Research credentials cannot control paper or live trading.
|
||||
Research credentials can read the catalog, historical results and known frozen datasets. The
|
||||
server freezes each backtest’s financial policy. Research credentials cannot control paper
|
||||
or live trading.
|
||||
</p>
|
||||
{writeError && <p role="alert">{writeError}</p>}
|
||||
{token && (
|
||||
|
|
|
|||
|
|
@ -8,13 +8,13 @@ Selected scope: allow only the existing exact GET/HEAD canonical export path wit
|
|||
|
||||
Add `ResearchClient.canonicalDataset(hash, signal?)`, using the existing `validateDatasetV2` content/hash validator and matching the requested hash. Return detached, frozen retained bars/metadata without interpolation or provider queries. Callers select the exact hash from the saved run request or predeclared experiment input, including phase-specific hashes. No new storage, financial calculations, caches, input truncation or automatic research execution.
|
||||
|
||||
Affected files: research credential service/allowlist; research client and tests; authenticated AI workflow fixture/tests; existing security integration tests; README usage. The dataset export/validator implementation remains authoritative and is reused unchanged.
|
||||
Affected files: research credential service/allowlist; research client and tests; authenticated AI workflow fixture/tests; existing security/export integration tests; README usage and the operator page's permission description. The dataset export/validator implementation remains authoritative and is reused unchanged. The web change is descriptive copy only.
|
||||
|
||||
Acceptance/tests:
|
||||
|
||||
- Exact known-hash GET/HEAD export authenticates a real research credential; source/data-write/catalog/admin/trading routes remain denied as before. Malformed/extra dataset paths fail closed. Revoked credentials cannot export.
|
||||
- Typed reads preserve original bars, calendar/session/availability metadata, lineage/hash and limitations. Invalid hash inputs fail before transport; tampered content, derived-policy mismatches and a different valid dataset fail as read errors without retries.
|
||||
- Actual API tests compare exports to retained PostgreSQL payloads, demonstrate existing saved-template edits do not change a prior hash, and verify no runs/experiments/datasets are created by reads. Unknown/corrupt snapshots produce the existing 404/409 read errors. Abort/deadline behavior uses the existing client transport.
|
||||
- Run client/cycle and focused credential/security suites, complete tooling/integration, actual PostgreSQL AI/agent tests, application/authored types, contracts, strict lint/formatting and secrets. No engine/web rebuild or browser change is necessary.
|
||||
- Run client/cycle and focused credential/security suites, complete tooling/integration, actual PostgreSQL AI/agent tests, application/authored types, contracts, strict lint/formatting and secrets. Build the web app to verify the permission description; no engine rebuild or browser-flow change is necessary.
|
||||
|
||||
Definition of done: reproduce the missing typed/read permission capability, add the narrow existing endpoint access and typed read, review shared research-read versus privileged data-write scope, pass gates, document usage/holdout discipline, update task state and commit. This fits ADR-007 research/data isolation; no new architecture approval is required.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
/** Authorized research API client. No strategy import, financial simulation, or trading controls. */
|
||||
import { z } from 'zod';
|
||||
import { validateDatasetV2 } from '@stock-bot/research/datasets';
|
||||
import { parseCanonicalRunResult } from '@stock-bot/research/results';
|
||||
import {
|
||||
chronologicalValidationInputSchema,
|
||||
|
|
@ -763,6 +764,22 @@ export class ResearchClient {
|
|||
key
|
||||
);
|
||||
}
|
||||
canonicalDataset(datasetHash: string, signal?: AbortSignal) {
|
||||
datasetHash = hash.parse(datasetHash);
|
||||
return this.#request(
|
||||
`datasets/canonical/${datasetHash}/export`,
|
||||
'GET',
|
||||
200,
|
||||
value => {
|
||||
const dataset = validateDatasetV2(value);
|
||||
expect(dataset.manifest.hash === datasetHash);
|
||||
return dataset;
|
||||
},
|
||||
undefined,
|
||||
undefined,
|
||||
signal
|
||||
);
|
||||
}
|
||||
canonicalRunResult(runId: string, signal?: AbortSignal) {
|
||||
runId = uuid.parse(runId);
|
||||
return this.#request(
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { createHash } from 'node:crypto';
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import type { ExperimentDetail } from '@stock-bot/stock-config/experiments';
|
||||
import { canonicalResultFixture } from '../../test/fixtures/canonical-result';
|
||||
import { nativeReplayFixture } from '../../test/fixtures/native-replay';
|
||||
import { comparisonFixture, tableFixture } from '../benchmark-experiment-tables';
|
||||
import {
|
||||
pollResearch,
|
||||
|
|
@ -37,6 +38,86 @@ function client(handler: (call: Call, index: number) => Response | Promise<Respo
|
|||
}
|
||||
const ordinary = () => tableFixture(1) as ExperimentDetail;
|
||||
|
||||
describe('frozen market data inspection', () => {
|
||||
test('reads the complete requested snapshot without changing bars or metadata', async () => {
|
||||
const dataset = nativeReplayFixture().dataset;
|
||||
const before = structuredClone(dataset);
|
||||
const { value, calls } = client(() => Response.json(dataset));
|
||||
const saved = await value.canonicalDataset(dataset.manifest.hash);
|
||||
expect(saved).toEqual(before);
|
||||
expect(Object.isFrozen(saved)).toBe(true);
|
||||
expect(dataset).toEqual(before);
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]!.url.pathname).toBe(
|
||||
`/api/v2/datasets/canonical/${dataset.manifest.hash}/export`
|
||||
);
|
||||
expect(calls[0]!.init.method).toBe('GET');
|
||||
expect(calls[0]!.body).toBeUndefined();
|
||||
expect(new Headers(calls[0]!.init.headers).get('authorization')).toBe(`Bearer ${token}`);
|
||||
expect(new Headers(calls[0]!.init.headers).has('idempotency-key')).toBe(false);
|
||||
});
|
||||
|
||||
test('rejects altered content, derived policy and a different valid snapshot without retries', async () => {
|
||||
const dataset = nativeReplayFixture().dataset;
|
||||
const changedBar = {
|
||||
...dataset,
|
||||
bars: dataset.bars.map((bar, index) => (index ? bar : { ...bar, volume: bar.volume + 1 })),
|
||||
};
|
||||
const changedTime = {
|
||||
...dataset,
|
||||
bars: dataset.bars.map((bar, index) =>
|
||||
index ? bar : { ...bar, availableAt: bar.availableAt + 1 }
|
||||
),
|
||||
};
|
||||
const changedPolicy = {
|
||||
...dataset,
|
||||
manifest: { ...dataset.manifest, eligibility: 'exploratory' },
|
||||
};
|
||||
for (const response of [
|
||||
null,
|
||||
{},
|
||||
changedBar,
|
||||
changedTime,
|
||||
changedPolicy,
|
||||
nativeReplayFixture(4).dataset,
|
||||
]) {
|
||||
const { value, calls } = client(() => Response.json(response));
|
||||
await expect(value.canonicalDataset(dataset.manifest.hash)).rejects.toMatchObject({
|
||||
status: null,
|
||||
uncertain: false,
|
||||
});
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]!.init.method).toBe('GET');
|
||||
}
|
||||
});
|
||||
|
||||
test('invalid hashes, HTTP failures and aborts never query alternate data', async () => {
|
||||
const invalid = client(() => {
|
||||
throw new Error('No transport expected');
|
||||
});
|
||||
for (const input of ['../runs', 'a'.repeat(63), 'A'.repeat(64)]) {
|
||||
expect(() => invalid.value.canonicalDataset(input)).toThrow();
|
||||
}
|
||||
expect(invalid.calls).toHaveLength(0);
|
||||
for (const status of [401, 404, 409, 500]) {
|
||||
const { value, calls } = client(() =>
|
||||
Response.json({ error: 'Dataset unavailable' }, { status })
|
||||
);
|
||||
await expect(value.canonicalDataset('a'.repeat(64))).rejects.toMatchObject({
|
||||
status,
|
||||
uncertain: false,
|
||||
});
|
||||
expect(calls).toHaveLength(1);
|
||||
}
|
||||
const controller = new AbortController();
|
||||
const stalled = client(() => new Promise<Response>(() => {}));
|
||||
const pending = stalled.value.canonicalDataset('a'.repeat(64), controller.signal);
|
||||
controller.abort();
|
||||
await expect(pending).rejects.toMatchObject({ uncertain: false });
|
||||
expect(stalled.calls).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('canonical run inspection', () => {
|
||||
test('reads complete native finances and retained inputs through authenticated GET', async () => {
|
||||
const result = canonicalResultFixture();
|
||||
|
|
|
|||
|
|
@ -32,10 +32,13 @@ const payloadSql = 'SELECT payload FROM backtest_datasets WHERE hash=$1';
|
|||
const baseline = createDatasetV2(datasetInput());
|
||||
const path = (hash = baseline.manifest.hash) => `/api/v2/datasets/canonical/${hash}/export`;
|
||||
function fixture(load: () => Promise<unknown> = async () => baseline) {
|
||||
let researchEnabled = true;
|
||||
const payloadRead = mock(load);
|
||||
const query = mock(async (sql: string, values?: unknown[]) => {
|
||||
if (sql === 'SELECT id,enabled,policy FROM research_agents WHERE token_hash=$1') {
|
||||
return { rows: [{ id: agentId, enabled: true, policy: { allowedProjectIds: [] } }] };
|
||||
return {
|
||||
rows: [{ id: agentId, enabled: researchEnabled, policy: { allowedProjectIds: [] } }],
|
||||
};
|
||||
}
|
||||
if (sql !== payloadSql || values?.length !== 1) {
|
||||
throw new Error('Unexpected query: export must not write or read other tables');
|
||||
|
|
@ -69,7 +72,18 @@ function fixture(load: () => Promise<unknown> = async () => baseline) {
|
|||
headers: Record<string, string> = { Authorization: `Bearer ${tokens.admin}` },
|
||||
signal?: AbortSignal
|
||||
) => app.request(path(hash), { headers, signal });
|
||||
return { app, request, database, query, payloadRead, sourceRead, research };
|
||||
return {
|
||||
app,
|
||||
request,
|
||||
database,
|
||||
query,
|
||||
payloadRead,
|
||||
sourceRead,
|
||||
research,
|
||||
revokeResearch: () => {
|
||||
researchEnabled = false;
|
||||
},
|
||||
};
|
||||
}
|
||||
function responseHeaders(response: Response) {
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
||||
|
|
@ -268,11 +282,11 @@ describe('validated canonical dataset export', () => {
|
|||
).rejects.toThrow('cancelled after query');
|
||||
});
|
||||
|
||||
test('existing read, admin, service and browser credentials may export; anonymous and real research credentials may not', async () => {
|
||||
test('read, admin, service, browser and research credentials export; anonymous and revoked credentials do not', async () => {
|
||||
const f = fixture();
|
||||
expect((await f.request(baseline.manifest.hash, {})).status).toBe(401);
|
||||
expect(f.query).not.toHaveBeenCalled();
|
||||
for (const token of [tokens.read, tokens.admin, tokens.service]) {
|
||||
for (const token of [tokens.read, tokens.admin, tokens.service, tokens.research]) {
|
||||
expect(
|
||||
(await f.request(baseline.manifest.hash, { Authorization: `Bearer ${token}` })).status
|
||||
).toBe(200);
|
||||
|
|
@ -289,20 +303,13 @@ describe('validated canonical dataset export', () => {
|
|||
expect((await f.request(baseline.manifest.hash, { Cookie: cookie! })).status).toBe(200);
|
||||
}
|
||||
const before = f.payloadRead.mock.calls.length;
|
||||
f.revokeResearch();
|
||||
const denied = await f.request(baseline.manifest.hash, {
|
||||
Authorization: `Bearer ${tokens.research}`,
|
||||
});
|
||||
expect(denied.status).toBe(403);
|
||||
expect(denied.status).toBe(401);
|
||||
expect(denied.headers.get('Content-Disposition')).toBeNull();
|
||||
expect(f.payloadRead).toHaveBeenCalledTimes(before);
|
||||
// Positive control: this token is recognized by the real resolver for an allowed route.
|
||||
expect(
|
||||
await f.research.authenticate(
|
||||
new Request('http://localhost/api/v2/experiments', {
|
||||
headers: { Authorization: `Bearer ${tokens.research}` },
|
||||
})
|
||||
)
|
||||
).toEqual({ principal: agentId });
|
||||
expect(
|
||||
f.query.mock.calls.filter(call => call[0].includes('FROM research_agents'))
|
||||
).toHaveLength(2);
|
||||
|
|
|
|||
|
|
@ -118,6 +118,41 @@ test('operator-only provisioning fails closed without enabled research authentic
|
|||
}
|
||||
expect(query).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
test('resolver grants only exact immutable dataset exports among dataset operations', async () => {
|
||||
const query = mock(async () => ({ rows: [{ id: agent, enabled: true, policy: {} }] }));
|
||||
const service = new ResearchAgentsService({
|
||||
postgres: { query },
|
||||
} as unknown as IServiceContainer);
|
||||
const hash = 'a'.repeat(64);
|
||||
const check = (path: string, method = 'GET') =>
|
||||
service.authenticate(
|
||||
new Request(`http://localhost${path}`, {
|
||||
method,
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
);
|
||||
for (const method of ['GET', 'HEAD']) {
|
||||
expect(await check(`/api/v2/datasets/canonical/${hash}/export`, method)).toEqual({
|
||||
principal: agent,
|
||||
});
|
||||
}
|
||||
for (const [path, method] of [
|
||||
['/api/v2/datasets/canonical', 'GET'],
|
||||
[`/api/v2/datasets/canonical/${hash}`, 'GET'],
|
||||
[`/api/v2/datasets/canonical/${hash}/export/extra`, 'GET'],
|
||||
[`/api/v2/datasets/canonical/${hash.toUpperCase()}/export`, 'GET'],
|
||||
['/api/v2/datasets/canonical/invalid/export', 'GET'],
|
||||
['/api/v2/datasets/stored-eod/coverage', 'GET'],
|
||||
['/api/v2/datasets/canonical/preview', 'POST'],
|
||||
['/api/v2/datasets/canonical/retain', 'POST'],
|
||||
['/api/v2/datasets/canonical/stored-source', 'POST'],
|
||||
['/api/v2/datasets/stored-eod/inspect', 'POST'],
|
||||
[`/api/v2/datasets/canonical/${hash}/export`, 'POST'],
|
||||
]) {
|
||||
expect(((await check(path!, method)) as Response).status).toBe(403);
|
||||
}
|
||||
});
|
||||
|
||||
test('resolver exact write capabilities refuse trading, operators, foreign evidence and ownership impersonation', async () => {
|
||||
const projectId = randomUUID(),
|
||||
experimentId = randomUUID(),
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/Backt
|
|||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
|
||||
import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes';
|
||||
import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
|
||||
import { createResearchAgentRoutes } from '../../apps/stock/web-api/src/routes/research-agents.routes';
|
||||
import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes';
|
||||
|
|
@ -118,6 +119,7 @@ async function fixture() {
|
|||
app.route('/', createResearchRoutes(container));
|
||||
app.route('/', createExperimentRoutes(container));
|
||||
app.route('/', createBacktestV2Routes(container));
|
||||
app.route('/', createDatasetRoutes(container));
|
||||
const engine = new RustBacktestAdapter({
|
||||
logger,
|
||||
});
|
||||
|
|
@ -258,6 +260,71 @@ async function fixture() {
|
|||
}
|
||||
|
||||
describe.skipIf(!url)('AI research workflow through authenticated APIs and Rust', () => {
|
||||
test('research credentials export known immutable snapshots with exact read-only scope', async () => {
|
||||
const f = await fixture();
|
||||
const hash = f.dataset.manifest.hash;
|
||||
const totals = async () =>
|
||||
(
|
||||
await f.pool.query(`SELECT
|
||||
(SELECT count(*)::int FROM runs) AS runs,
|
||||
(SELECT count(*)::int FROM research_experiments) AS experiments,
|
||||
(SELECT count(*)::int FROM backtest_datasets) AS datasets`)
|
||||
).rows[0];
|
||||
const before = await totals();
|
||||
expect(await f.client.canonicalDataset(hash)).toEqual(f.dataset);
|
||||
const head = await f.transport(
|
||||
`http://127.0.0.1:2003/api/v2/datasets/canonical/${hash}/export`,
|
||||
{
|
||||
method: 'HEAD',
|
||||
headers: { Authorization: `Bearer ${f.provisioned.token}` },
|
||||
}
|
||||
);
|
||||
expect(head.status).toBe(200);
|
||||
expect(head.headers.get('cache-control')).toBe('no-store');
|
||||
expect(head.headers.get('x-content-type-options')).toBe('nosniff');
|
||||
expect(head.headers.get('content-disposition')).toBe(
|
||||
`attachment; filename="dataset-${hash}.json"`
|
||||
);
|
||||
expect(await head.text()).toBe('');
|
||||
for (const [path, method] of [
|
||||
['/datasets/canonical', 'GET'],
|
||||
['/datasets/stored-eod/coverage', 'GET'],
|
||||
['/datasets/canonical/preview', 'POST'],
|
||||
['/datasets/canonical/retain', 'POST'],
|
||||
['/datasets/canonical/stored-source', 'POST'],
|
||||
['/datasets/stored-eod/inspect', 'POST'],
|
||||
[`/datasets/canonical/${hash}/export`, 'POST'],
|
||||
]) {
|
||||
const response = await f.transport(`http://127.0.0.1:2003/api/v2${path}`, {
|
||||
method,
|
||||
headers: { Authorization: `Bearer ${f.provisioned.token}` },
|
||||
});
|
||||
expect(response.status).toBe(403);
|
||||
}
|
||||
await expect(f.client.canonicalDataset('0'.repeat(64))).rejects.toMatchObject({
|
||||
status: 404,
|
||||
uncertain: false,
|
||||
});
|
||||
expect(await totals()).toEqual(before);
|
||||
const badHash = 'f'.repeat(64);
|
||||
await f.pool.query('INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2::jsonb)', [
|
||||
badHash,
|
||||
f.dataset,
|
||||
]);
|
||||
const afterFixtureInsert = await totals();
|
||||
await expect(f.client.canonicalDataset(badHash)).rejects.toMatchObject({
|
||||
status: 409,
|
||||
uncertain: false,
|
||||
});
|
||||
expect(await totals()).toEqual(afterFixtureInsert);
|
||||
await f.agents.update(f.provisioned.agent.id, { expectedRevision: 1, enabled: false });
|
||||
await expect(f.client.canonicalDataset(hash)).rejects.toMatchObject({
|
||||
status: 401,
|
||||
uncertain: false,
|
||||
});
|
||||
expect(f.executionErrors).toEqual([]);
|
||||
});
|
||||
|
||||
test('defaulted candidate validation accepts, reopens and replays the exact original input', async () => {
|
||||
const f = await fixture();
|
||||
const plan = f.suggestions();
|
||||
|
|
@ -607,6 +674,34 @@ describe.skipIf(!url)('AI research workflow through authenticated APIs and Rust'
|
|||
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(
|
||||
before
|
||||
);
|
||||
const original = await f.client.canonicalRunResult(reference.runId);
|
||||
const snapshot = await f.client.canonicalDataset(original.request.datasetHash);
|
||||
expect(snapshot).toEqual(
|
||||
(
|
||||
await f.pool.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [
|
||||
original.request.datasetHash,
|
||||
])
|
||||
).rows[0].payload
|
||||
);
|
||||
const template = await f.api.getBacktest(original.backtestId);
|
||||
if (!template) {
|
||||
throw new Error('Missing original template');
|
||||
}
|
||||
await f.api.updateBacktest(original.backtestId, {
|
||||
startDate: new Date(f.dataset.manifest.bounds.tradeStart).toISOString(),
|
||||
endDate: new Date(f.dataset.manifest.bounds.tradeEnd).toISOString(),
|
||||
symbols: f.dataset.manifest.executionSeries.map(series => series.instrumentId),
|
||||
config: {
|
||||
...template.config,
|
||||
datasetHash: f.dataset.manifest.hash,
|
||||
dataFrequency: f.dataset.manifest.series[0]!.interval,
|
||||
},
|
||||
});
|
||||
expect(await f.client.canonicalDataset(original.request.datasetHash)).toEqual(snapshot);
|
||||
expect(await f.client.canonicalRunResult(reference.runId)).toEqual(original);
|
||||
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(
|
||||
before
|
||||
);
|
||||
await f.agents.update(f.provisioned.agent.id, {
|
||||
expectedRevision: f.provisioned.agent.revision,
|
||||
enabled: false,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue