feat(research): retain exact experiment and report citations in findings

This commit is contained in:
Boki 2026-10-24 14:42:14 -04:00
parent 46a4f13acd
commit 06039d17ba
36 changed files with 4170 additions and 253 deletions

View file

@ -561,7 +561,7 @@ export class ExperimentsService {
async readDetail(database: Query, id: string): Promise<WorkbenchExperimentDetail> {
const row = (
await database.query(
`SELECT ${summaryColumns},e.preview FROM research_experiments e WHERE e.id=$1`,
`SELECT ${summaryColumns},e.preview,(to_jsonb(e) ? 'validation_phase' AND to_jsonb(e)->'validation_phase' = 'null'::jsonb) AS standalone FROM research_experiments e WHERE e.id=$1`,
[id]
)
).rows[0];
@ -686,6 +686,12 @@ export class ExperimentsService {
counts[run.status as keyof ExperimentCounts]++;
}
}
return { ...summary(row), counts, preview, trials } as WorkbenchExperimentDetail;
return {
...summary(row),
standalone: row.standalone === true,
counts,
preview,
trials,
} as WorkbenchExperimentDetail;
}
}

View file

@ -11,9 +11,11 @@ import type {
CanonicalMetrics,
ResearchEvidence,
ResearchEvidenceReference,
ResearchFindingSource,
} from '@stock-bot/types';
import { BacktestServiceV2, type BacktestResultQuery } from './backtest-v2.service';
import { ResearchError } from './research-errors';
import { verifyResearchSource } from './research-source-evidence';
function unitOf(path: string): ResearchEvidence['unit'] {
const name = path.split('.').at(-1);
@ -128,6 +130,26 @@ export class ResearchEvidenceResolver {
this.results = new BacktestServiceV2(container);
}
async resolveAll(
references: ResearchEvidenceReference[],
source: ResearchFindingSource | null,
database: BacktestResultQuery
): Promise<ResearchEvidence[]> {
if (!source) {
return Promise.all(references.map(reference => this.resolve(reference, database)));
}
const results = await verifyResearchSource(source, references, database, (id, query) =>
this.results.getRunResults(id, query)
);
return references.map(reference => {
const result = results.get(reference.runId);
if (!result) {
throw new Error('Verified source result is missing');
}
return projectResearchEvidence(reference, result);
});
}
async resolve(
input: ResearchEvidenceReference,
database: BacktestResultQuery = this.database

View file

@ -0,0 +1,341 @@
import type { QueryResultRow } from 'pg';
import { at } from '@stock-bot/invariants';
import {
isCanonicalRunResult,
type CanonicalRunResult,
type ResearchRunResult,
} from '@stock-bot/stock-config/canonical-research';
import type {
ChronologicalValidationReport,
ChronologicalValidationSelection,
ValidationPhase,
} from '@stock-bot/stock-config/chronological-validation';
import type { WorkbenchExperimentPreview } from '@stock-bot/stock-config/cost-sensitivity';
import type { ExperimentCandidate } from '@stock-bot/stock-config/experiments';
import type { WalkForwardSegment } from '@stock-bot/stock-config/walk-forward';
import type { ResearchEvidenceReference, ResearchFindingSource } from '@stock-bot/types';
import type { BacktestResultQuery } from './backtest-v2.service';
import { retainedWorkbenchPreview, workbenchTrialRequest } from './cost-sensitivity-input';
import { ResearchError } from './research-errors';
import {
publicValidationDocument,
retainedValidationPreview,
selectValidationWinner,
validationEqual,
validationEvidence,
validationPhasePreview,
} from './validation-evidence';
import { publicWalkForwardReport, retainedWalkForwardPreview } from './walk-forward-input';
function retained(condition: unknown, message: string): asserts condition {
if (!condition) {
throw new Error(`Retained finding source ${message}`);
}
}
function requested(condition: unknown, message: string): asserts condition {
if (!condition) {
throw new ResearchError(422, message);
}
}
function documentMetadata(value: Record<string, unknown>, report: boolean): void {
const receipt = value._receipt as { key?: unknown; hash?: unknown } | undefined;
retained(
typeof value.id === 'string' &&
/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value.id) &&
typeof value.createdAt === 'string' &&
Number.isFinite(Date.parse(value.createdAt)) &&
(value.principal === 'operator' || value.principal === 'service') &&
typeof receipt?.key === 'string' &&
/^[!-~]{1,200}$/.test(receipt.key) &&
typeof receipt.hash === 'string' &&
/^[a-f0-9]{64}$/.test(receipt.hash) &&
(!report ||
(Array.isArray(value.limitations) &&
value.limitations.every(item => typeof item === 'string'))),
'document metadata is invalid'
);
}
type ResultReader = (
id: string,
database: BacktestResultQuery
) => Promise<ResearchRunResult | null>;
/** Historical provenance only. The existing canonical reader owns all financial validation. */
export async function verifyResearchSource(
source: ResearchFindingSource,
references: ResearchEvidenceReference[],
database: BacktestResultQuery,
readResult: ResultReader
): Promise<Map<string, CanonicalRunResult>> {
requested(
references.length > 0 && references.every(r => r.metricsVersion === 'canonical-analytics/v1'),
'A finding source requires at least one canonical metric reference'
);
const results = new Map<string, CanonicalRunResult>();
const experiment = async (id: string) =>
(await database.query('SELECT * FROM research_experiments WHERE id=$1', [id])).rows[0];
const previewOf = (row: QueryResultRow): WorkbenchExperimentPreview => {
const preview = retainedWorkbenchPreview(row.preview);
retained(
preview.previewHash === row.preview_hash &&
preview.input.backtestId === row.backtest_id &&
preview.input.name === row.name,
'experiment identity mismatch'
);
return preview;
};
const resultOf = async (
row: QueryResultRow,
preview: WorkbenchExperimentPreview,
candidate: ExperimentCandidate
) => {
retained(
row.status === 'completed' &&
row.backtest_id === preview.input.backtestId &&
row.trial_key === candidate.trialKey &&
row.trial_index === candidate.index,
'completed trial identity mismatch'
);
const request = workbenchTrialRequest(preview, candidate, row.id);
retained(
validationEqual(row.request_snapshot, request) && row.dataset_hash === request.datasetHash,
'trial request mismatch'
);
let result = results.get(row.id);
if (!result) {
const saved = await readResult(row.id, database);
retained(
saved &&
isCanonicalRunResult(saved) &&
saved.runId === row.id &&
saved.backtestId === row.backtest_id &&
saved.status === 'completed',
'canonical result unavailable'
);
result = saved;
results.set(row.id, result);
}
retained(validationEqual(result.request, request), 'result request mismatch');
return result;
};
const phaseEvidence = async (
row: QueryResultRow,
phase: ValidationPhase,
sourceIndex?: number
) => {
const preview = previewOf(row);
retained(
preview.version === 'research-experiment-preview/v1' && row.validation_phase === phase,
'phase kind mismatch'
);
const runs = (
await database.query('SELECT * FROM runs WHERE experiment_id=$1 ORDER BY trial_index', [
row.id,
])
).rows;
retained(runs.length === preview.candidates.length, 'phase run count mismatch');
const evidence = [];
for (const [index, candidate] of preview.candidates.entries()) {
const run = at(runs, index);
const result = await resultOf(run, preview, candidate);
evidence.push(
validationEvidence(phase, row.id, candidate, sourceIndex ?? candidate.index, result)
);
}
return evidence;
};
const chronological = async (root: QueryResultRow): Promise<ChronologicalValidationReport> => {
retained(
root.validation_phase === 'train' &&
root.validation_parent_id === null &&
root.validation_selection &&
root.validation_report,
'sealed chronological report unavailable'
);
documentMetadata(root.validation_selection, false);
documentMetadata(root.validation_report, true);
const preview = retainedValidationPreview(root.validation_manifest);
const selection = publicValidationDocument<ChronologicalValidationSelection>(
root.validation_selection,
'selectionHash'
);
const report = publicValidationDocument<ChronologicalValidationReport>(
root.validation_report,
'reportHash'
);
retained(
preview.input.backtestId === root.backtest_id &&
validationEqual(previewOf(root), validationPhasePreview(preview, 'train')),
'training preview mismatch'
);
retained(
selection.version === 'chronological-validation-selection/v1' &&
selection.validationId === root.id &&
selection.previewHash === preview.previewHash &&
report.version === 'chronological-validation-report/v1' &&
report.validationId === root.id &&
report.previewHash === preview.previewHash &&
report.selectionHash === selection.selectionHash &&
report.reset === 'initial-capital-empty-positions',
'chronological report identity mismatch'
);
const training = await phaseEvidence(root, 'train');
const winner = selectValidationWinner(previewOf(root).candidates, training);
retained(
validationEqual(selection.training, training) &&
validationEqual(report.training, training) &&
validationEqual(selection.winner, winner),
'training selection or report mismatch'
);
const children = (
await database.query(
'SELECT * FROM research_experiments WHERE validation_parent_id=$1 ORDER BY validation_phase',
[root.id]
)
).rows;
retained(children.length === 2, 'holdout membership mismatch');
for (const phase of ['validation', 'test'] as const) {
const child = children.find(
item => item.id === selection.holdoutExperimentIds[phase] && item.validation_phase === phase
);
retained(
child &&
child.backtest_id === root.backtest_id &&
validationEqual(
previewOf(child),
validationPhasePreview(preview, phase, winner, selection.reviewId)
),
'holdout preview or membership mismatch'
);
const evidence = await phaseEvidence(child, phase, winner.index);
retained(
evidence.length === 1 && validationEqual(report[phase], at(evidence, 0)),
'holdout report mismatch'
);
}
return report;
};
try {
let members: Set<string>;
if (source.kind === 'experiment/v1') {
const row = await experiment(source.experimentId);
requested(
row && row.validation_phase === null,
'Source must be a retained standalone experiment'
);
const preview = previewOf(row);
requested(
preview.previewHash === source.previewHash,
'Source experiment preview does not match'
);
members = new Set();
for (const reference of references) {
const run = (
await database.query('SELECT * FROM runs WHERE id=$1 AND experiment_id=$2', [
reference.runId,
row.id,
])
).rows[0];
requested(
run && run.status === 'completed',
'Evidence must be a completed source experiment trial'
);
const candidate = preview.candidates[run.trial_index];
retained(candidate, 'trial candidate unavailable');
await resultOf(run, preview, candidate);
members.add(run.id);
}
} else if (source.kind === 'chronological-report/v1') {
const row = await experiment(source.validationId);
requested(
row && row.validation_phase === 'train' && row.validation_report,
'Source requires a sealed chronological report'
);
const report = await chronological(row);
requested(
report.id === source.reportId &&
report.reportHash === source.reportHash &&
report.previewHash === source.previewHash,
'Source chronological report does not match'
);
members = new Set(
[...report.training, report.validation, report.test].map(item => item.runId)
);
} else {
const header = (
await database.query('SELECT * FROM research_walk_forwards WHERE id=$1', [
source.walkForwardId,
])
).rows[0];
requested(header && header.report, 'Source requires a sealed walk-forward report');
documentMetadata(header.report, true);
const preview = retainedWalkForwardPreview(header.preview),
report = publicWalkForwardReport(header.report);
retained(
header.preview_hash === preview.previewHash &&
header.backtest_id === preview.input.backtestId &&
header.name === preview.input.name &&
Array.isArray(header.member_ids) &&
header.member_ids.length === preview.windows.length &&
new Set(header.member_ids).size === header.member_ids.length,
'walk-forward header identity mismatch'
);
retained(
report.version === 'walk-forward-report/v1' &&
report.walkForwardId === header.id &&
report.previewHash === preview.previewHash &&
report.reset === 'initial-capital-empty-positions',
'walk-forward report identity mismatch'
);
requested(
report.id === source.reportId &&
report.reportHash === source.reportHash &&
report.previewHash === source.previewHash,
'Source walk-forward report does not match'
);
const rows = (
await database.query(
'SELECT * FROM research_experiments WHERE walk_forward_id=$1 ORDER BY walk_forward_index',
[header.id]
)
).rows;
retained(rows.length === header.member_ids.length, 'walk-forward member count mismatch');
const segments: WalkForwardSegment[] = [];
for (const [index, row] of rows.entries()) {
const window = at(preview.windows, index);
retained(
row.id === header.member_ids[index] &&
row.walk_forward_index === index &&
row.backtest_id === header.backtest_id &&
validationEqual(row.validation_manifest, window.preview),
'walk-forward member identity mismatch'
);
const member = await chronological(row);
segments.push({
index,
validationId: row.id,
previewHash: member.previewHash,
selectionHash: member.selectionHash,
reportId: member.id,
reportHash: member.reportHash,
validation: member.validation,
test: member.test,
});
}
retained(validationEqual(report.segments, segments), 'walk-forward segment report mismatch');
members = new Set(
segments.flatMap(segment => [segment.validation.runId, segment.test.runId])
);
}
requested(
references.every(reference => members.has(reference.runId)),
'Evidence run does not belong to the selected source'
);
return results;
} catch (cause) {
if (cause instanceof ResearchError) {
throw cause;
}
throw new Error('Retained research source could not be verified', { cause });
}
}

View file

@ -8,6 +8,7 @@ import {
createResearchProjectSchema,
parseResearchInput,
researchActorSchema,
researchFindingSourceSchema,
researchIdSchema,
reviseResearchArtifactSchema,
reviseResearchHypothesisSchema,
@ -19,7 +20,9 @@ import type {
ResearchArtifactRevision,
ResearchAuthorship,
ResearchContentOrigin,
ResearchEvidence,
ResearchEvidenceReference,
ResearchFindingSource,
ResearchHypothesis,
ResearchHypothesisRevision,
ResearchProject,
@ -90,6 +93,37 @@ function active(row: QueryResultRow, label: string): void {
}
}
function findingSource(raw: unknown): ResearchFindingSource | null {
if (raw === null || raw === undefined) {
return null;
}
try {
return researchFindingSourceSchema.parse(raw);
} catch (cause) {
throw new Error('Retained finding source identity is invalid', { cause });
}
}
function artifactRevisionValue(
row: QueryResultRow,
evidence: ResearchEvidence[],
source: ResearchFindingSource | null
): ResearchArtifactRevision {
return {
id: row.id,
artifactId: row.artifact_id,
ordinal: row.ordinal,
title: row.title,
body: row.body,
submittedBy: row.submitted_by,
contentOrigin: row.content_origin,
validationState: 'unvalidated',
evidenceState: evidence.length ? 'referenced' : 'none',
evidence,
source,
createdAt: iso(row.created_at),
};
}
/** Metadata transactions only. The existing result reader owns every measured value. */
export class ResearchService {
private readonly database;
@ -320,14 +354,18 @@ export class ResearchService {
}
async listArtifacts(projectId: string, includeArchived = false): Promise<ResearchArtifact[]> {
await this.getProject(projectId);
const rows = (
await this.database.query(
'SELECT * FROM analysis_artifacts WHERE project_id=$1 AND ($2::boolean OR archived_at IS NULL) ORDER BY created_at DESC,id',
[projectId, includeArchived]
)
).rows;
return Promise.all(rows.map(row => this.artifact(this.database, row)));
researchIdSchema.parse(projectId);
return this.database.transaction(async client => {
await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
await this.projectRow(client, projectId);
const rows = (
await client.query(
'SELECT * FROM analysis_artifacts WHERE project_id=$1 AND ($2::boolean OR archived_at IS NULL) ORDER BY created_at DESC,id',
[projectId, includeArchived]
)
).rows;
return Promise.all(rows.map(row => this.artifact(client, row)));
});
}
async createArtifact(
projectId: string,
@ -362,26 +400,36 @@ export class ResearchService {
).rows[0],
'Created artifact'
);
await this.insertArtifactRevision(client, row.id, 1, data, author);
return this.artifact(client, row);
const revision = await this.insertArtifactRevision(
client,
row.id,
1,
{ ...data, source: data.source ?? null },
author
);
return this.artifact(client, row, revision);
});
}
async getArtifact(id: string): Promise<ResearchArtifact> {
return this.artifact(
this.database,
await this.artifactRow(this.database, researchIdSchema.parse(id))
);
researchIdSchema.parse(id);
return this.database.transaction(async client => {
await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
return this.artifact(client, await this.artifactRow(client, id));
});
}
async listArtifactRevisions(id: string): Promise<ResearchArtifactRevision[]> {
researchIdSchema.parse(id);
await this.artifactRow(this.database, id);
const rows = (
await this.database.query(
'SELECT * FROM analysis_artifact_revisions WHERE artifact_id=$1 ORDER BY ordinal',
[id]
)
).rows;
return Promise.all(rows.map(row => this.artifactRevision(this.database, row)));
return this.database.transaction(async client => {
await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
await this.artifactRow(client, id);
const rows = (
await client.query(
'SELECT * FROM analysis_artifact_revisions WHERE artifact_id=$1 ORDER BY ordinal',
[id]
)
).rows;
return Promise.all(rows.map(row => this.artifactRevision(client, row)));
});
}
async reviseArtifact(
id: string,
@ -398,14 +446,21 @@ export class ResearchService {
const current = required(
(
await client.query(
'SELECT ordinal FROM analysis_artifact_revisions WHERE artifact_id=$1 ORDER BY ordinal DESC LIMIT 1',
'SELECT ordinal,source FROM analysis_artifact_revisions WHERE artifact_id=$1 ORDER BY ordinal DESC LIMIT 1',
[id]
)
).rows[0],
'Artifact revision'
);
expectRevision(current.ordinal, data.expectedRevision);
await this.insertArtifactRevision(client, id, data.expectedRevision + 1, data, author);
const source = data.source === undefined ? findingSource(current.source) : data.source;
const revision = await this.insertArtifactRevision(
client,
id,
data.expectedRevision + 1,
{ ...data, source },
author
);
const updated = required(
(
await client.query(
@ -415,7 +470,7 @@ export class ResearchService {
).rows[0],
'Artifact'
);
return this.artifact(client, updated);
return this.artifact(client, updated, revision);
});
}
async archiveArtifact(
@ -531,16 +586,25 @@ export class ResearchService {
]
);
}
private async artifact(database: Database, row: QueryResultRow): Promise<ResearchArtifact> {
const latest = required(
(
await database.query(
'SELECT * FROM analysis_artifact_revisions WHERE artifact_id=$1 ORDER BY ordinal DESC LIMIT 1',
[row.id]
private async artifact(
database: Database,
row: QueryResultRow,
resolved?: ResearchArtifactRevision
): Promise<ResearchArtifact> {
const latest =
resolved ??
(await this.artifactRevision(
database,
required(
(
await database.query(
'SELECT * FROM analysis_artifact_revisions WHERE artifact_id=$1 ORDER BY ordinal DESC LIMIT 1',
[row.id]
)
).rows[0],
'Artifact revision'
)
).rows[0],
'Artifact revision'
);
));
return {
id: row.id,
projectId: row.project_id,
@ -551,45 +615,35 @@ export class ResearchService {
updatedAt: iso(row.updated_at),
archived: row.archived_at !== null,
createdAt: iso(row.created_at),
latestRevision: await this.artifactRevision(database, latest),
latestRevision: latest,
};
}
private async artifactRevision(
database: Database,
row: QueryResultRow
): Promise<ResearchArtifactRevision> {
const references = (
const references: ResearchEvidenceReference[] = (
await database.query(
'SELECT * FROM analysis_evidence WHERE revision_id=$1 ORDER BY ordinal',
[row.id]
)
).rows;
const evidence = await Promise.all(
references.map(item =>
this.evidence.resolve(
{
runId: item.run_id,
metricsVersion: item.metrics_version,
metricPath: item.metric_path,
strategyVersionId: item.strategy_version_id,
},
database
)
)
);
return {
id: row.id,
artifactId: row.artifact_id,
ordinal: row.ordinal,
title: row.title,
body: row.body,
submittedBy: row.submitted_by,
contentOrigin: row.content_origin,
validationState: 'unvalidated',
evidenceState: evidence.length ? 'referenced' : 'none',
evidence,
createdAt: iso(row.created_at),
};
).rows.map(item => ({
runId: item.run_id,
metricsVersion: item.metrics_version,
metricPath: item.metric_path,
strategyVersionId: item.strategy_version_id,
}));
const source = findingSource(row.source);
let evidence;
try {
evidence = await this.evidence.resolveAll(references, source, database);
} catch (cause) {
if (!source) {
throw cause;
}
throw new Error('Retained finding source evidence could not be resolved', { cause });
}
return artifactRevisionValue(row, evidence, source);
}
private requireFindingEvidence(kind: string, evidence: ResearchEvidenceReference[]): void {
if (kind === 'finding' && evidence.length === 0) {
@ -600,18 +654,39 @@ export class ResearchService {
client: PoolClient,
id: string,
ordinal: number,
data: { title: string; body: string; evidence: ResearchEvidenceReference[] },
data: {
title: string;
body: string;
evidence: ResearchEvidenceReference[];
source: ResearchFindingSource | null;
},
author: ResearchAuthorship
): Promise<void> {
// Validate using the authoritative reader; only references are persisted.
for (const reference of data.evidence) {
await this.evidence.resolve(reference, client);
}
): Promise<ResearchArtifactRevision> {
// Validate once per revision; only references are persisted.
const references = data.evidence.map(reference => ({
...reference,
strategyVersionId: reference.strategyVersionId ?? null,
}));
const evidence = await this.evidence.resolveAll(references, data.source, client);
const revisionId = randomUUID();
await client.query(
`INSERT INTO analysis_artifact_revisions(id,artifact_id,ordinal,title,body,submitted_by,content_origin)
VALUES($1,$2,$3,$4,$5,$6,$7)`,
[revisionId, id, ordinal, data.title, data.body, author.submittedBy, author.contentOrigin]
const row = required(
(
await client.query(
`INSERT INTO analysis_artifact_revisions(id,artifact_id,ordinal,title,body,submitted_by,content_origin,source)
VALUES($1,$2,$3,$4,$5,$6,$7,$8) RETURNING *`,
[
revisionId,
id,
ordinal,
data.title,
data.body,
author.submittedBy,
author.contentOrigin,
data.source,
]
)
).rows[0],
'Artifact revision'
);
for (const [index, reference] of data.evidence.entries()) {
await client.query(
@ -627,5 +702,6 @@ export class ResearchService {
]
);
}
return artifactRevisionValue(row, evidence, data.source);
}
}