feat(research): retain exact experiment and report citations in findings
This commit is contained in:
parent
46a4f13acd
commit
06039d17ba
36 changed files with 4170 additions and 253 deletions
|
|
@ -17,12 +17,17 @@ function fixture(
|
|||
security: 'enabled' | 'disabled' | 'absent' = 'enabled',
|
||||
query: Query = async () => {
|
||||
throw new Error('Rejected request reached storage');
|
||||
}
|
||||
},
|
||||
allowReadTransaction = false
|
||||
) {
|
||||
const transactionQuery = mock(query);
|
||||
const database = {
|
||||
query: mock(query),
|
||||
transaction: mock(async () => {
|
||||
throw new Error('Rejected request reached transaction');
|
||||
transaction: mock(async (callback: (client: { query: Query }) => Promise<unknown>) => {
|
||||
if (!allowReadTransaction) {
|
||||
throw new Error('Rejected request reached transaction');
|
||||
}
|
||||
return callback({ query: transactionQuery });
|
||||
}),
|
||||
};
|
||||
const logger = { error: mock((_message: string, _details?: unknown) => {}) };
|
||||
|
|
@ -44,6 +49,7 @@ function fixture(
|
|||
app.post('/api/v2/unrelated', c => c.json({ ok: true }));
|
||||
return {
|
||||
database,
|
||||
transactionQuery,
|
||||
logger,
|
||||
app,
|
||||
request(
|
||||
|
|
@ -349,79 +355,94 @@ describe('research HTTP credential and transport boundary', () => {
|
|||
const runId = randomUUID();
|
||||
const backtestId = randomUUID();
|
||||
const stamp = new Date('2026-01-01');
|
||||
const f = fixture('enabled', async sql => {
|
||||
if (sql.includes('FROM analysis_artifacts WHERE')) {
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
id: artifactId,
|
||||
project_id: projectId,
|
||||
hypothesis_revision_id: null,
|
||||
kind: 'finding',
|
||||
owner_principal: 'operator',
|
||||
updated_by: 'operator',
|
||||
archived_at: null,
|
||||
created_at: stamp,
|
||||
updated_at: stamp,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (sql.includes('FROM analysis_artifact_revisions WHERE')) {
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
id: revisionId,
|
||||
artifact_id: artifactId,
|
||||
ordinal: 1,
|
||||
title: 'Retained finding',
|
||||
body: 'Narrative is not a metric',
|
||||
submitted_by: 'operator',
|
||||
content_origin: 'human',
|
||||
created_at: stamp,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (sql.includes('FROM analysis_evidence WHERE')) {
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
revision_id: revisionId,
|
||||
ordinal: 1,
|
||||
run_id: runId,
|
||||
metrics_version: 'canonical-analytics/v1',
|
||||
metric_path: 'analytics.metrics.totalReturn',
|
||||
strategy_version_id: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (sql.includes('FROM runs WHERE')) {
|
||||
return { rows: [{ id: runId, backtest_id: backtestId, status: 'completed' }] };
|
||||
}
|
||||
if (sql.includes('FROM backtest_results br')) {
|
||||
// The reference is valid. This damage is in retained server evidence,
|
||||
// and must not be classified as a malformed client request.
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
run_id: runId,
|
||||
backtest_id: backtestId,
|
||||
run_status: 'completed',
|
||||
canonical_result: { kind: 'canonical-result/v1' },
|
||||
request_snapshot: { kind: 'canonical-research/v1', 'private-retained-marker': true },
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
throw new Error(`Unexpected evidence query: ${sql}`);
|
||||
});
|
||||
const f = fixture(
|
||||
'enabled',
|
||||
async sql => {
|
||||
if (sql === 'SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY') {
|
||||
return { rows: [] };
|
||||
}
|
||||
if (sql.includes('FROM analysis_artifacts WHERE')) {
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
id: artifactId,
|
||||
project_id: projectId,
|
||||
hypothesis_revision_id: null,
|
||||
kind: 'finding',
|
||||
owner_principal: 'operator',
|
||||
updated_by: 'operator',
|
||||
archived_at: null,
|
||||
created_at: stamp,
|
||||
updated_at: stamp,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (sql.includes('FROM analysis_artifact_revisions WHERE')) {
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
id: revisionId,
|
||||
artifact_id: artifactId,
|
||||
ordinal: 1,
|
||||
title: 'Retained finding',
|
||||
body: 'Narrative is not a metric',
|
||||
submitted_by: 'operator',
|
||||
content_origin: 'human',
|
||||
created_at: stamp,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (sql.includes('FROM analysis_evidence WHERE')) {
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
revision_id: revisionId,
|
||||
ordinal: 1,
|
||||
run_id: runId,
|
||||
metrics_version: 'canonical-analytics/v1',
|
||||
metric_path: 'analytics.metrics.totalReturn',
|
||||
strategy_version_id: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (sql.includes('FROM runs WHERE')) {
|
||||
return { rows: [{ id: runId, backtest_id: backtestId, status: 'completed' }] };
|
||||
}
|
||||
if (sql.includes('FROM backtest_results br')) {
|
||||
// The reference is valid. This damage is in retained server evidence,
|
||||
// and must not be classified as a malformed client request.
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
run_id: runId,
|
||||
backtest_id: backtestId,
|
||||
run_status: 'completed',
|
||||
canonical_result: { kind: 'canonical-result/v1' },
|
||||
request_snapshot: {
|
||||
kind: 'canonical-research/v1',
|
||||
'private-retained-marker': true,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
throw new Error(`Unexpected evidence query: ${sql}`);
|
||||
},
|
||||
true
|
||||
);
|
||||
const response = await f.request(`analysis-artifacts/${artifactId}`, undefined, 'read');
|
||||
expect(response.status).toBe(500);
|
||||
expect(await response.json()).toEqual({ error: 'Research workspace unavailable' });
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
||||
expect(f.database.query.mock.calls).toHaveLength(5);
|
||||
expect(f.database.query.mock.calls).toHaveLength(0);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(1);
|
||||
expect(f.transactionQuery.mock.calls).toHaveLength(6);
|
||||
expect(f.transactionQuery.mock.calls[0]?.[0]).toBe(
|
||||
'SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'
|
||||
);
|
||||
expect(f.logger.error.mock.calls).toHaveLength(1);
|
||||
const diagnostic = f.logger.error.mock.calls[0]?.[1] as { error?: unknown } | undefined;
|
||||
expect(diagnostic?.error).toBeInstanceOf(Error);
|
||||
|
|
|
|||
149
test/integration/research-source-evidence-api.test.ts
Normal file
149
test/integration/research-source-evidence-api.test.ts
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { describe, expect, mock, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes';
|
||||
|
||||
const tokens = {
|
||||
operator: 'research-admin-fixture-not-a-real-secret-1234',
|
||||
service: 'research-service-fixture-not-a-real-secret-1234',
|
||||
read: 'research-read-fixture-not-a-real-secret-1234',
|
||||
};
|
||||
type Query = (sql: string, values?: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;
|
||||
function fixture(
|
||||
security: 'enabled' | 'disabled' | 'absent' = 'enabled',
|
||||
query: Query = async () => {
|
||||
throw new Error('Rejected request reached storage');
|
||||
}
|
||||
) {
|
||||
const database = {
|
||||
query: mock(query),
|
||||
transaction: mock(async <T>(work: (client: { query: Query }) => Promise<T>) => work({ query })),
|
||||
};
|
||||
const logger = { error: mock((_message: string, _details?: unknown) => {}) };
|
||||
const app = new Hono();
|
||||
if (security !== 'absent') {
|
||||
createHttpSecurity({
|
||||
adminToken: tokens.operator,
|
||||
serviceToken: tokens.service,
|
||||
readToken: tokens.read,
|
||||
environment: 'test',
|
||||
hostname: '127.0.0.1',
|
||||
disabled: security === 'disabled',
|
||||
}).mount(app);
|
||||
}
|
||||
app.route(
|
||||
'/',
|
||||
createResearchRoutes({ postgres: database, logger } as unknown as IServiceContainer)
|
||||
);
|
||||
app.post('/api/v2/unrelated', c => c.json({ ok: true }));
|
||||
return {
|
||||
database,
|
||||
logger,
|
||||
app,
|
||||
request(
|
||||
path: string,
|
||||
body?: unknown,
|
||||
role?: keyof typeof tokens,
|
||||
method = body === undefined ? 'GET' : 'POST',
|
||||
extra: Record<string, string> = {}
|
||||
) {
|
||||
return app.request(`/api/v2/${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}),
|
||||
'Content-Type': 'application/json',
|
||||
...extra,
|
||||
},
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const projectId = randomUUID(),
|
||||
runId = randomUUID();
|
||||
const source = { kind: 'experiment/v1', experimentId: randomUUID(), previewHash: 'a'.repeat(64) };
|
||||
const body = {
|
||||
kind: 'finding',
|
||||
title: 'Evidence',
|
||||
body: 'Claim',
|
||||
source,
|
||||
evidence: [
|
||||
{
|
||||
runId,
|
||||
metricsVersion: 'canonical-analytics/v1',
|
||||
metricPath: 'analytics.metrics.totalReturn',
|
||||
},
|
||||
],
|
||||
};
|
||||
describe('source findings HTTP boundary', () => {
|
||||
test('malformed source metadata rejects before storage and write credentials remain mandatory', async () => {
|
||||
for (const change of [
|
||||
{ ...source, extra: true },
|
||||
{ ...source, previewHash: null },
|
||||
{ ...source, experimentId: 'bad' },
|
||||
{ ...source, kind: 'chronological-report/v1' },
|
||||
]) {
|
||||
const f = fixture();
|
||||
expect(
|
||||
(
|
||||
await f.request(
|
||||
`research-projects/${projectId}/analysis-artifacts`,
|
||||
{ ...body, source: change },
|
||||
'operator'
|
||||
)
|
||||
).status
|
||||
).toBe(400);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
}
|
||||
const f = fixture();
|
||||
expect(
|
||||
(await f.request(`research-projects/${projectId}/analysis-artifacts`, body)).status
|
||||
).toBe(401);
|
||||
expect(
|
||||
(await f.request(`research-projects/${projectId}/analysis-artifacts`, body, 'read')).status
|
||||
).toBe(403);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
});
|
||||
test('missing source is422 without exposing storage details; unexpected errors remain sanitized500', async () => {
|
||||
for (const broken of [false, true]) {
|
||||
const f = fixture('enabled', async sql => {
|
||||
if (sql.includes('FROM research_projects')) {
|
||||
return { rows: [{ id: projectId, archived_at: null }] };
|
||||
}
|
||||
if (sql.startsWith('INSERT INTO analysis_artifacts(')) {
|
||||
return { rows: [{ id: randomUUID() }] };
|
||||
}
|
||||
if (broken) {
|
||||
throw new Error('private database details');
|
||||
}
|
||||
return { rows: [] };
|
||||
});
|
||||
const response = await f.request(
|
||||
`research-projects/${projectId}/analysis-artifacts`,
|
||||
body,
|
||||
'operator'
|
||||
);
|
||||
expect(response.status).toBe(broken ? 500 : 422);
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
||||
if (broken) {
|
||||
expect(await response.json()).toEqual({ error: 'Research workspace unavailable' });
|
||||
}
|
||||
}
|
||||
});
|
||||
test('artifact reads select repeatable read-only mode before storage and do not require mutation credentials', async () => {
|
||||
const calls: string[] = [];
|
||||
const f = fixture('enabled', async sql => {
|
||||
calls.push(sql);
|
||||
return { rows: [] };
|
||||
});
|
||||
const response = await f.request(`analysis-artifacts/${randomUUID()}`, undefined, 'read');
|
||||
expect(response.status).toBe(404);
|
||||
expect(calls[0]).toBe('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
expect(calls.every(sql => !sql.includes('FOR UPDATE') && !sql.includes('FOR SHARE'))).toBe(
|
||||
true
|
||||
);
|
||||
});
|
||||
});
|
||||
104
test/integration/research-source-evidence.test.ts
Normal file
104
test/integration/research-source-evidence.test.ts
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
import { describe, expect, mock, test } from 'bun:test';
|
||||
import {
|
||||
createResearchArtifactSchema,
|
||||
parseResearchInput,
|
||||
researchFindingSourceSchema,
|
||||
reviseResearchArtifactSchema,
|
||||
} from '@stock-bot/stock-config/research';
|
||||
import type { BacktestResultQuery } from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { verifyResearchSource } from '../../apps/stock/web-api/src/services/research-source-evidence';
|
||||
|
||||
const id = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
|
||||
const source = { kind: 'experiment/v1' as const, experimentId: id, previewHash: 'a'.repeat(64) };
|
||||
const canonical = {
|
||||
runId: id,
|
||||
metricsVersion: 'canonical-analytics/v1' as const,
|
||||
metricPath: 'analytics.metrics.totalReturn',
|
||||
};
|
||||
describe('finding source contract', () => {
|
||||
test('strict source identities normalize UUIDs and reject client measurements, mixed kinds and missing hashes', () => {
|
||||
expect(
|
||||
researchFindingSourceSchema.parse({ ...source, experimentId: id.toUpperCase() })
|
||||
).toEqual(source);
|
||||
for (const raw of [
|
||||
{ ...source, previewHash: 'A'.repeat(64) },
|
||||
{ ...source, previewHash: null },
|
||||
{ ...source, experimentId: null },
|
||||
{ ...source, totalReturn: 0 },
|
||||
{ ...source, reportId: id },
|
||||
{ ...source, kind: 'unknown' },
|
||||
{
|
||||
kind: 'chronological-report/v1',
|
||||
validationId: id,
|
||||
previewHash: source.previewHash,
|
||||
reportId: id,
|
||||
},
|
||||
{
|
||||
kind: 'walk-forward-report/v1',
|
||||
walkForwardId: id,
|
||||
previewHash: source.previewHash,
|
||||
reportId: id,
|
||||
reportHash: 'bad',
|
||||
},
|
||||
]) {
|
||||
expect(researchFindingSourceSchema.safeParse(raw).success).toBe(false);
|
||||
}
|
||||
for (const kind of ['chronological-report/v1', 'walk-forward-report/v1'] as const) {
|
||||
const owner =
|
||||
kind === 'chronological-report/v1'
|
||||
? { validationId: id.toUpperCase() }
|
||||
: { walkForwardId: id.toUpperCase() };
|
||||
const parsed = researchFindingSourceSchema.parse({
|
||||
kind,
|
||||
...owner,
|
||||
previewHash: source.previewHash,
|
||||
reportId: id.toUpperCase(),
|
||||
reportHash: 'b'.repeat(64),
|
||||
});
|
||||
expect('reportId' in parsed && parsed.reportId).toBe(id);
|
||||
}
|
||||
});
|
||||
test('old create and revise requests preserve the distinction between omitted and explicitly detached sources', () => {
|
||||
const body = { title: 'Observation', body: 'Unvalidated narrative', evidence: [canonical] };
|
||||
expect(
|
||||
parseResearchInput(createResearchArtifactSchema, { ...body, kind: 'finding' }).source
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
parseResearchInput(reviseResearchArtifactSchema, { ...body, expectedRevision: 1 }).source
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
parseResearchInput(reviseResearchArtifactSchema, {
|
||||
...body,
|
||||
expectedRevision: 1,
|
||||
source: null,
|
||||
}).source
|
||||
).toBeNull();
|
||||
expect(
|
||||
parseResearchInput(createResearchArtifactSchema, { ...body, kind: 'note', source }).source
|
||||
).toEqual(source);
|
||||
});
|
||||
test('source cannot substitute for canonical metric evidence; unavailable source fails before any result reader', async () => {
|
||||
const query = mock(async () => ({ rows: [] })),
|
||||
read = mock(async () => null);
|
||||
const database = { query } as unknown as BacktestResultQuery;
|
||||
for (const evidence of [
|
||||
[],
|
||||
[
|
||||
{
|
||||
runId: id,
|
||||
metricsVersion: 'legacy-display/v1' as const,
|
||||
metricPath: 'metrics.totalReturn',
|
||||
},
|
||||
],
|
||||
]) {
|
||||
await expect(verifyResearchSource(source, evidence, database, read)).rejects.toMatchObject({
|
||||
status: 422,
|
||||
});
|
||||
}
|
||||
expect(query.mock.calls).toHaveLength(0);
|
||||
await expect(verifyResearchSource(source, [canonical], database, read)).rejects.toMatchObject({
|
||||
status: 422,
|
||||
});
|
||||
expect(read.mock.calls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
1321
test/integration/research-source-ui.test.tsx
Normal file
1321
test/integration/research-source-ui.test.tsx
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue