feat(research): compare saved experiments against explicit trials
This commit is contained in:
parent
397cd0e160
commit
46a4f13acd
22 changed files with 3045 additions and 35 deletions
124
apps/stock/web-api/src/services/experiment-comparison.ts
Normal file
124
apps/stock/web-api/src/services/experiment-comparison.ts
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
import { at } from '@stock-bot/invariants';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalRunRequest,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import type { WorkbenchExperimentDetail } from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import {
|
||||
experimentComparisonDimensions,
|
||||
experimentComparisonInputSchema,
|
||||
type ExperimentComparison,
|
||||
type ExperimentComparisonDimension,
|
||||
type ExperimentComparisonInput,
|
||||
} from '@stock-bot/stock-config/experiment-comparison';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import type { HistoricalDatasetManifestV2 } from '@stock-bot/types';
|
||||
import { workbenchTrialRequest } from './cost-sensitivity-input';
|
||||
import { ExperimentError, PREVIEW_RUN_ID } from './experiment-input';
|
||||
|
||||
export function parseExperimentComparison(raw: unknown): ExperimentComparisonInput {
|
||||
const parsed = experimentComparisonInputSchema.safeParse(raw);
|
||||
if (!parsed.success) {
|
||||
throw new ExperimentError(
|
||||
400,
|
||||
'Comparison requires two distinct experiment IDs and an optional reference trial key'
|
||||
);
|
||||
}
|
||||
return parsed.data;
|
||||
}
|
||||
/** Partition the complete parsed replay policy. Only validated admission/owner identities normalize. */
|
||||
export function comparisonConditions(
|
||||
input: CanonicalRunRequest,
|
||||
manifest: HistoricalDatasetManifestV2
|
||||
): Record<ExperimentComparisonDimension, unknown> {
|
||||
const request = canonicalRunRequestSchema.parse(input),
|
||||
policy = structuredClone(request.policy);
|
||||
policy.matching.risk.ledger.sessionId = 'comparison-run';
|
||||
policy.matching.risk.ledger.accountId = 'comparison-account';
|
||||
policy.matching.risk.ledger.ownerIds[0] = 'comparison-owner';
|
||||
at(policy.matching.owners, 0).ownerId = 'comparison-owner';
|
||||
at(policy.cadence, 0).owner_id = 'comparison-owner';
|
||||
const { matching, risk_boundaries, ...policyRemainder } = policy;
|
||||
const { risk, halfSpreadRate, slippageRate, ...matchingRemainder } = matching;
|
||||
const { ledger, feeRate, ...riskRemainder } = risk;
|
||||
const { initialCapital, riskSession, ...ledgerRemainder } = ledger;
|
||||
return {
|
||||
dataset: { manifest, datasetHash: request.datasetHash },
|
||||
window: manifest.bounds,
|
||||
capital: { initialCapital, ownerBudget: request.strategy.selection.ownerBudget },
|
||||
costs: { feeRate, halfSpreadRate, slippageRate },
|
||||
execution: {
|
||||
...policyRemainder,
|
||||
matching: matchingRemainder,
|
||||
instrumentId: request.strategy.selection.instrumentId,
|
||||
seriesId: request.strategy.selection.seriesId,
|
||||
},
|
||||
risk: { ...riskRemainder, ledger: ledgerRemainder },
|
||||
clock: { riskSession, risk_boundaries },
|
||||
analytics: request.analyticsPolicy,
|
||||
seed: request.strategy.selection.seed,
|
||||
build: request.build,
|
||||
models: request.modelArtifacts,
|
||||
};
|
||||
}
|
||||
export function compareExperiments(
|
||||
raw: ExperimentComparisonInput,
|
||||
experiments: [WorkbenchExperimentDetail, WorkbenchExperimentDetail]
|
||||
): ExperimentComparison {
|
||||
const input = parseExperimentComparison(raw),
|
||||
[left, right] = experiments;
|
||||
if (left.id !== input.leftId || right.id !== input.rightId) {
|
||||
throw new Error('Comparison experiment identities do not match the requested pair');
|
||||
}
|
||||
const reference =
|
||||
input.referenceTrialKey === undefined
|
||||
? at(left.trials, 0)
|
||||
: left.trials.find(trial => trial.trialKey === input.referenceTrialKey);
|
||||
if (!reference) {
|
||||
throw new ExperimentError(409, 'Reference trial does not belong to the left experiment');
|
||||
}
|
||||
const conditions = comparisonConditions(
|
||||
workbenchTrialRequest(left.preview, reference, reference.runId ?? PREVIEW_RUN_ID),
|
||||
left.preview.dataset
|
||||
);
|
||||
const rows = experiments.flatMap(experiment =>
|
||||
experiment.trials.map(trial => {
|
||||
const current = comparisonConditions(
|
||||
workbenchTrialRequest(experiment.preview, trial, trial.runId ?? PREVIEW_RUN_ID),
|
||||
experiment.preview.dataset
|
||||
);
|
||||
const differences = experimentComparisonDimensions.filter(
|
||||
dimension =>
|
||||
canonicalStrategyJson(current[dimension]) !== canonicalStrategyJson(conditions[dimension])
|
||||
);
|
||||
return {
|
||||
experimentId: experiment.id,
|
||||
trialKey: trial.trialKey,
|
||||
inputCompatibility: differences.length ? ('mismatch' as const) : ('match' as const),
|
||||
differences,
|
||||
summaryAvailable: trial.comparable,
|
||||
ready: differences.length === 0 && trial.comparable && reference.comparable,
|
||||
};
|
||||
})
|
||||
);
|
||||
return {
|
||||
version: 'experiment-comparison/v1',
|
||||
policy: 'retained-input-compatibility/v1',
|
||||
selection: { ...input, referenceTrialKey: reference.trialKey },
|
||||
reference: {
|
||||
experimentId: left.id,
|
||||
trialKey: reference.trialKey,
|
||||
index: reference.index,
|
||||
runId: reference.runId,
|
||||
summaryAvailable: reference.comparable,
|
||||
diagnostic: reference.diagnostic,
|
||||
},
|
||||
experiments,
|
||||
rows,
|
||||
limitations: [
|
||||
'Matching settings and saved scalar summaries do not establish economic equivalence, full financial reconciliation, independence, statistical significance or out-of-sample validity.',
|
||||
'Summary availability uses existing compact provenance and shape checks. Open the exact run for deeper retained-result validation.',
|
||||
'Strategy implementations and parameters may differ. Rows preserve original candidate order; no ranking or preferred candidate is implied.',
|
||||
],
|
||||
};
|
||||
}
|
||||
|
|
@ -27,6 +27,7 @@ import {
|
|||
retainedWorkbenchPreview,
|
||||
workbenchTrialRequest,
|
||||
} from './cost-sensitivity-input';
|
||||
import { compareExperiments, parseExperimentComparison } from './experiment-comparison';
|
||||
import {
|
||||
buildExperimentPreview,
|
||||
ExperimentError,
|
||||
|
|
@ -319,6 +320,30 @@ export class ExperimentsService {
|
|||
);
|
||||
return rows.rows.map(summary);
|
||||
}
|
||||
async compare(raw: unknown) {
|
||||
const input = parseExperimentComparison(raw);
|
||||
return this.database.transaction(async client => {
|
||||
await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
const rows = (
|
||||
await client.query(
|
||||
'SELECT id,validation_phase FROM research_experiments WHERE id=ANY($1::uuid[])',
|
||||
[[input.leftId, input.rightId]]
|
||||
)
|
||||
).rows;
|
||||
if (rows.length !== 2) {
|
||||
throw new ExperimentError(404, 'Comparison experiment not found');
|
||||
}
|
||||
if (rows.some(row => row.validation_phase !== null)) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Compare standalone experiments; chronological phases have their own workflow'
|
||||
);
|
||||
}
|
||||
const left = await this.readDetail(client, input.leftId),
|
||||
right = await this.readDetail(client, input.rightId);
|
||||
return compareExperiments(input, [left, right]);
|
||||
});
|
||||
}
|
||||
async get(id: string): Promise<WorkbenchExperimentDetail> {
|
||||
experimentId(id);
|
||||
return this.readDetail(this.database, id);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue