feat(research): isolate candidates and add reviewed paper promotion
This commit is contained in:
parent
26b97265c6
commit
25b5cbf481
128 changed files with 13038 additions and 1388 deletions
|
|
@ -52,6 +52,18 @@
|
|||
"./research-agents": {
|
||||
"types": "./dist/contracts/research-agents.d.ts",
|
||||
"default": "./dist/contracts/research-agents.js"
|
||||
},
|
||||
"./research-responses": {
|
||||
"types": "./dist/contracts/research-responses/index.d.ts",
|
||||
"default": "./dist/contracts/research-responses/index.js"
|
||||
},
|
||||
"./candidate-execution": {
|
||||
"types": "./dist/contracts/candidate-execution.d.ts",
|
||||
"default": "./dist/contracts/candidate-execution.js"
|
||||
},
|
||||
"./paper-deployments": {
|
||||
"types": "./dist/contracts/paper-deployments.d.ts",
|
||||
"import": "./dist/contracts/paper-deployments.js"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
|
|
|||
94
apps/stock/config/src/contracts/candidate-execution.ts
Normal file
94
apps/stock/config/src/contracts/candidate-execution.ts
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
/** Pure isolated-candidate contracts. No runtime, artifact import or financial implementation. */
|
||||
import { z } from 'zod';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import type { financialDecimal } from '@stock-bot/types';
|
||||
|
||||
export type { financialDecimal };
|
||||
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/);
|
||||
const identity = z
|
||||
.string()
|
||||
.min(1)
|
||||
.refine(value =>
|
||||
[...value].every(character => {
|
||||
const code = character.charCodeAt(0);
|
||||
return (
|
||||
code >= 32 && code !== 127 && !(character.length === 1 && code >= 0xd800 && code <= 0xdfff)
|
||||
);
|
||||
})
|
||||
);
|
||||
export const candidatePackageExecutionSchema = z
|
||||
.object({
|
||||
kind: z.literal('isolated-candidate/v1'),
|
||||
/** Fixed author declaration for all parameter combinations, not a verified leakage claim. */
|
||||
warmupBars: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
||||
})
|
||||
.strict();
|
||||
export const retainedProgramSelectionSchema = z
|
||||
.object({
|
||||
ownerId: identity,
|
||||
strategyId: identity,
|
||||
strategyVersion: identity,
|
||||
seed: z.number().int().min(0).max(0xffffffff),
|
||||
instrumentId: identity,
|
||||
seriesId: identity,
|
||||
/** Strategy sizing input. Rust portfolio constraints remain the financial authority. */
|
||||
ownerBudget: z
|
||||
.string()
|
||||
.transform(parseFinancialDecimal)
|
||||
.refine(value => !value.startsWith('-') && value !== '0.00000000'),
|
||||
parameters: z.record(z.union([z.string(), z.number().finite(), z.boolean()])),
|
||||
})
|
||||
.strict();
|
||||
export type RetainedProgramSelection = z.infer<typeof retainedProgramSelectionSchema>;
|
||||
|
||||
export const candidateSandboxLimits = {
|
||||
memoryBytes: 536870912,
|
||||
cpuQuota: 1,
|
||||
pids: 64,
|
||||
tmpBytes: 16777216,
|
||||
wallMs: 300000,
|
||||
frameBytes: 8388608,
|
||||
stderrBytes: 65536,
|
||||
} as const;
|
||||
export const candidateSandboxProfileSchema = z
|
||||
.object({
|
||||
version: z.literal(1),
|
||||
policy: z.literal('linux-docker-guardian/v1'),
|
||||
protocol: z.literal('candidate-controller/v1'),
|
||||
platform: z.literal('linux'),
|
||||
arch: z.literal('x64'),
|
||||
hostSha256: hash,
|
||||
guardianSha256: hash,
|
||||
bunSha256: hash,
|
||||
limits: z
|
||||
.object({
|
||||
memoryBytes: z.literal(candidateSandboxLimits.memoryBytes),
|
||||
cpuQuota: z.literal(candidateSandboxLimits.cpuQuota),
|
||||
pids: z.literal(candidateSandboxLimits.pids),
|
||||
tmpBytes: z.literal(candidateSandboxLimits.tmpBytes),
|
||||
wallMs: z.literal(candidateSandboxLimits.wallMs),
|
||||
frameBytes: z.literal(candidateSandboxLimits.frameBytes),
|
||||
stderrBytes: z.literal(candidateSandboxLimits.stderrBytes),
|
||||
})
|
||||
.strict(),
|
||||
})
|
||||
.strict();
|
||||
export const candidateExecutionSchema = z
|
||||
.object({
|
||||
kind: z.literal('typescript-isolated-candidate/v1'),
|
||||
imageId: z.string().regex(/^sha256:[a-f0-9]{64}$/),
|
||||
profile: candidateSandboxProfileSchema,
|
||||
})
|
||||
.strict();
|
||||
export type CandidateExecution = z.infer<typeof candidateExecutionSchema>;
|
||||
|
||||
export const candidateOverrideSchema = z
|
||||
.object({
|
||||
versionId: z
|
||||
.string()
|
||||
.uuid()
|
||||
.transform(value => value.toLowerCase()),
|
||||
parameters: retainedProgramSelectionSchema.shape.parameters,
|
||||
})
|
||||
.strict();
|
||||
|
|
@ -10,6 +10,11 @@ import type {
|
|||
} from '@stock-bot/types';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import { builtinStrategySelectionSchema } from './builtin-strategy';
|
||||
import {
|
||||
candidateExecutionSchema,
|
||||
retainedProgramSelectionSchema,
|
||||
type CandidateExecution,
|
||||
} from './candidate-execution';
|
||||
import {
|
||||
parseReplayReportValue,
|
||||
replayConfigSchema,
|
||||
|
|
@ -93,16 +98,30 @@ const admitted = z
|
|||
runId: z.string().uuid(),
|
||||
backtestId: z.string().uuid(),
|
||||
name: z.string().min(1),
|
||||
strategy: z
|
||||
.object({
|
||||
familyId: z.string().uuid(),
|
||||
versionId: z.string().uuid(),
|
||||
origin: z.literal('builtin'),
|
||||
reviewId: z.string().uuid(),
|
||||
package: z.unknown().transform(parseStrategyVersionPackage),
|
||||
selection: builtinStrategySelectionSchema,
|
||||
})
|
||||
.strict(),
|
||||
strategy: z.discriminatedUnion('origin', [
|
||||
z
|
||||
.object({
|
||||
familyId: z.string().uuid(),
|
||||
versionId: z.string().uuid(),
|
||||
origin: z.literal('builtin'),
|
||||
reviewId: z.string().uuid(),
|
||||
package: z.unknown().transform(parseStrategyVersionPackage),
|
||||
selection: builtinStrategySelectionSchema,
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
familyId: z.string().uuid(),
|
||||
versionId: z.string().uuid(),
|
||||
origin: z.literal('candidate'),
|
||||
baselineVersionId: z.string().uuid(),
|
||||
reviewId: z.string().uuid().nullable(),
|
||||
package: z.unknown().transform(parseStrategyVersionPackage),
|
||||
selection: retainedProgramSelectionSchema,
|
||||
execution: candidateExecutionSchema,
|
||||
})
|
||||
.strict(),
|
||||
]),
|
||||
datasetHash: hash,
|
||||
policy: replayConfigSchema,
|
||||
analyticsPolicy: metricsPolicy,
|
||||
|
|
@ -117,6 +136,9 @@ export const canonicalRunRequestSchema = admitted.superRefine((value, context) =
|
|||
const ledger = policy.matching.risk.ledger;
|
||||
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
|
||||
const valid =
|
||||
(strategy.origin === 'candidate'
|
||||
? strategy.package.execution?.kind === 'isolated-candidate/v1'
|
||||
: strategy.package.execution === undefined) &&
|
||||
strategy.package.program.strategyId === selection.strategyId &&
|
||||
strategy.package.program.strategyVersion === selection.strategyVersion &&
|
||||
ledger.sessionId === value.runId &&
|
||||
|
|
@ -146,6 +168,12 @@ export const canonicalRunRequestSchema = admitted.superRefine((value, context) =
|
|||
}
|
||||
});
|
||||
export type CanonicalRunRequest = z.infer<typeof canonicalRunRequestSchema>;
|
||||
/** Derive execution from the strict origin branch, never from an independent client flag. */
|
||||
export function canonicalStrategyExecution(request: CanonicalRunRequest) {
|
||||
return request.strategy.origin === 'candidate'
|
||||
? ('typescript-isolated-candidate/v1' as const)
|
||||
: ('typescript-retained-builtin/v1' as const);
|
||||
}
|
||||
|
||||
export interface CanonicalRunResult {
|
||||
kind: 'canonical-result/v1';
|
||||
|
|
@ -155,7 +183,7 @@ export interface CanonicalRunResult {
|
|||
completedAt: string;
|
||||
executionTime: number;
|
||||
financialEngine: 'rust';
|
||||
strategyExecution: 'typescript-retained-builtin/v1';
|
||||
strategyExecution: 'typescript-retained-builtin/v1' | 'typescript-isolated-candidate/v1';
|
||||
request: CanonicalRunRequest;
|
||||
financial: ReplayReportResult;
|
||||
analytics: CanonicalBacktestAnalytics;
|
||||
|
|
@ -165,6 +193,7 @@ export function isCanonicalRunResult(value: ResearchRunResult): value is Canonic
|
|||
return 'kind' in value && value.kind === 'canonical-result/v1';
|
||||
}
|
||||
export interface CanonicalRunCapability {
|
||||
execution?: CandidateExecution;
|
||||
available: boolean;
|
||||
reason: string | null;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -72,6 +72,12 @@ export const chronologicalValidationPolicy = {
|
|||
model: 'deterministic-unfitted',
|
||||
readiness: 'input-checks-only',
|
||||
} as const;
|
||||
/** Arbitrary candidate code does not prove deterministic/unfitted behavior. */
|
||||
export function chronologicalPolicyForOrigin(origin: 'builtin' | 'candidate') {
|
||||
return origin === 'candidate'
|
||||
? { ...chronologicalValidationPolicy, model: 'unverified-candidate' as const }
|
||||
: chronologicalValidationPolicy;
|
||||
}
|
||||
export interface ChronologicalValidationPreview {
|
||||
version: 'chronological-validation-preview/v1';
|
||||
execution: 'preview-only';
|
||||
|
|
@ -79,7 +85,7 @@ export interface ChronologicalValidationPreview {
|
|||
input: ChronologicalValidationInput;
|
||||
/** Source lineage lives here; dataset parentDatasetHash retains its legacy-v1 meaning. */
|
||||
source: ExperimentPreview;
|
||||
policy: typeof chronologicalValidationPolicy;
|
||||
policy: ReturnType<typeof chronologicalPolicyForOrigin>;
|
||||
partitions: [ValidationPartitionPreview, ValidationPartitionPreview, ValidationPartitionPreview];
|
||||
}
|
||||
|
||||
|
|
@ -129,7 +135,7 @@ export interface ChronologicalValidationSelection {
|
|||
createdAt: string;
|
||||
principal: ResearchActor;
|
||||
/** Current original-version approval for the new holdout admissions. */
|
||||
reviewId: string;
|
||||
reviewId: string | null;
|
||||
winner: ExperimentCandidate;
|
||||
/** All training candidates in ascending original candidate index. */
|
||||
training: ValidationResultEvidence[];
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
/** Cost diagnostics reuse ordinary experiments and the authoritative Rust matcher. */
|
||||
import { z } from 'zod';
|
||||
import type { financialDecimal } from '@stock-bot/types';
|
||||
import { candidateOverrideSchema } from './candidate-execution';
|
||||
import { canonicalResearchSettingsSchema, type CanonicalRunRequest } from './canonical-research';
|
||||
import {
|
||||
MAX_EXPERIMENT_TRIALS,
|
||||
|
|
@ -21,6 +22,7 @@ export const costSensitivityInputSchema = z
|
|||
.object({
|
||||
backtestId: z.string().uuid(),
|
||||
name: z.string().trim().min(1),
|
||||
candidate: candidateOverrideSchema.optional(),
|
||||
/** Baseline is automatic and consumes one of the existing 100 trial slots. */
|
||||
scenarios: z
|
||||
.array(costScenarioSchema)
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import type {
|
|||
ResearchActor,
|
||||
StrategyParameterValue,
|
||||
} from '@stock-bot/types';
|
||||
import { candidateOverrideSchema } from './candidate-execution';
|
||||
import type { CanonicalRunRequest } from './canonical-research';
|
||||
|
||||
/** Admission bound for atomic expansion, not a promise of concurrent execution. */
|
||||
|
|
@ -36,6 +37,7 @@ export const experimentInputSchema = z
|
|||
backtestId: z.string().uuid(),
|
||||
name: z.string().trim().min(1),
|
||||
grid,
|
||||
candidate: candidateOverrideSchema.optional(),
|
||||
})
|
||||
.strict();
|
||||
export const experimentSubmissionSchema = experimentInputSchema.extend({
|
||||
|
|
@ -70,7 +72,7 @@ export interface ExperimentTrialRetry {
|
|||
recordedAt: string;
|
||||
principal: ResearchActor;
|
||||
/** Current approval at retry admission; the original run snapshot stays immutable. */
|
||||
reviewId: string;
|
||||
reviewId: string | null;
|
||||
}
|
||||
export interface ExperimentRetryResult {
|
||||
retry: ExperimentTrialRetry;
|
||||
|
|
|
|||
215
apps/stock/config/src/contracts/paper-deployments.ts
Normal file
215
apps/stock/config/src/contracts/paper-deployments.ts
Normal file
|
|
@ -0,0 +1,215 @@
|
|||
/** Explicit human promotion into a trusted paper host. No live capability or code import. */
|
||||
import { z } from 'zod';
|
||||
import type { financialDecimal } from '@stock-bot/types';
|
||||
import { retainedProgramSelectionSchema } from './candidate-execution';
|
||||
import { replayConfigSchema } from './canonical-replay';
|
||||
import { researchFindingSourceSchema } from './research';
|
||||
|
||||
export type { financialDecimal };
|
||||
|
||||
const id = z
|
||||
.string()
|
||||
.min(1)
|
||||
.refine(value => [...value].every(c => c.charCodeAt(0) >= 32 && c.charCodeAt(0) !== 127));
|
||||
const uuid = z
|
||||
.string()
|
||||
.uuid()
|
||||
.transform(value => value.toLowerCase());
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/);
|
||||
const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const time = z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER);
|
||||
const riskSession = replayConfigSchema.shape.matching.shape.risk.shape.ledger.shape.riskSession;
|
||||
export const paperPolicySchema = z
|
||||
.object({
|
||||
version: z.literal(1),
|
||||
sourceId: id,
|
||||
priceBasis: z.literal('raw'),
|
||||
maxFeedAgeMs: counter.refine(v => v > 0),
|
||||
observations: z.array(
|
||||
z
|
||||
.object({
|
||||
seriesId: id,
|
||||
instrumentId: id,
|
||||
intervalMs: counter.refine(v => v > 0),
|
||||
staleAfterMs: counter,
|
||||
})
|
||||
.strict()
|
||||
),
|
||||
cadence: z.array(z.object({ ownerId: id, seriesIds: z.array(id).min(1) }).strict()),
|
||||
calendars: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
instrumentId: id,
|
||||
calendarId: id,
|
||||
revision: id,
|
||||
sessions: z
|
||||
.array(z.object({ sessionId: id, opensAt: time, closesAt: time }).strict())
|
||||
.min(1),
|
||||
})
|
||||
.strict()
|
||||
)
|
||||
.min(1),
|
||||
riskBoundaries: z.array(riskSession),
|
||||
})
|
||||
.strict()
|
||||
.transform(value => ({
|
||||
...value,
|
||||
calendars: value.calendars.map(calendar => ({
|
||||
...calendar,
|
||||
sessions: [...calendar.sessions].sort((a, b) => a.opensAt - b.opensAt),
|
||||
})),
|
||||
riskBoundaries: [...value.riskBoundaries].sort((a, b) => a.startsAt - b.startsAt),
|
||||
}));
|
||||
export const deployedPaperConfigurationSchema = z
|
||||
.object({
|
||||
version: z.literal(2),
|
||||
matching: replayConfigSchema.shape.matching.extend({
|
||||
series: z
|
||||
.array(
|
||||
replayConfigSchema.shape.matching.shape.series.element.extend({
|
||||
mode: z.literal('Quote'),
|
||||
})
|
||||
)
|
||||
.length(1),
|
||||
}),
|
||||
strategies: z.tuple([retainedProgramSelectionSchema]),
|
||||
policy: paperPolicySchema,
|
||||
})
|
||||
.strict();
|
||||
export const paperHostIdentitySchema = z
|
||||
.object({
|
||||
version: z.literal('paper-host/v1'),
|
||||
hostSha256: hash,
|
||||
engineWrapperSha256: hash,
|
||||
engineBinarySha256: hash,
|
||||
dependencyLockSha256: hash,
|
||||
runtime: z.literal('bun'),
|
||||
runtimeVersion: id,
|
||||
platform: id,
|
||||
arch: id,
|
||||
})
|
||||
.strict();
|
||||
/** Only transport and future clocks are operator inputs. Economics come from the selected cost trial. */
|
||||
export const paperTransportSchema = z
|
||||
.object({
|
||||
accountId: id,
|
||||
sessionId: id,
|
||||
quoteSeriesId: id,
|
||||
riskSession,
|
||||
policy: paperPolicySchema,
|
||||
})
|
||||
.strict();
|
||||
export const paperPromotionInputSchema = z
|
||||
.object({
|
||||
name: z.string().trim().min(1),
|
||||
outOfSample: researchFindingSourceSchema.refine(
|
||||
value => value.kind !== 'experiment/v1',
|
||||
'Select a sealed chronological or walk-forward report'
|
||||
),
|
||||
testRunId: uuid,
|
||||
costExperimentId: uuid,
|
||||
costPreviewHash: hash,
|
||||
costRunId: uuid,
|
||||
transport: paperTransportSchema,
|
||||
reason: z.string().trim().min(1),
|
||||
acknowledgeTrustedCode: z.literal(true),
|
||||
})
|
||||
.strict();
|
||||
export const paperPromotionSubmissionSchema = paperPromotionInputSchema.extend({
|
||||
previewHash: hash,
|
||||
});
|
||||
export const paperMetricEvidenceSchema = z
|
||||
.object({
|
||||
runId: uuid,
|
||||
datasetHash: hash,
|
||||
economicHash: hash,
|
||||
resultHash: hash,
|
||||
metrics: z.record(z.number().finite().nullable()),
|
||||
fillCount: counter,
|
||||
limitations: z.array(z.string()),
|
||||
})
|
||||
.strict();
|
||||
export const paperPromotionPreviewSchema = z
|
||||
.object({
|
||||
version: z.literal('paper-promotion-preview/v1'),
|
||||
previewHash: hash,
|
||||
input: paperPromotionInputSchema,
|
||||
strategy: z
|
||||
.object({
|
||||
familyId: uuid,
|
||||
versionId: uuid,
|
||||
reviewId: uuid,
|
||||
origin: z.enum(['builtin', 'candidate']),
|
||||
artifactSha256: hash,
|
||||
dependencyLockSha256: hash,
|
||||
})
|
||||
.strict(),
|
||||
configuration: deployedPaperConfigurationSchema,
|
||||
host: paperHostIdentitySchema,
|
||||
evidence: z
|
||||
.object({ test: paperMetricEvidenceSchema, costs: z.array(paperMetricEvidenceSchema).min(2) })
|
||||
.strict(),
|
||||
limitations: z.array(z.string()),
|
||||
})
|
||||
.strict();
|
||||
export const paperDeploymentSchema = z
|
||||
.object({
|
||||
id: uuid,
|
||||
version: z.literal('paper-deployment/v1'),
|
||||
principal: z.literal('operator'),
|
||||
createdAt: z.string().datetime(),
|
||||
promotionHash: hash,
|
||||
preview: paperPromotionPreviewSchema,
|
||||
})
|
||||
.strict();
|
||||
export const paperDeploymentBindingSchema = z
|
||||
.object({
|
||||
deploymentId: uuid,
|
||||
promotionHash: hash,
|
||||
strategyVersionId: uuid,
|
||||
artifactSha256: hash,
|
||||
dependencyLockSha256: hash,
|
||||
host: paperHostIdentitySchema,
|
||||
})
|
||||
.strict();
|
||||
export const paperReadinessSchema = z
|
||||
.object({
|
||||
configured: z.boolean(),
|
||||
accountId: z.string().nullable(),
|
||||
sourceId: z.string().nullable(),
|
||||
active: z.boolean(),
|
||||
ready: z.boolean(),
|
||||
operatorHalted: z.boolean(),
|
||||
connected: z.boolean(),
|
||||
reasons: z.array(z.string()),
|
||||
lastReceivedAt: time.nullable(),
|
||||
lastAvailableAt: time.nullable(),
|
||||
requiresHistoricalRecovery: z.boolean(),
|
||||
pendingInput: z.string().nullable(),
|
||||
pendingBatch: z.string().nullable(),
|
||||
pendingDecisionSequence: counter.nullable(),
|
||||
nativeStatus: z
|
||||
.union([
|
||||
z.literal('Running'),
|
||||
z.literal('Complete'),
|
||||
z.object({ Failed: z.object({ diagnostic: z.string() }).strict() }).strict(),
|
||||
])
|
||||
.nullable(),
|
||||
risk: z.object({ dailyHalted: z.boolean(), drawdownHalted: z.boolean() }).strict().nullable(),
|
||||
})
|
||||
.strict();
|
||||
export const paperDeploymentStatusSchema = z
|
||||
.object({
|
||||
deploymentId: uuid,
|
||||
boundDeploymentId: uuid.nullable(),
|
||||
readiness: paperReadinessSchema,
|
||||
})
|
||||
.strict();
|
||||
export type PaperPromotionInput = z.input<typeof paperPromotionInputSchema>;
|
||||
export type PaperPromotionPreview = z.infer<typeof paperPromotionPreviewSchema>;
|
||||
export type PaperDeployment = z.infer<typeof paperDeploymentSchema>;
|
||||
export type PaperDeploymentBinding = z.infer<typeof paperDeploymentBindingSchema>;
|
||||
export type PaperHostIdentity = z.infer<typeof paperHostIdentitySchema>;
|
||||
export type PaperDeploymentStatus = z.infer<typeof paperDeploymentStatusSchema>;
|
||||
export type DeployedPaperConfiguration = z.infer<typeof deployedPaperConfigurationSchema>;
|
||||
|
|
@ -27,6 +27,8 @@ export const createResearchAgentSchema = z
|
|||
name: z.string().trim().min(1),
|
||||
allowedProjectIds: ids,
|
||||
allowedBacktestIds: ids,
|
||||
/** Explicit operator opt-in, a subset of allowed backtests. Omitted means none. */
|
||||
allowOwnCandidateBacktestIds: ids.optional(),
|
||||
limits: researchAgentLimitsSchema,
|
||||
})
|
||||
.strict();
|
||||
|
|
@ -50,7 +52,11 @@ export const researchAgentRecordSchema = z
|
|||
allowedProjectIds: ids,
|
||||
grants: z.array(
|
||||
z
|
||||
.object({ backtestId: z.string().uuid(), policyHash: z.string().regex(/^[a-f0-9]{64}$/) })
|
||||
.object({
|
||||
backtestId: z.string().uuid(),
|
||||
policyHash: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
allowOwnCandidates: z.boolean().optional(),
|
||||
})
|
||||
.strict()
|
||||
),
|
||||
limits: researchAgentLimitsSchema,
|
||||
|
|
|
|||
115
apps/stock/config/src/contracts/research-responses/comparison.ts
Normal file
115
apps/stock/config/src/contracts/research-responses/comparison.ts
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
/** Shared response verification; no IO or financial calculations. */
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
experimentComparisonDimensions,
|
||||
experimentComparisonInputSchema,
|
||||
type ExperimentComparison,
|
||||
type ExperimentComparisonInput,
|
||||
} from '../experiment-comparison';
|
||||
import { parseWorkbenchExperimentDetail, type WorkbenchExperimentDetailView } from './experiment';
|
||||
|
||||
export type ExperimentComparisonView = Omit<ExperimentComparison, 'experiments'> & {
|
||||
experiments: [WorkbenchExperimentDetailView, WorkbenchExperimentDetailView];
|
||||
};
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/),
|
||||
uuid = z.string().uuid();
|
||||
const schema = z.object({
|
||||
version: z.literal('experiment-comparison/v1'),
|
||||
policy: z.literal('retained-input-compatibility/v1'),
|
||||
selection: z.object({ leftId: uuid, rightId: uuid, referenceTrialKey: hash }).strict(),
|
||||
reference: z.object({
|
||||
experimentId: uuid,
|
||||
trialKey: hash,
|
||||
index: z.number().int().nonnegative(),
|
||||
runId: uuid.nullable(),
|
||||
summaryAvailable: z.boolean(),
|
||||
diagnostic: z.string().nullable(),
|
||||
}),
|
||||
experiments: z.tuple([z.unknown(), z.unknown()]),
|
||||
rows: z
|
||||
.array(
|
||||
z.object({
|
||||
experimentId: uuid,
|
||||
trialKey: hash,
|
||||
inputCompatibility: z.enum(['match', 'mismatch']),
|
||||
differences: z.array(z.enum(experimentComparisonDimensions)),
|
||||
summaryAvailable: z.boolean(),
|
||||
ready: z.boolean(),
|
||||
})
|
||||
)
|
||||
.min(2)
|
||||
.max(200),
|
||||
limitations: z.array(z.string().min(1)).min(1),
|
||||
});
|
||||
const invalid = () =>
|
||||
new Error('The experiment comparison could not be verified. Refresh the same selection.');
|
||||
export function parseComparisonQuery(params: URLSearchParams): ExperimentComparisonInput {
|
||||
const allowed = ['leftId', 'rightId', 'referenceTrialKey'];
|
||||
for (const key of params.keys()) {
|
||||
if (!allowed.includes(key) || params.getAll(key).length !== 1) {
|
||||
throw new Error(
|
||||
'Comparison URL requires two different experiment IDs and at most one reference trial key. Unknown or repeated query fields are not supported.'
|
||||
);
|
||||
}
|
||||
}
|
||||
const result = experimentComparisonInputSchema.safeParse(Object.fromEntries(params));
|
||||
if (!result.success) {
|
||||
throw new Error(
|
||||
'Select two different saved experiments to compare. The URL must contain valid leftId and rightId values and, when supplied, a valid referenceTrialKey.'
|
||||
);
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
export function parseExperimentComparison(
|
||||
raw: unknown,
|
||||
input: ExperimentComparisonInput
|
||||
): ExperimentComparisonView {
|
||||
const value = schema.parse(raw),
|
||||
experiments = value.experiments.map(
|
||||
parseWorkbenchExperimentDetail
|
||||
) as ExperimentComparisonView['experiments'];
|
||||
const [left, right] = experiments;
|
||||
const expectedKey = input.referenceTrialKey ?? left.trials[0]?.trialKey;
|
||||
const reference = left.trials.find(trial => trial.trialKey === expectedKey);
|
||||
if (
|
||||
!reference ||
|
||||
left.id !== input.leftId ||
|
||||
right.id !== input.rightId ||
|
||||
value.selection.leftId !== input.leftId ||
|
||||
value.selection.rightId !== input.rightId ||
|
||||
value.selection.referenceTrialKey !== expectedKey ||
|
||||
value.reference.experimentId !== left.id ||
|
||||
value.reference.trialKey !== reference.trialKey ||
|
||||
value.reference.index !== reference.index ||
|
||||
value.reference.runId !== reference.runId ||
|
||||
value.reference.summaryAvailable !== reference.comparable ||
|
||||
value.reference.diagnostic !== reference.diagnostic
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const expectedRows = experiments.flatMap(experiment =>
|
||||
experiment.trials.map(trial => ({ experimentId: experiment.id, trial }))
|
||||
);
|
||||
if (value.rows.length !== expectedRows.length) {
|
||||
throw invalid();
|
||||
}
|
||||
value.rows.forEach((row, index) => {
|
||||
const expected = expectedRows[index],
|
||||
order = row.differences.map(key => experimentComparisonDimensions.indexOf(key));
|
||||
if (
|
||||
!expected ||
|
||||
row.experimentId !== expected.experimentId ||
|
||||
row.trialKey !== expected.trial.trialKey ||
|
||||
order.some((position, i) => i > 0 && position <= (order[i - 1] ?? -1)) ||
|
||||
(row.inputCompatibility === 'match') !== (row.differences.length === 0) ||
|
||||
row.summaryAvailable !== expected.trial.comparable ||
|
||||
row.ready !==
|
||||
(row.inputCompatibility === 'match' && row.summaryAvailable && reference.comparable)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
});
|
||||
return { ...value, experiments };
|
||||
}
|
||||
|
||||
export { invalid as invalidExperimentComparison };
|
||||
349
apps/stock/config/src/contracts/research-responses/experiment.ts
Normal file
349
apps/stock/config/src/contracts/research-responses/experiment.ts
Normal file
|
|
@ -0,0 +1,349 @@
|
|||
/** Shared response verification for browser and authorized research clients; no IO or accounting. */
|
||||
import { z } from 'zod';
|
||||
import { canonicalRunRequestSchema } from '../canonical-research';
|
||||
import {
|
||||
costScenarioSchema,
|
||||
costSensitivityInputSchema,
|
||||
type CostSensitivityDetail,
|
||||
type CostSensitivityPreview,
|
||||
} from '../cost-sensitivity';
|
||||
import {
|
||||
experimentInputSchema,
|
||||
MAX_EXPERIMENT_TRIALS,
|
||||
type ExperimentDetail,
|
||||
type ExperimentPreview,
|
||||
type ExperimentSummary,
|
||||
} from '../experiments';
|
||||
import { researchActorSchema } from '../research';
|
||||
import { canonicalStrategyJson, validateStrategyParameters } from '../strategy';
|
||||
|
||||
export class ExperimentApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number | null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
get ambiguous() {
|
||||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/);
|
||||
const count = z.number().int().nonnegative().max(MAX_EXPERIMENT_TRIALS);
|
||||
const counter = z.number().int().nonnegative().max(2147483647);
|
||||
const scalar = z.union([z.string(), z.number().finite(), z.boolean()]);
|
||||
const candidate = z
|
||||
.object({
|
||||
index: count,
|
||||
trialKey: hash,
|
||||
parameters: z.record(scalar),
|
||||
})
|
||||
.strict();
|
||||
const statuses = ['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'] as const;
|
||||
const counts = z.object({
|
||||
pending: count,
|
||||
running: count,
|
||||
paused: count,
|
||||
completed: count,
|
||||
failed: count,
|
||||
cancelled: count,
|
||||
});
|
||||
const summary = z.object({
|
||||
kind: z.enum(['parameters', 'cost-sensitivity']).optional(),
|
||||
id: z.string().uuid(),
|
||||
name: z.string().min(1),
|
||||
backtestId: z.string().uuid(),
|
||||
createdAt: z.string().min(1),
|
||||
cancelRequested: z.boolean(),
|
||||
trialCount: count.min(1),
|
||||
counts,
|
||||
datasetHash: hash,
|
||||
strategyVersionId: z.string().uuid(),
|
||||
previewHash: hash,
|
||||
});
|
||||
const timestamp = z.number().int().min(-8640000000000000).max(8640000000000000);
|
||||
const dataset = z
|
||||
.object({
|
||||
version: z.literal(2),
|
||||
hash,
|
||||
bounds: z.object({
|
||||
warmupStart: timestamp,
|
||||
tradeStart: timestamp,
|
||||
tradeEnd: timestamp,
|
||||
}),
|
||||
series: z.array(
|
||||
z.object({ id: z.string(), instrumentId: z.string(), interval: z.string() }).passthrough()
|
||||
),
|
||||
})
|
||||
.passthrough();
|
||||
/** Only the manifest fields consumed by this UI are structurally decoded here. */
|
||||
export type ExperimentPreviewView = Omit<ExperimentPreview, 'dataset'> & {
|
||||
dataset: z.infer<typeof dataset>;
|
||||
};
|
||||
export type ExperimentDetailView = Omit<ExperimentDetail, 'preview'> & {
|
||||
preview: ExperimentPreviewView;
|
||||
};
|
||||
export type CostSensitivityPreviewView = Omit<CostSensitivityPreview, 'dataset' | 'source'> & {
|
||||
dataset: ExperimentPreviewView['dataset'];
|
||||
source: ExperimentPreviewView;
|
||||
};
|
||||
export type WorkbenchExperimentPreviewView = ExperimentPreviewView | CostSensitivityPreviewView;
|
||||
export type CostSensitivityDetailView = Omit<CostSensitivityDetail, 'preview'> & {
|
||||
preview: CostSensitivityPreviewView;
|
||||
};
|
||||
export type WorkbenchExperimentDetailView = ExperimentDetailView | CostSensitivityDetailView;
|
||||
const preview = z
|
||||
.object({
|
||||
version: z.literal('research-experiment-preview/v1'),
|
||||
previewHash: hash,
|
||||
input: experimentInputSchema,
|
||||
request: canonicalRunRequestSchema,
|
||||
dataset,
|
||||
candidates: z.array(candidate).min(1).max(MAX_EXPERIMENT_TRIALS),
|
||||
})
|
||||
.strict();
|
||||
const metric = z.number().finite().nullable();
|
||||
export const experimentMetricsSchema = z.object({
|
||||
totalReturn: metric,
|
||||
cagr: metric,
|
||||
maxDrawdown: metric,
|
||||
exposureTime: metric,
|
||||
volatility: metric,
|
||||
downsideDeviation: metric,
|
||||
sharpeRatio: metric,
|
||||
sortinoRatio: metric,
|
||||
var95: metric,
|
||||
cvar95: metric,
|
||||
var99: metric,
|
||||
alpha: z.null(),
|
||||
beta: z.null(),
|
||||
informationRatio: z.null(),
|
||||
roundTripCount: z.null(),
|
||||
winRate: z.null(),
|
||||
profitFactor: z.null(),
|
||||
avgWin: z.null(),
|
||||
avgLoss: z.null(),
|
||||
});
|
||||
const trial = candidate.extend({
|
||||
runId: z.string().uuid().nullable(),
|
||||
attemptNumber: counter,
|
||||
retryCount: counter,
|
||||
status: z.enum([...statuses, 'missing']),
|
||||
progress: z.number().finite().min(0).max(100),
|
||||
cancelRequested: z.boolean(),
|
||||
error: z.string().nullable(),
|
||||
comparable: z.boolean(),
|
||||
diagnostic: z.string().nullable(),
|
||||
metrics: experimentMetricsSchema.nullable(),
|
||||
unavailable: z.record(z.string()).nullable(),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const detail = summary.extend({
|
||||
standalone: z.boolean().optional(),
|
||||
preview,
|
||||
trials: z.array(trial).max(MAX_EXPERIMENT_TRIALS),
|
||||
});
|
||||
const retryReceipt = z.object({
|
||||
id: z.string().uuid(),
|
||||
experimentId: z.string().uuid(),
|
||||
runId: z.string().uuid(),
|
||||
trialKey: hash,
|
||||
retryNumber: counter.min(1),
|
||||
previousAttemptNumber: counter,
|
||||
previousAttemptId: z.string().uuid().nullable(),
|
||||
error: z.string().nullable(),
|
||||
progress: z.number().finite().min(0).max(100),
|
||||
currentDate: z.string().nullable(),
|
||||
startedAt: z.string().nullable(),
|
||||
completedAt: z.string().nullable(),
|
||||
pausedAt: z.string().nullable(),
|
||||
failureUpdatedAt: z.string().min(1),
|
||||
recordedAt: z.string().min(1),
|
||||
principal: researchActorSchema,
|
||||
reviewId: z.string().uuid().nullable(),
|
||||
});
|
||||
/** Immutable source identity captured when the operator reviews a failed trial. */
|
||||
export interface ExperimentRetryTarget {
|
||||
experimentId: string;
|
||||
backtestId: string;
|
||||
previewHash: string;
|
||||
runId: string;
|
||||
trialKey: string;
|
||||
}
|
||||
const same = (left: unknown, right: unknown) =>
|
||||
canonicalStrategyJson(left) === canonicalStrategyJson(right);
|
||||
const invalid = () =>
|
||||
new ExperimentApiError(
|
||||
'The experiment response could not be verified. Refresh or retry the same submission.',
|
||||
null
|
||||
);
|
||||
|
||||
function parseSummary(value: unknown): ExperimentSummary {
|
||||
const parsed = summary.parse(value);
|
||||
if (Object.values(parsed.counts).reduce((sum, value) => sum + value, 0) > parsed.trialCount) {
|
||||
throw invalid();
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
export function parseExperimentPreview(value: unknown): ExperimentPreviewView {
|
||||
const parsed = preview.parse(value);
|
||||
if (
|
||||
parsed.input.backtestId !== parsed.request.backtestId ||
|
||||
(parsed.input.candidate &&
|
||||
(parsed.request.strategy.origin !== 'candidate' ||
|
||||
parsed.input.candidate.versionId !== parsed.request.strategy.versionId ||
|
||||
!same(
|
||||
validateStrategyParameters(
|
||||
parsed.request.strategy.package,
|
||||
parsed.input.candidate.parameters
|
||||
),
|
||||
parsed.request.strategy.selection.parameters
|
||||
))) ||
|
||||
parsed.dataset.hash !== parsed.request.datasetHash ||
|
||||
parsed.dataset.bounds.warmupStart > parsed.dataset.bounds.tradeStart ||
|
||||
parsed.dataset.bounds.tradeStart >= parsed.dataset.bounds.tradeEnd ||
|
||||
!parsed.dataset.series.some(
|
||||
series =>
|
||||
series.id === parsed.request.strategy.selection.seriesId &&
|
||||
series.instrumentId === parsed.request.strategy.selection.instrumentId
|
||||
) ||
|
||||
parsed.candidates.some((item, index) => item.index !== index) ||
|
||||
new Set(parsed.candidates.map(item => item.trialKey)).size !== parsed.candidates.length
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
// The server retains and verifies the complete manifest; the browser only renders its identity/window.
|
||||
return parsed;
|
||||
}
|
||||
const costCandidate = candidate.extend({ costs: costScenarioSchema });
|
||||
const costPreview = preview
|
||||
.omit({ version: true, input: true, candidates: true })
|
||||
.extend({
|
||||
version: z.literal('cost-sensitivity-preview/v1'),
|
||||
input: costSensitivityInputSchema,
|
||||
source: z.unknown(),
|
||||
candidates: z.array(costCandidate).min(2).max(MAX_EXPERIMENT_TRIALS),
|
||||
})
|
||||
.strict();
|
||||
const costDetail = summary.extend({
|
||||
kind: z.literal('cost-sensitivity'),
|
||||
standalone: z.boolean().optional(),
|
||||
preview: z.unknown(),
|
||||
trials: z.array(trial.extend({ costs: costScenarioSchema })).max(MAX_EXPERIMENT_TRIALS),
|
||||
});
|
||||
export function parseCostSensitivityPreview(raw: unknown): CostSensitivityPreviewView {
|
||||
const parsed = costPreview.parse(raw),
|
||||
source = parseExperimentPreview(parsed.source);
|
||||
const costs = [
|
||||
{
|
||||
feeRate: source.request.policy.matching.risk.feeRate,
|
||||
slippageRate: source.request.policy.matching.slippageRate,
|
||||
},
|
||||
...parsed.input.scenarios,
|
||||
];
|
||||
if (
|
||||
!same(source.input, {
|
||||
backtestId: parsed.input.backtestId,
|
||||
name: parsed.input.name,
|
||||
grid: {},
|
||||
...(parsed.input.candidate ? { candidate: parsed.input.candidate } : {}),
|
||||
}) ||
|
||||
source.candidates.length !== 1 ||
|
||||
!same(source.candidates[0]?.parameters, source.request.strategy.selection.parameters) ||
|
||||
!same(parsed.request, source.request) ||
|
||||
!same(parsed.dataset, source.dataset) ||
|
||||
parsed.candidates.length !== costs.length ||
|
||||
new Set(costs.map(canonicalStrategyJson)).size !== costs.length ||
|
||||
new Set(parsed.candidates.map(item => item.trialKey)).size !== costs.length ||
|
||||
parsed.candidates.some(
|
||||
(item, index) =>
|
||||
item.index !== index ||
|
||||
!same(item.parameters, source.request.strategy.selection.parameters) ||
|
||||
!same(item.costs, costs[index])
|
||||
)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...parsed, source } as CostSensitivityPreviewView;
|
||||
}
|
||||
function checkDetail(
|
||||
parsed: z.infer<typeof detail> | z.infer<typeof costDetail>,
|
||||
retained: WorkbenchExperimentPreviewView
|
||||
) {
|
||||
parseSummary(parsed);
|
||||
if (
|
||||
parsed.backtestId !== retained.input.backtestId ||
|
||||
parsed.name !== retained.input.name ||
|
||||
parsed.previewHash !== retained.previewHash ||
|
||||
parsed.datasetHash !== retained.request.datasetHash ||
|
||||
parsed.strategyVersionId !== retained.request.strategy.versionId ||
|
||||
parsed.trialCount !== retained.candidates.length ||
|
||||
parsed.trials.length !== parsed.trialCount
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const costKind = retained.version === 'cost-sensitivity-preview/v1';
|
||||
if (
|
||||
(costKind && parsed.kind !== 'cost-sensitivity') ||
|
||||
(!costKind && parsed.kind === 'cost-sensitivity')
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const runIds = new Set<string>();
|
||||
for (const [index, item] of parsed.trials.entries()) {
|
||||
const expected = retained.candidates[index];
|
||||
if (
|
||||
!expected ||
|
||||
item.index !== expected.index ||
|
||||
item.trialKey !== expected.trialKey ||
|
||||
!same(item.parameters, expected.parameters) ||
|
||||
(costKind &&
|
||||
(!('costs' in item) || !('costs' in expected) || !same(item.costs, expected.costs))) ||
|
||||
(item.status === 'missing') !== (item.runId === null) ||
|
||||
(item.status === 'missing' && (item.attemptNumber !== 0 || item.retryCount !== 0)) ||
|
||||
(item.comparable && (item.status !== 'completed' || !item.metrics || !item.unavailable)) ||
|
||||
(item.runId !== null && runIds.has(item.runId))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
if (item.runId) {
|
||||
runIds.add(item.runId);
|
||||
}
|
||||
}
|
||||
if (
|
||||
statuses.some(
|
||||
status =>
|
||||
parsed.counts[status] !== parsed.trials.filter(item => item.status === status).length
|
||||
)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
|
||||
return { ...parsed, preview: retained };
|
||||
}
|
||||
export function parseExperimentDetail(value: unknown): ExperimentDetailView {
|
||||
const parsed = detail.parse(value);
|
||||
return checkDetail(parsed, parseExperimentPreview(parsed.preview)) as ExperimentDetailView;
|
||||
}
|
||||
export function parseWorkbenchExperimentDetail(value: unknown): WorkbenchExperimentDetailView {
|
||||
const version = z.object({ preview: z.object({ version: z.string() }) }).parse(value)
|
||||
.preview.version;
|
||||
if (version === 'research-experiment-preview/v1') {
|
||||
return parseExperimentDetail(value);
|
||||
}
|
||||
if (version !== 'cost-sensitivity-preview/v1') {
|
||||
throw invalid();
|
||||
}
|
||||
const parsed = costDetail.parse(value);
|
||||
return checkDetail(
|
||||
parsed,
|
||||
parseCostSensitivityPreview(parsed.preview)
|
||||
) as CostSensitivityDetailView;
|
||||
}
|
||||
|
||||
export {
|
||||
retryReceipt as experimentRetryReceiptSchema,
|
||||
invalid as invalidExperimentResponse,
|
||||
parseSummary as parseExperimentSummary,
|
||||
same as sameExperimentInput,
|
||||
};
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
export * from './experiment';
|
||||
export * from './validation';
|
||||
export * from './validation-preview';
|
||||
export * from './walk-forward';
|
||||
export * from './comparison';
|
||||
|
|
@ -0,0 +1,138 @@
|
|||
/** Shared response verification for browser and authorized research clients; no IO or accounting. */
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
chronologicalPolicyForOrigin,
|
||||
chronologicalValidationInputSchema,
|
||||
type ChronologicalValidationInput,
|
||||
type ChronologicalValidationPreview,
|
||||
type ValidationPartitionPreview,
|
||||
} from '../chronological-validation';
|
||||
import { canonicalStrategyJson } from '../strategy';
|
||||
import { parseExperimentPreview, type ExperimentPreviewView } from './experiment';
|
||||
|
||||
export type ValidationPartitionView = Omit<ValidationPartitionPreview, 'dataset'> & {
|
||||
dataset: ExperimentPreviewView['dataset'];
|
||||
};
|
||||
export type ChronologicalValidationPreviewView = Omit<
|
||||
ChronologicalValidationPreview,
|
||||
'source' | 'partitions'
|
||||
> & {
|
||||
source: ExperimentPreviewView;
|
||||
partitions: [ValidationPartitionView, ValidationPartitionView, ValidationPartitionView];
|
||||
};
|
||||
const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const counts = z.object({
|
||||
totalBars: counter,
|
||||
availableWarmup: counter,
|
||||
admittedWarmup: counter,
|
||||
ignoredLateWarmup: counter,
|
||||
availableEvaluation: counter,
|
||||
terminalAtEnd: counter,
|
||||
unavailableAtEnd: counter,
|
||||
});
|
||||
const partition = z.object({
|
||||
phase: z.enum(['train', 'validation', 'test']),
|
||||
dataset: z.unknown(),
|
||||
request: z.unknown(),
|
||||
counts,
|
||||
requiredWarmup: counter,
|
||||
warnings: z.array(z.string()),
|
||||
});
|
||||
const prepared = z.object({
|
||||
version: z.literal('chronological-validation-preview/v1'),
|
||||
execution: z.literal('preview-only'),
|
||||
previewHash: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
input: chronologicalValidationInputSchema,
|
||||
source: z.unknown(),
|
||||
policy: z.unknown(),
|
||||
partitions: z.tuple([partition, partition, partition]),
|
||||
});
|
||||
const same = (left: unknown, right: unknown) =>
|
||||
canonicalStrategyJson(left) === canonicalStrategyJson(right);
|
||||
const invalid = () =>
|
||||
new Error(
|
||||
'The chronological validation preview could not be verified. Preview the current inputs again.'
|
||||
);
|
||||
|
||||
export function parseChronologicalValidationPreview(
|
||||
body: unknown,
|
||||
input: ChronologicalValidationInput
|
||||
): ChronologicalValidationPreviewView {
|
||||
const value = prepared.parse(z.object({ preview: z.unknown() }).parse(body).preview);
|
||||
const source = parseExperimentPreview(value.source);
|
||||
const { recipe: _recipe, ...sourceInput } = input;
|
||||
if (
|
||||
!same(value.input, input) ||
|
||||
!same(source.input, sourceInput) ||
|
||||
!same(value.policy, chronologicalPolicyForOrigin(source.request.strategy.origin))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const phases = ['train', 'validation', 'test'] as const;
|
||||
const partitions = value.partitions.map((part, index): ValidationPartitionView => {
|
||||
const phase = phases[index];
|
||||
if (!phase || part.phase !== phase) {
|
||||
throw invalid();
|
||||
}
|
||||
const decoded = parseExperimentPreview({
|
||||
...source,
|
||||
dataset: part.dataset,
|
||||
request: part.request,
|
||||
});
|
||||
const { request, dataset } = decoded;
|
||||
const expected = {
|
||||
...source.request,
|
||||
datasetHash: dataset.hash,
|
||||
policy: {
|
||||
...source.request.policy,
|
||||
risk_boundaries: request.policy.risk_boundaries,
|
||||
matching: {
|
||||
...source.request.policy.matching,
|
||||
risk: {
|
||||
...source.request.policy.matching.risk,
|
||||
ledger: {
|
||||
...source.request.policy.matching.risk.ledger,
|
||||
riskSession: request.policy.matching.risk.ledger.riskSession,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
const measured = part.counts;
|
||||
const metadata = (manifest: ExperimentPreviewView['dataset']) => {
|
||||
const { hash: _hash, bounds: _bounds, barCount: _barCount, ...retained } = manifest;
|
||||
return retained;
|
||||
};
|
||||
if (
|
||||
!same(request, expected) ||
|
||||
!same(dataset.bounds, input.recipe[phase]) ||
|
||||
!same(metadata(dataset), metadata(source.dataset)) ||
|
||||
measured.totalBars !== dataset.barCount ||
|
||||
dataset.bounds.warmupStart < source.dataset.bounds.warmupStart ||
|
||||
dataset.bounds.tradeStart < source.dataset.bounds.tradeStart ||
|
||||
dataset.bounds.tradeEnd > source.dataset.bounds.tradeEnd ||
|
||||
measured.totalBars !==
|
||||
measured.availableWarmup +
|
||||
measured.availableEvaluation +
|
||||
measured.terminalAtEnd +
|
||||
measured.unavailableAtEnd ||
|
||||
measured.availableWarmup !== measured.admittedWarmup + measured.ignoredLateWarmup ||
|
||||
measured.admittedWarmup < part.requiredWarmup ||
|
||||
(source.request.strategy.origin === 'candidate'
|
||||
? part.requiredWarmup !== source.request.strategy.package.execution?.warmupBars
|
||||
: part.requiredWarmup < 1) ||
|
||||
measured.availableEvaluation === 0
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...part, phase, request, dataset };
|
||||
}) as [ValidationPartitionView, ValidationPartitionView, ValidationPartitionView];
|
||||
return {
|
||||
...value,
|
||||
source,
|
||||
policy: chronologicalPolicyForOrigin(source.request.strategy.origin),
|
||||
partitions,
|
||||
};
|
||||
}
|
||||
|
||||
export { invalid as invalidValidationPreview };
|
||||
288
apps/stock/config/src/contracts/research-responses/validation.ts
Normal file
288
apps/stock/config/src/contracts/research-responses/validation.ts
Normal file
|
|
@ -0,0 +1,288 @@
|
|||
/** Shared response verification for browser and authorized research clients; no IO or accounting. */
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
chronologicalValidationInputSchema,
|
||||
type ChronologicalValidationDetail,
|
||||
} from '../chronological-validation';
|
||||
import { researchActorSchema } from '../research';
|
||||
import { canonicalStrategyJson } from '../strategy';
|
||||
import {
|
||||
experimentMetricsSchema,
|
||||
parseExperimentDetail,
|
||||
type ExperimentDetailView,
|
||||
} from './experiment';
|
||||
import {
|
||||
parseChronologicalValidationPreview,
|
||||
type ChronologicalValidationPreviewView,
|
||||
} from './validation-preview';
|
||||
|
||||
export type ValidationDetailView = Omit<ChronologicalValidationDetail, 'preview' | 'phases'> & {
|
||||
preview: ChronologicalValidationPreviewView;
|
||||
phases: Array<{
|
||||
phase: 'train' | 'validation' | 'test';
|
||||
status: 'not-admitted' | 'admitted' | 'missing';
|
||||
experimentId: string | null;
|
||||
experiment: ExperimentDetailView | null;
|
||||
}>;
|
||||
};
|
||||
export class ValidationApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number | null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
get ambiguous() {
|
||||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/),
|
||||
uuid = z.string().uuid(),
|
||||
count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const candidate = z.object({
|
||||
index: count,
|
||||
trialKey: hash,
|
||||
parameters: z.record(z.union([z.string(), z.number().finite(), z.boolean()])),
|
||||
});
|
||||
const actor = researchActorSchema;
|
||||
const summary = z.object({
|
||||
id: uuid,
|
||||
name: z.string().min(1),
|
||||
backtestId: uuid,
|
||||
createdAt: z.string().min(1),
|
||||
cancelRequested: z.boolean(),
|
||||
previewHash: hash,
|
||||
trainingCandidateCount: count.min(1).max(100),
|
||||
stage: z.enum(['training', 'holdouts', 'reported']),
|
||||
});
|
||||
export const validationEvidenceSchema = z.object({
|
||||
phase: z.enum(['train', 'validation', 'test']),
|
||||
experimentId: uuid,
|
||||
runId: uuid,
|
||||
sourceCandidateIndex: count,
|
||||
trialKey: hash,
|
||||
parameters: candidate.shape.parameters,
|
||||
datasetHash: hash,
|
||||
requestHash: hash,
|
||||
economicHash: hash,
|
||||
metrics: experimentMetricsSchema,
|
||||
unavailable: z.record(z.string()),
|
||||
completePeriodCount: count,
|
||||
periodicSampleCount: count,
|
||||
fillCount: count,
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const selection = z.object({
|
||||
version: z.literal('chronological-validation-selection/v1'),
|
||||
id: uuid,
|
||||
validationId: uuid,
|
||||
previewHash: hash,
|
||||
selectionHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: actor,
|
||||
reviewId: uuid.nullable(),
|
||||
winner: candidate,
|
||||
training: z.array(validationEvidenceSchema).min(1).max(100),
|
||||
holdoutExperimentIds: z.object({ validation: uuid, test: uuid }),
|
||||
});
|
||||
const report = z.object({
|
||||
version: z.literal('chronological-validation-report/v1'),
|
||||
id: uuid,
|
||||
validationId: uuid,
|
||||
previewHash: hash,
|
||||
selectionHash: hash,
|
||||
reportHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: actor,
|
||||
reset: z.literal('initial-capital-empty-positions'),
|
||||
training: z.array(validationEvidenceSchema).min(1).max(100),
|
||||
validation: validationEvidenceSchema,
|
||||
test: validationEvidenceSchema,
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const capability = z.object({ available: z.boolean(), reason: z.string().nullable() });
|
||||
const phase = z.object({
|
||||
phase: z.enum(['train', 'validation', 'test']),
|
||||
status: z.enum(['not-admitted', 'admitted', 'missing']),
|
||||
experimentId: uuid.nullable(),
|
||||
experiment: z.unknown(),
|
||||
});
|
||||
const detail = summary.extend({
|
||||
preview: z.unknown(),
|
||||
phases: z.tuple([phase, phase, phase]),
|
||||
selection: selection.nullable(),
|
||||
report: report.nullable(),
|
||||
actions: z.object({ select: capability, finalize: capability }),
|
||||
});
|
||||
const receipt = z.object({
|
||||
id: uuid,
|
||||
validationId: uuid,
|
||||
operation: z.enum(['select-and-admit-holdouts', 'finalize-report']),
|
||||
previewHash: hash,
|
||||
selectionHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: actor,
|
||||
});
|
||||
const same = (a: unknown, b: unknown) => canonicalStrategyJson(a) === canonicalStrategyJson(b);
|
||||
const invalid = () =>
|
||||
new ValidationApiError(
|
||||
'The saved validation response could not be verified. Refresh or retry the same request.',
|
||||
null
|
||||
);
|
||||
export function parseValidationDetail(raw: unknown): ValidationDetailView {
|
||||
const value = detail.parse(raw);
|
||||
const rawPreview = z.object({ input: chronologicalValidationInputSchema }).parse(value.preview);
|
||||
const preview = parseChronologicalValidationPreview({ preview: value.preview }, rawPreview.input);
|
||||
if (
|
||||
value.backtestId !== preview.input.backtestId ||
|
||||
value.name !== preview.input.name ||
|
||||
value.previewHash !== preview.previewHash ||
|
||||
value.trainingCandidateCount !== preview.source.candidates.length ||
|
||||
(value.selection?.reviewId === null &&
|
||||
preview.source.request.strategy.origin !== 'candidate') ||
|
||||
(value.stage === 'training') !== (value.selection === null) ||
|
||||
(value.stage === 'reported') !== (value.report !== null)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const phases = value.phases.map((item, index) => {
|
||||
const name = (['train', 'validation', 'test'] as const)[index];
|
||||
if (item.phase !== name || (item.status === 'admitted') !== (item.experiment !== null)) {
|
||||
throw invalid();
|
||||
}
|
||||
const expectedId =
|
||||
name === 'train'
|
||||
? value.id
|
||||
: (value.selection?.holdoutExperimentIds[name ?? 'validation'] ?? null);
|
||||
if (
|
||||
item.experimentId !== expectedId ||
|
||||
(item.status === 'not-admitted') !== (expectedId === null)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const experiment = item.experiment === null ? null : parseExperimentDetail(item.experiment);
|
||||
if (experiment) {
|
||||
const prototype = preview.partitions[index];
|
||||
const parameters =
|
||||
name === 'train'
|
||||
? prototype?.request.strategy.selection.parameters
|
||||
: value.selection?.winner.parameters;
|
||||
if (!prototype || !parameters) {
|
||||
throw invalid();
|
||||
}
|
||||
const expectedRequest = {
|
||||
...prototype.request,
|
||||
strategy: {
|
||||
...prototype.request.strategy,
|
||||
reviewId:
|
||||
name === 'train' ? prototype.request.strategy.reviewId : value.selection?.reviewId,
|
||||
selection: { ...prototype.request.strategy.selection, parameters },
|
||||
},
|
||||
};
|
||||
const expectedCandidates =
|
||||
name === 'train' ? preview.source.candidates : [{ ...value.selection?.winner, index: 0 }];
|
||||
if (
|
||||
experiment.id !== expectedId ||
|
||||
experiment.backtestId !== value.backtestId ||
|
||||
!same(experiment.preview.request, expectedRequest) ||
|
||||
!same(experiment.preview.dataset, prototype.dataset) ||
|
||||
!same(experiment.preview.candidates, expectedCandidates) ||
|
||||
!same(
|
||||
experiment.preview.input.candidate ?? null,
|
||||
preview.input.candidate
|
||||
? {
|
||||
...preview.input.candidate,
|
||||
parameters:
|
||||
name === 'train'
|
||||
? preview.input.candidate.parameters
|
||||
: value.selection?.winner.parameters,
|
||||
}
|
||||
: null
|
||||
) ||
|
||||
!same(experiment.preview.input.grid, name === 'train' ? preview.input.grid : {})
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
return { ...item, experiment };
|
||||
});
|
||||
const validateEvidence = (
|
||||
item: z.infer<typeof validationEvidenceSchema>,
|
||||
expectedPhase: 'train' | 'validation' | 'test'
|
||||
) => {
|
||||
const index = ['train', 'validation', 'test'].indexOf(expectedPhase);
|
||||
const candidateValue = preview.source.candidates[item.sourceCandidateIndex];
|
||||
const phaseValue = phases[index];
|
||||
const trial = phaseValue?.experiment?.trials.find(
|
||||
trial => trial.runId === item.runId && trial.trialKey === item.trialKey
|
||||
);
|
||||
if (
|
||||
!candidateValue ||
|
||||
!phaseValue ||
|
||||
item.phase !== expectedPhase ||
|
||||
item.experimentId !== phaseValue.experimentId ||
|
||||
item.trialKey !== candidateValue.trialKey ||
|
||||
!same(item.parameters, candidateValue.parameters) ||
|
||||
item.datasetHash !== preview.partitions[index]?.dataset.hash ||
|
||||
(expectedPhase !== 'train' && item.sourceCandidateIndex !== value.selection?.winner.index) ||
|
||||
(phaseValue.experiment &&
|
||||
(!trial ||
|
||||
trial.status !== 'completed' ||
|
||||
!trial.comparable ||
|
||||
!same(trial.metrics, item.metrics) ||
|
||||
!same(trial.unavailable, item.unavailable) ||
|
||||
!same(trial.limitations, item.limitations)))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
};
|
||||
if (value.selection) {
|
||||
const chosen = value.selection;
|
||||
if (
|
||||
chosen.validationId !== value.id ||
|
||||
chosen.previewHash !== value.previewHash ||
|
||||
!same(chosen.winner, preview.source.candidates[chosen.winner.index]) ||
|
||||
chosen.training.length !== value.trainingCandidateCount ||
|
||||
chosen.training.some((item, index) => item.sourceCandidateIndex !== index) ||
|
||||
new Set([value.id, chosen.holdoutExperimentIds.validation, chosen.holdoutExperimentIds.test])
|
||||
.size !== 3
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
for (const item of chosen.training) {
|
||||
validateEvidence(item, 'train');
|
||||
if (item.metrics.totalReturn === null) {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (value.report) {
|
||||
const saved = value.report;
|
||||
if (
|
||||
!value.selection ||
|
||||
saved.validationId !== value.id ||
|
||||
saved.previewHash !== value.previewHash ||
|
||||
saved.selectionHash !== value.selection.selectionHash ||
|
||||
!same(saved.training, value.selection.training)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
validateEvidence(saved.validation, 'validation');
|
||||
validateEvidence(saved.test, 'test');
|
||||
}
|
||||
if (
|
||||
(value.actions.select.available && (value.selection || value.cancelRequested)) ||
|
||||
(value.actions.finalize.available &&
|
||||
(!value.selection || value.report || value.cancelRequested))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...value, preview, phases } as ValidationDetailView;
|
||||
}
|
||||
|
||||
export {
|
||||
invalid as invalidValidationResponse,
|
||||
same as sameValidationInput,
|
||||
receipt as validationReceiptSchema,
|
||||
summary as validationSummarySchema,
|
||||
};
|
||||
|
|
@ -0,0 +1,314 @@
|
|||
/** Shared response verification for browser and authorized research clients; no IO or accounting. */
|
||||
import { z } from 'zod';
|
||||
import { researchActorSchema } from '../research';
|
||||
import { canonicalStrategyJson } from '../strategy';
|
||||
import {
|
||||
MAX_WALK_FORWARD_RUNS,
|
||||
MAX_WALK_FORWARD_WINDOWS,
|
||||
walkForwardInputSchema,
|
||||
walkForwardPolicy,
|
||||
type WalkForwardDetail,
|
||||
type WalkForwardInput,
|
||||
} from '../walk-forward';
|
||||
import { parseExperimentPreview, type ExperimentPreviewView } from './experiment';
|
||||
import {
|
||||
parseValidationDetail,
|
||||
validationEvidenceSchema,
|
||||
type ValidationDetailView,
|
||||
} from './validation';
|
||||
import {
|
||||
parseChronologicalValidationPreview,
|
||||
type ChronologicalValidationPreviewView,
|
||||
} from './validation-preview';
|
||||
|
||||
export type WalkForwardPreviewView = {
|
||||
version: 'walk-forward-preview/v1';
|
||||
execution: 'preview-only';
|
||||
previewHash: string;
|
||||
input: WalkForwardInput;
|
||||
source: ExperimentPreviewView;
|
||||
policy: typeof walkForwardPolicy;
|
||||
windows: { index: number; preview: ChronologicalValidationPreviewView }[];
|
||||
counts: {
|
||||
windows: number;
|
||||
trainingRuns: number;
|
||||
holdoutRuns: number;
|
||||
totalRuns: number;
|
||||
maxRuns: number;
|
||||
};
|
||||
};
|
||||
export type WalkForwardDetailView = Omit<WalkForwardDetail, 'preview' | 'windows'> & {
|
||||
preview: WalkForwardPreviewView;
|
||||
windows: {
|
||||
index: number;
|
||||
validationId: string;
|
||||
status: 'admitted' | 'missing';
|
||||
validation: ValidationDetailView | null;
|
||||
}[];
|
||||
};
|
||||
export class WalkForwardApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number | null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
get ambiguous() {
|
||||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/),
|
||||
uuid = z.string().uuid(),
|
||||
count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const same = (left: unknown, right: unknown) =>
|
||||
canonicalStrategyJson(left) === canonicalStrategyJson(right);
|
||||
const invalid = () =>
|
||||
new WalkForwardApiError(
|
||||
'The walk-forward response could not be verified. Refresh or retry the same request.',
|
||||
null
|
||||
);
|
||||
const prepared = z.object({
|
||||
version: z.literal('walk-forward-preview/v1'),
|
||||
execution: z.literal('preview-only'),
|
||||
previewHash: hash,
|
||||
input: walkForwardInputSchema,
|
||||
source: z.unknown(),
|
||||
policy: z.unknown(),
|
||||
windows: z
|
||||
.array(z.object({ index: count, preview: z.unknown() }))
|
||||
.min(2)
|
||||
.max(MAX_WALK_FORWARD_WINDOWS),
|
||||
counts: z.object({
|
||||
windows: count,
|
||||
trainingRuns: count,
|
||||
holdoutRuns: count,
|
||||
totalRuns: count,
|
||||
maxRuns: count,
|
||||
}),
|
||||
});
|
||||
export function parseWalkForwardPreview(
|
||||
raw: unknown,
|
||||
expected?: WalkForwardInput
|
||||
): WalkForwardPreviewView {
|
||||
const value = prepared.parse(raw),
|
||||
source = parseExperimentPreview(value.source);
|
||||
const { windows: recipes, ...sourceInput } = value.input;
|
||||
const size = recipes.length,
|
||||
candidates = source.candidates.length;
|
||||
if (
|
||||
(expected && !same(value.input, expected)) ||
|
||||
!same(source.input, sourceInput) ||
|
||||
!same(value.policy, walkForwardPolicy) ||
|
||||
value.windows.length !== size ||
|
||||
!same(value.counts, {
|
||||
windows: size,
|
||||
trainingRuns: size * candidates,
|
||||
holdoutRuns: size * 2,
|
||||
totalRuns: size * (candidates + 2),
|
||||
maxRuns: MAX_WALK_FORWARD_RUNS,
|
||||
}) ||
|
||||
value.counts.totalRuns > MAX_WALK_FORWARD_RUNS
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const windows = value.windows.map((item, index) => {
|
||||
const recipe = recipes[index],
|
||||
previous = recipes[index - 1];
|
||||
if (
|
||||
!recipe ||
|
||||
item.index !== index ||
|
||||
(previous &&
|
||||
(recipe.train.tradeStart < previous.train.tradeStart ||
|
||||
recipe.train.tradeEnd <= previous.train.tradeEnd ||
|
||||
recipe.validation.tradeStart < previous.test.tradeEnd))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const name = `${value.input.name} · window ${index + 1}`;
|
||||
const preview = parseChronologicalValidationPreview(
|
||||
{ preview: item.preview },
|
||||
{ ...sourceInput, name, recipe }
|
||||
);
|
||||
const { previewHash: _windowHash, ...childSource } = preview.source;
|
||||
const { previewHash: _sourceHash, ...originalSource } = source;
|
||||
if (!same(childSource, { ...originalSource, input: { ...sourceInput, name } })) {
|
||||
throw invalid();
|
||||
}
|
||||
return { index, preview };
|
||||
});
|
||||
return { ...value, source, windows, policy: walkForwardPolicy };
|
||||
}
|
||||
const summary = z
|
||||
.object({
|
||||
id: uuid,
|
||||
backtestId: uuid,
|
||||
name: z.string().min(1),
|
||||
previewHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
cancelRequested: z.boolean(),
|
||||
windowCount: count.min(2).max(MAX_WALK_FORWARD_WINDOWS),
|
||||
reportedWindowCount: count,
|
||||
trainingRunCount: count,
|
||||
plannedRunCount: count.max(MAX_WALK_FORWARD_RUNS),
|
||||
stage: z.enum(['windows', 'reported']),
|
||||
})
|
||||
.superRefine((item, context) => {
|
||||
if (
|
||||
item.reportedWindowCount > item.windowCount ||
|
||||
item.trainingRunCount < item.windowCount ||
|
||||
item.plannedRunCount !== item.trainingRunCount + 2 * item.windowCount
|
||||
) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'Inconsistent walk-forward counts',
|
||||
});
|
||||
}
|
||||
});
|
||||
const report = z.object({
|
||||
version: z.literal('walk-forward-report/v1'),
|
||||
id: uuid,
|
||||
walkForwardId: uuid,
|
||||
previewHash: hash,
|
||||
reportHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: researchActorSchema,
|
||||
reset: z.literal('initial-capital-empty-positions'),
|
||||
segments: z
|
||||
.array(
|
||||
z.object({
|
||||
index: count,
|
||||
validationId: uuid,
|
||||
previewHash: hash,
|
||||
selectionHash: hash,
|
||||
reportId: uuid,
|
||||
reportHash: hash,
|
||||
validation: validationEvidenceSchema,
|
||||
test: validationEvidenceSchema,
|
||||
})
|
||||
)
|
||||
.min(2)
|
||||
.max(MAX_WALK_FORWARD_WINDOWS),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const detail = z.object({
|
||||
preview: z.unknown(),
|
||||
windows: z.array(
|
||||
z.object({
|
||||
index: count,
|
||||
validationId: uuid,
|
||||
status: z.enum(['admitted', 'missing']),
|
||||
validation: z.unknown(),
|
||||
})
|
||||
),
|
||||
report: report.nullable(),
|
||||
actions: z.object({
|
||||
finalize: z.object({ available: z.boolean(), reason: z.string().nullable() }),
|
||||
}),
|
||||
});
|
||||
export function parseWalkForwardDetail(raw: unknown): WalkForwardDetailView {
|
||||
const base = summary.parse(raw),
|
||||
value = detail.parse(raw),
|
||||
preview = parseWalkForwardPreview(value.preview);
|
||||
if (
|
||||
base.backtestId !== preview.input.backtestId ||
|
||||
base.name !== preview.input.name ||
|
||||
base.previewHash !== preview.previewHash ||
|
||||
base.windowCount !== preview.counts.windows ||
|
||||
base.trainingRunCount !== preview.counts.trainingRuns ||
|
||||
base.plannedRunCount !== preview.counts.totalRuns ||
|
||||
value.windows.length !== base.windowCount ||
|
||||
new Set(value.windows.map(item => item.validationId)).size !== base.windowCount ||
|
||||
(base.stage === 'reported') !== (value.report !== null)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const windows = value.windows.map((item, index) => {
|
||||
if (item.index !== index || (item.status === 'missing') !== (item.validation === null)) {
|
||||
throw invalid();
|
||||
}
|
||||
const validation = item.validation === null ? null : parseValidationDetail(item.validation);
|
||||
if (
|
||||
validation &&
|
||||
(validation.id !== item.validationId ||
|
||||
validation.backtestId !== base.backtestId ||
|
||||
!same(validation.preview, preview.windows[index]?.preview))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...item, validation };
|
||||
});
|
||||
if (
|
||||
base.reportedWindowCount !== windows.filter(item => item.validation?.report).length ||
|
||||
(value.actions.finalize.available &&
|
||||
(base.cancelRequested ||
|
||||
value.report ||
|
||||
windows.some(
|
||||
item =>
|
||||
!item.validation?.report ||
|
||||
item.validation.cancelRequested ||
|
||||
item.validation.phases.some(
|
||||
phase =>
|
||||
phase.status !== 'admitted' ||
|
||||
!phase.experiment ||
|
||||
phase.experiment.cancelRequested ||
|
||||
phase.experiment.trials.some(
|
||||
trial =>
|
||||
trial.status !== 'completed' || !trial.comparable || trial.cancelRequested
|
||||
)
|
||||
)
|
||||
)))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
if (value.report) {
|
||||
const saved = value.report;
|
||||
if (
|
||||
saved.walkForwardId !== base.id ||
|
||||
saved.previewHash !== base.previewHash ||
|
||||
saved.segments.length !== base.windowCount
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
for (const [index, segment] of saved.segments.entries()) {
|
||||
const member = windows[index],
|
||||
frozen = preview.windows[index]?.preview,
|
||||
child = member?.validation?.report;
|
||||
const candidate = frozen?.source.candidates[segment.validation.sourceCandidateIndex];
|
||||
if (
|
||||
!member ||
|
||||
!frozen ||
|
||||
!candidate ||
|
||||
segment.index !== index ||
|
||||
segment.validationId !== member.validationId ||
|
||||
segment.previewHash !== frozen.previewHash ||
|
||||
segment.validation.phase !== 'validation' ||
|
||||
segment.test.phase !== 'test' ||
|
||||
segment.validation.sourceCandidateIndex !== segment.test.sourceCandidateIndex ||
|
||||
segment.validation.datasetHash !== frozen.partitions[1].dataset.hash ||
|
||||
segment.test.datasetHash !== frozen.partitions[2].dataset.hash ||
|
||||
[segment.validation, segment.test].some(
|
||||
item =>
|
||||
item.trialKey !== candidate.trialKey || !same(item.parameters, candidate.parameters)
|
||||
) ||
|
||||
(member.validation &&
|
||||
(!child ||
|
||||
segment.reportId !== child.id ||
|
||||
segment.reportHash !== child.reportHash ||
|
||||
segment.selectionHash !== child.selectionHash ||
|
||||
!same(segment.validation, child.validation) ||
|
||||
!same(segment.test, child.test)))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
}
|
||||
return { ...base, ...value, preview, windows };
|
||||
}
|
||||
|
||||
export {
|
||||
invalid as invalidWalkForwardResponse,
|
||||
same as sameWalkForwardInput,
|
||||
hash as walkForwardHashSchema,
|
||||
uuid as walkForwardIdSchema,
|
||||
summary as walkForwardSummarySchema,
|
||||
};
|
||||
|
|
@ -10,6 +10,7 @@ import {
|
|||
meanReversionStrategySelectionSchema,
|
||||
smaStrategySelectionSchema,
|
||||
} from './builtin-strategy';
|
||||
import { candidatePackageExecutionSchema } from './candidate-execution';
|
||||
import { maxStrategyPeriod } from './strategy-names';
|
||||
|
||||
export * from './builtin-strategy';
|
||||
|
|
@ -70,6 +71,7 @@ const text = z.string().min(1);
|
|||
const packageSchema = z
|
||||
.object({
|
||||
version: z.literal(1),
|
||||
execution: candidatePackageExecutionSchema.optional(),
|
||||
program: z
|
||||
.object({
|
||||
strategyId: text,
|
||||
|
|
|
|||
|
|
@ -89,6 +89,14 @@ export const stockAppSchema = baseAppSchema.extend({
|
|||
paperTradingCapital: z.number().default(100000),
|
||||
// Validated by the orchestrator's canonical contract before opening resources.
|
||||
canonicalPaper: z.record(z.unknown()).optional(),
|
||||
// Explicitly creates an unbound/halted host. A supplied ID binds without activation.
|
||||
paperDeploymentHost: z
|
||||
.object({
|
||||
enabled: z.literal(true),
|
||||
deploymentId: z.string().uuid().optional(),
|
||||
})
|
||||
.strict()
|
||||
.optional(),
|
||||
enableWebSocket: z.boolean().default(true),
|
||||
backtesting: z
|
||||
.object({
|
||||
|
|
|
|||
6
apps/stock/engine/index.d.ts
vendored
6
apps/stock/engine/index.d.ts
vendored
|
|
@ -7,3 +7,9 @@ export {
|
|||
|
||||
declare const nativeBinding: typeof import('./dist/index');
|
||||
export default nativeBinding;
|
||||
|
||||
/** Exact wrapper/native bytes captured when this module first loaded. Artifact updates require restart. */
|
||||
export declare const loadedNativeIdentity: Readonly<{
|
||||
engineWrapperSha256: string;
|
||||
engineBinarySha256: string;
|
||||
}>;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
// ESM wrapper for the native module
|
||||
import { createRequire } from 'module';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
|
|
@ -7,7 +9,21 @@ const require = createRequire(import.meta.url);
|
|||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
|
||||
const nativeBinding = require(join(__dirname, 'dist', 'engine.node'));
|
||||
// Loaded executable identity is captured before native loading, not inferred later from disk.
|
||||
// Build artifacts must remain immutable while the process runs; updates require a restart.
|
||||
const nativePath = join(__dirname, 'dist', 'engine.node');
|
||||
const fileHash = path => createHash('sha256').update(readFileSync(path)).digest('hex');
|
||||
export const loadedNativeIdentity = Object.freeze({
|
||||
engineWrapperSha256: fileHash(__filename),
|
||||
engineBinarySha256: fileHash(nativePath),
|
||||
});
|
||||
const nativeBinding = require(nativePath);
|
||||
if (
|
||||
loadedNativeIdentity.engineWrapperSha256 !== fileHash(__filename) ||
|
||||
loadedNativeIdentity.engineBinarySha256 !== fileHash(nativePath)
|
||||
) {
|
||||
throw new Error('Native artifacts changed while loading; restart with immutable build artifacts');
|
||||
}
|
||||
|
||||
export const {
|
||||
TradingEngine,
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@
|
|||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"dev": "bun --watch src/index.ts",
|
||||
"build": "bun build src/index.ts src/backtest/native-worker.ts --outdir dist --entry-naming '[name].[ext]' --target node --external @stock-bot/engine --external @tensorflow/tfjs-node --external chromium-bidi --external electron --external playwright --external playwright-core",
|
||||
"build": "bun build src/index.ts src/backtest/native-worker.ts src/paper/paper-host.ts --outdir dist --entry-naming '[name].[ext]' --target node --external @stock-bot/engine --external @tensorflow/tfjs-node --external chromium-bidi --external electron --external playwright --external playwright-core",
|
||||
"start": "bun dist/index.js",
|
||||
"test": "bun test",
|
||||
"test:indicators": "bun test tests/indicators.test.ts",
|
||||
|
|
|
|||
96
apps/stock/orchestrator/src/api/rest/paper-deployments.ts
Normal file
96
apps/stock/orchestrator/src/api/rest/paper-deployments.ts
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
paperActivationSchema,
|
||||
paperHaltSchema,
|
||||
PaperRuntimeError,
|
||||
} from '../../contracts/paper-runtime';
|
||||
import { ExecutionConflictError } from '../../execution/repository';
|
||||
import { PaperDeploymentError } from '../../paper/paper-deployment-custody';
|
||||
import { paperAllowedOrigins, requirePaperOperator } from '../../paper/paper-operator';
|
||||
import type { PaperDeploymentHost } from '../../paper/PaperDeploymentHost';
|
||||
|
||||
export function createPaperDeploymentHostRoutes(
|
||||
host?: PaperDeploymentHost,
|
||||
origins: readonly string[] = paperAllowedOrigins()
|
||||
) {
|
||||
const app = new Hono();
|
||||
app.use('*', async (c, next) => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
requirePaperOperator(c.req.raw, origins);
|
||||
await next();
|
||||
});
|
||||
app.onError((error, c) => {
|
||||
if (error instanceof PaperDeploymentError) {
|
||||
return c.json({ error: error.message }, error.status);
|
||||
}
|
||||
if (error instanceof z.ZodError || error instanceof SyntaxError) {
|
||||
return c.json({ error: 'Invalid paper command' }, 400);
|
||||
}
|
||||
if (error instanceof PaperRuntimeError || error instanceof ExecutionConflictError) {
|
||||
return c.json({ error: error.message }, 409);
|
||||
}
|
||||
return c.json({ error: 'Paper deployment host unavailable' }, 503);
|
||||
});
|
||||
const configured = () => {
|
||||
if (!host) {
|
||||
throw new PaperDeploymentError(
|
||||
503,
|
||||
'Paper deployment host is explicitly disabled or unconfigured'
|
||||
);
|
||||
}
|
||||
return host;
|
||||
};
|
||||
app.get('/:id/readiness', async c =>
|
||||
c.json(
|
||||
await configured().status(
|
||||
z
|
||||
.string()
|
||||
.uuid()
|
||||
.transform(value => value.toLowerCase())
|
||||
.parse(c.req.param('id'))
|
||||
)
|
||||
)
|
||||
);
|
||||
app.post('/:id/bind', async c => {
|
||||
z.object({})
|
||||
.strict()
|
||||
.parse(await c.req.json());
|
||||
return c.json(
|
||||
await configured().bind(
|
||||
z
|
||||
.string()
|
||||
.uuid()
|
||||
.transform(value => value.toLowerCase())
|
||||
.parse(c.req.param('id'))
|
||||
)
|
||||
);
|
||||
});
|
||||
app.post('/:id/activate', async c => {
|
||||
const input = paperActivationSchema.parse(await c.req.json());
|
||||
return c.json(
|
||||
await configured().activate(
|
||||
z
|
||||
.string()
|
||||
.uuid()
|
||||
.transform(value => value.toLowerCase())
|
||||
.parse(c.req.param('id')),
|
||||
input.recoverPending
|
||||
)
|
||||
);
|
||||
});
|
||||
app.post('/:id/halt', async c => {
|
||||
const input = paperHaltSchema.parse(await c.req.json());
|
||||
return c.json(
|
||||
await configured().halt(
|
||||
z
|
||||
.string()
|
||||
.uuid()
|
||||
.transform(value => value.toLowerCase())
|
||||
.parse(c.req.param('id')),
|
||||
input.reason
|
||||
)
|
||||
);
|
||||
});
|
||||
return app;
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { getVerifiedHttpPrincipal } from '@stock-bot/di';
|
||||
import { getCredentialHttpPrincipal } from '@stock-bot/di';
|
||||
import {
|
||||
paperActivationSchema,
|
||||
paperConnectionSchema,
|
||||
|
|
@ -10,12 +10,20 @@ import {
|
|||
type PaperReadiness,
|
||||
} from '../../contracts/paper-runtime';
|
||||
import { ExecutionConflictError } from '../../execution/repository';
|
||||
import { PaperDeploymentError } from '../../paper/paper-deployment-custody';
|
||||
import { paperAllowedOrigins, requirePaperOperator } from '../../paper/paper-operator';
|
||||
import type { PaperDeploymentHost } from '../../paper/PaperDeploymentHost';
|
||||
import type { OrchestratorServices } from '../../types';
|
||||
|
||||
export function createPaperRoutes(services: OrchestratorServices): Hono {
|
||||
export function createPaperRoutes(
|
||||
services: OrchestratorServices,
|
||||
options: { deploymentHost?: PaperDeploymentHost; origins?: readonly string[] } = {}
|
||||
): Hono {
|
||||
const app = new Hono();
|
||||
const runtime = () => {
|
||||
const value = services.custom?.CanonicalPaperRuntime;
|
||||
const value = options.deploymentHost
|
||||
? options.deploymentHost.runtime()
|
||||
: services.custom?.CanonicalPaperRuntime;
|
||||
if (!value) {
|
||||
throw new PaperRuntimeError('not-ready', 'Canonical paper execution is not configured');
|
||||
}
|
||||
|
|
@ -24,8 +32,11 @@ export function createPaperRoutes(services: OrchestratorServices): Hono {
|
|||
app.use('*', async (c, next) => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
if (c.req.method !== 'GET') {
|
||||
const principal = getVerifiedHttpPrincipal(c.req.raw);
|
||||
const principal = getCredentialHttpPrincipal(c.req.raw);
|
||||
const feed = c.req.path.includes('/feed/');
|
||||
if (!feed) {
|
||||
requirePaperOperator(c.req.raw, options.origins ?? paperAllowedOrigins());
|
||||
}
|
||||
if (principal !== 'operator' && !(feed && principal === 'service')) {
|
||||
return c.json(
|
||||
{ error: feed ? 'Verified feed producer required' : 'Human operator required' },
|
||||
|
|
@ -37,6 +48,9 @@ export function createPaperRoutes(services: OrchestratorServices): Hono {
|
|||
return undefined;
|
||||
});
|
||||
app.onError((error, c) => {
|
||||
if (error instanceof PaperDeploymentError) {
|
||||
return c.json({ error: error.message }, error.status);
|
||||
}
|
||||
if (error instanceof z.ZodError || error instanceof SyntaxError) {
|
||||
return c.json({ error: 'Invalid paper request' }, 400);
|
||||
}
|
||||
|
|
@ -53,7 +67,10 @@ export function createPaperRoutes(services: OrchestratorServices): Hono {
|
|||
return c.json({ error: 'Canonical paper runtime unavailable' }, 503);
|
||||
});
|
||||
app.get('/readiness', async c => {
|
||||
if (!services.custom?.CanonicalPaperRuntime) {
|
||||
if (options.deploymentHost) {
|
||||
return c.json(await options.deploymentHost.readiness());
|
||||
}
|
||||
if (!services.custom?.CanonicalPaperRuntime && !options.deploymentHost) {
|
||||
const unavailable: PaperReadiness = {
|
||||
configured: false,
|
||||
accountId: null,
|
||||
|
|
@ -76,9 +93,12 @@ export function createPaperRoutes(services: OrchestratorServices): Hono {
|
|||
}
|
||||
return c.json(await runtime().status());
|
||||
});
|
||||
app.post('/activate', async c =>
|
||||
c.json(await runtime().activate(paperActivationSchema.parse(await c.req.json())))
|
||||
);
|
||||
app.post('/activate', async c => {
|
||||
if (options.deploymentHost) {
|
||||
throw new PaperDeploymentError(409, 'Use the deployment-bound activation endpoint');
|
||||
}
|
||||
return c.json(await runtime().activate(paperActivationSchema.parse(await c.req.json())));
|
||||
});
|
||||
app.post('/halt', async c =>
|
||||
c.json(await runtime().halt(paperHaltSchema.parse(await c.req.json()).reason))
|
||||
);
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import type { Logger } from '@stock-bot/services';
|
|||
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
canonicalStrategyExecution,
|
||||
type CanonicalRunRequest,
|
||||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
|
|
@ -260,14 +261,17 @@ export class BacktestRunner extends EventEmitter {
|
|||
throw new Error('Canonical execution capabilities are unavailable');
|
||||
}
|
||||
const claim = this.active;
|
||||
const report = await engine.runCanonical(executionConfig, signal =>
|
||||
loadCanonicalDataset.call(
|
||||
repository,
|
||||
claim.runId,
|
||||
claim.attemptId,
|
||||
executionConfig.datasetHash,
|
||||
signal
|
||||
)
|
||||
const report = await engine.runCanonical(
|
||||
executionConfig,
|
||||
signal =>
|
||||
loadCanonicalDataset.call(
|
||||
repository,
|
||||
claim.runId,
|
||||
claim.attemptId,
|
||||
executionConfig.datasetHash,
|
||||
signal
|
||||
),
|
||||
{ executionDeadlineAt: claim.executionDeadlineAt }
|
||||
);
|
||||
if (this.cancelled) {
|
||||
throw new BacktestCancelledError();
|
||||
|
|
@ -280,7 +284,7 @@ export class BacktestRunner extends EventEmitter {
|
|||
completedAt: new Date().toISOString(),
|
||||
executionTime: performance.now() - started,
|
||||
financialEngine: 'rust',
|
||||
strategyExecution: 'typescript-retained-builtin/v1',
|
||||
strategyExecution: canonicalStrategyExecution(executionConfig),
|
||||
request: executionConfig,
|
||||
...report,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { fork, type ChildProcess } from 'node:child_process';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { realpathSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import {
|
||||
|
|
@ -13,6 +14,7 @@ import {
|
|||
parseStrategyReplayResult,
|
||||
strategyReplayRequestSchema,
|
||||
} from '../contracts/strategy-replay';
|
||||
import { removeCandidateContainer } from './candidate-sandbox';
|
||||
import { canonicalWorkerUrl } from './canonical-build';
|
||||
import {
|
||||
nativeWorkerMessageSchema,
|
||||
|
|
@ -49,6 +51,16 @@ export class NativeBacktestWorker {
|
|||
request.type === 'runStrategyReplay'
|
||||
? structuredClone(strategyReplayRequestSchema.parse(request))
|
||||
: undefined;
|
||||
const candidateContainerName =
|
||||
retainedRequest?.request.strategy.origin === 'candidate'
|
||||
? `stock-bot-candidate-${randomUUID()}`
|
||||
: undefined;
|
||||
if (retainedRequest) {
|
||||
delete retainedRequest.candidateContainerName;
|
||||
if (candidateContainerName) {
|
||||
retainedRequest.candidateContainerName = candidateContainerName;
|
||||
}
|
||||
}
|
||||
const submitted = retainedRequest ?? strategyRequest ?? request;
|
||||
if (
|
||||
retainedRequest &&
|
||||
|
|
@ -155,7 +167,7 @@ export class NativeBacktestWorker {
|
|||
}
|
||||
}
|
||||
};
|
||||
const finish = (code: number | null, exitSignal: NodeJS.Signals | null) => {
|
||||
const finish = async (code: number | null, exitSignal: NodeJS.Signals | null) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -163,6 +175,13 @@ export class NativeBacktestWorker {
|
|||
signal.removeEventListener('abort', onAbort);
|
||||
child.off('message', onMessage);
|
||||
child.stderr?.off('data', onStderr);
|
||||
if (candidateContainerName) {
|
||||
try {
|
||||
await removeCandidateContainer(candidateContainerName);
|
||||
} catch (error) {
|
||||
failure ??= error instanceof Error ? error : new Error(String(error));
|
||||
}
|
||||
}
|
||||
this.active = undefined;
|
||||
if (failure) {
|
||||
reject(failure);
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import {
|
|||
} from '@stock-bot/stock-config/backtest';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
canonicalStrategyExecution,
|
||||
parseCanonicalFinancialResult,
|
||||
type CanonicalRunRequest,
|
||||
type CanonicalRunResult,
|
||||
|
|
@ -414,7 +415,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
result.runId !== request.runId ||
|
||||
result.backtestId !== request.backtestId ||
|
||||
result.financialEngine !== 'rust' ||
|
||||
result.strategyExecution !== 'typescript-retained-builtin/v1'
|
||||
result.strategyExecution !== canonicalStrategyExecution(request)
|
||||
) {
|
||||
throw new BacktestConflictError('Canonical result identity mismatch');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -58,7 +58,8 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
|
||||
async runCanonical(
|
||||
input: CanonicalRunRequest,
|
||||
resolveDataset: (signal: AbortSignal) => Promise<HistoricalDatasetV2>
|
||||
resolveDataset: (signal: AbortSignal) => Promise<HistoricalDatasetV2>,
|
||||
controls: { executionDeadlineAt?: number } = {}
|
||||
): Promise<Pick<CanonicalRunResult, 'financial' | 'analytics'>> {
|
||||
const request = canonicalRunRequestSchema.parse(input);
|
||||
return this.runOwned(
|
||||
|
|
@ -67,7 +68,14 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
const dataset = await Promise.race([resolveDataset(signal), aborted]);
|
||||
signal.throwIfAborted();
|
||||
const raw = await this.worker.execute(
|
||||
{ type: 'runRetainedStrategy', request, dataset },
|
||||
{
|
||||
type: 'runRetainedStrategy',
|
||||
request,
|
||||
dataset,
|
||||
...(controls.executionDeadlineAt === undefined
|
||||
? {}
|
||||
: { executionDeadlineAt: controls.executionDeadlineAt }),
|
||||
},
|
||||
signal,
|
||||
progress => {
|
||||
this.progress = progress.progress;
|
||||
|
|
|
|||
99
apps/stock/orchestrator/src/backtest/candidate-host.ts
Normal file
99
apps/stock/orchestrator/src/backtest/candidate-host.ts
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
/** This entrypoint runs ONLY inside the restricted image; never the API/native supervisor. */
|
||||
import { sameIdentity } from '../contracts/native-replay';
|
||||
import { importRetainedProgram } from '../strategies/retained-program';
|
||||
import { StrategyController } from '../strategies/strategy-controller';
|
||||
import { freeze } from '../strategies/strategy-decision';
|
||||
import {
|
||||
candidateRequestSchema,
|
||||
readCandidateFrames,
|
||||
writeCandidateFrame,
|
||||
} from './candidate-protocol';
|
||||
|
||||
// Ordinary logs are diagnostics, not protocol. Deliberate raw stdout forgery remains untrusted.
|
||||
// eslint-disable-next-line no-console -- stdout belongs exclusively to the framed protocol.
|
||||
console.log = console.info = console.debug = (...values: unknown[]) => console.error(...values);
|
||||
let controller: StrategyController | undefined;
|
||||
let identity: ConstructorParameters<typeof StrategyController>[0] | undefined;
|
||||
let sequence = 0;
|
||||
try {
|
||||
for await (const raw of readCandidateFrames(process.stdin)) {
|
||||
const request = candidateRequestSchema.parse(raw);
|
||||
if (request.sequence !== sequence) {
|
||||
throw new Error('Candidate protocol sequence mismatch');
|
||||
}
|
||||
const response = { version: 1, sequence };
|
||||
if (request.type === 'transpile') {
|
||||
if (sequence !== 0 || controller) {
|
||||
throw new Error('Packaging must be the first and only host operation');
|
||||
}
|
||||
const compiler = new Bun.Transpiler({ loader: 'ts', target: 'browser' });
|
||||
if (
|
||||
compiler.scanImports(request.source).length ||
|
||||
/\b(?:import|require)\s*\(/.test(request.source)
|
||||
) {
|
||||
throw new Error(
|
||||
'Candidate packaging accepts self-contained TypeScript without import/require edges'
|
||||
);
|
||||
}
|
||||
// Transformation only: top-level statements are data and are never imported or evaluated.
|
||||
const content = compiler.transformSync(request.source);
|
||||
if (compiler.scanImports(content).length) {
|
||||
throw new Error('Packaged candidate retained an import edge');
|
||||
}
|
||||
await writeCandidateFrame(process.stdout, {
|
||||
...response,
|
||||
type: 'transpiled',
|
||||
content,
|
||||
runtimeVersion: Bun.version,
|
||||
});
|
||||
process.exit(0);
|
||||
} else if (request.type === 'init') {
|
||||
if (controller || sequence !== 0) {
|
||||
throw new Error('Candidate host already initialized');
|
||||
}
|
||||
identity = freeze(request.identity);
|
||||
const program = await importRetainedProgram(
|
||||
request.package as Parameters<typeof importRetainedProgram>[0],
|
||||
request.selection
|
||||
);
|
||||
controller = new StrategyController(identity, [program], {
|
||||
matching: { owners: [{ ownerId: request.selection.ownerId, mode: 'Target' }] },
|
||||
});
|
||||
await writeCandidateFrame(process.stdout, { ...response, type: 'ready' });
|
||||
} else {
|
||||
if (!controller || !identity) {
|
||||
throw new Error('Candidate host is not initialized');
|
||||
}
|
||||
if (request.type === 'stage') {
|
||||
sameIdentity(request.published.identity, identity);
|
||||
if (request.published.step.type !== 'decisionBatch') {
|
||||
throw new Error('Candidate requires a decision barrier');
|
||||
}
|
||||
freeze(request.published);
|
||||
const decisions = controller.stage(request.published.step, request.published.observations);
|
||||
await writeCandidateFrame(process.stdout, { ...response, type: 'decisions', decisions });
|
||||
} else if (request.type === 'committed') {
|
||||
sameIdentity(request.admitted.identity, identity);
|
||||
freeze(request.admitted.outcome);
|
||||
controller.committed(request.admitted.outcome);
|
||||
await writeCandidateFrame(process.stdout, { ...response, type: 'ack' });
|
||||
} else {
|
||||
await writeCandidateFrame(process.stdout, { ...response, type: 'finished' });
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
sequence++;
|
||||
}
|
||||
throw new Error('Candidate supervisor disconnected before finish');
|
||||
} catch (error) {
|
||||
try {
|
||||
await writeCandidateFrame(process.stdout, {
|
||||
version: 1,
|
||||
sequence,
|
||||
type: 'error',
|
||||
message: String(error).slice(0, 4096),
|
||||
});
|
||||
} finally {
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
89
apps/stock/orchestrator/src/backtest/candidate-protocol.ts
Normal file
89
apps/stock/orchestrator/src/backtest/candidate-protocol.ts
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
/** Bounded transport, shared by the restricted host and its untrusted-output supervisor. */
|
||||
import { Readable, Writable } from 'node:stream';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
candidateSandboxLimits,
|
||||
retainedProgramSelectionSchema,
|
||||
} from '@stock-bot/stock-config/candidate-execution';
|
||||
import { parseFinancialStrategyDecision } from '@stock-bot/types';
|
||||
import { replayIdentitySchema, stepSchema, submissionSchema } from '../contracts/native-replay';
|
||||
|
||||
const base = {
|
||||
version: z.literal(1),
|
||||
sequence: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
||||
};
|
||||
export const candidateRequestSchema = z.discriminatedUnion('type', [
|
||||
z.object({ ...base, type: z.literal('transpile'), source: z.string().min(1) }).strict(),
|
||||
z
|
||||
.object({
|
||||
...base,
|
||||
type: z.literal('init'),
|
||||
identity: replayIdentitySchema,
|
||||
package: z.unknown(),
|
||||
selection: retainedProgramSelectionSchema,
|
||||
})
|
||||
.strict(),
|
||||
z.object({ ...base, type: z.literal('stage'), published: stepSchema }).strict(),
|
||||
z.object({ ...base, type: z.literal('committed'), admitted: submissionSchema }).strict(),
|
||||
z.object({ ...base, type: z.literal('finish') }).strict(),
|
||||
]);
|
||||
export const candidateResponseSchema = z.discriminatedUnion('type', [
|
||||
z.object({ ...base, type: z.literal('ready') }).strict(),
|
||||
z
|
||||
.object({
|
||||
...base,
|
||||
type: z.literal('transpiled'),
|
||||
content: z.string(),
|
||||
runtimeVersion: z.string().min(1),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
...base,
|
||||
type: z.literal('decisions'),
|
||||
decisions: z.array(z.unknown().transform(parseFinancialStrategyDecision)).length(1),
|
||||
})
|
||||
.strict(),
|
||||
z.object({ ...base, type: z.literal('ack') }).strict(),
|
||||
z.object({ ...base, type: z.literal('finished') }).strict(),
|
||||
z.object({ ...base, type: z.literal('error'), message: z.string().max(4096) }).strict(),
|
||||
]);
|
||||
export type CandidateResponse = z.infer<typeof candidateResponseSchema>;
|
||||
|
||||
export async function writeCandidateFrame(stream: Writable, value: unknown): Promise<void> {
|
||||
const body = Buffer.from(JSON.stringify(value));
|
||||
if (body.length > candidateSandboxLimits.frameBytes) {
|
||||
throw new Error('Candidate protocol frame exceeds its retained resource limit');
|
||||
}
|
||||
const header = Buffer.alloc(4);
|
||||
header.writeUInt32BE(body.length);
|
||||
await new Promise<void>((resolve, reject) =>
|
||||
stream.write(Buffer.concat([header, body]), error => (error ? reject(error) : resolve()))
|
||||
);
|
||||
}
|
||||
export async function* readCandidateFrames(stream: Readable): AsyncGenerator<unknown> {
|
||||
let buffer = Buffer.alloc(0);
|
||||
for await (const raw of stream) {
|
||||
const chunk = Buffer.isBuffer(raw) ? raw : Buffer.from(raw as string);
|
||||
// Readable chunks are bounded by stream buffering; reject oversized buffered input before parsing.
|
||||
if (buffer.length + chunk.length > candidateSandboxLimits.frameBytes + 4) {
|
||||
throw new Error('Candidate protocol buffer exceeds its retained resource limit');
|
||||
}
|
||||
buffer = Buffer.concat([buffer, chunk]);
|
||||
while (buffer.length >= 4) {
|
||||
const length = buffer.readUInt32BE(0);
|
||||
if (length === 0 || length > candidateSandboxLimits.frameBytes) {
|
||||
throw new Error('Invalid or oversized candidate protocol frame');
|
||||
}
|
||||
if (buffer.length < length + 4) {
|
||||
break;
|
||||
}
|
||||
const content = buffer.subarray(4, length + 4);
|
||||
buffer = buffer.subarray(length + 4);
|
||||
yield JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(content));
|
||||
}
|
||||
}
|
||||
if (buffer.length) {
|
||||
throw new Error('Truncated candidate protocol frame');
|
||||
}
|
||||
}
|
||||
467
apps/stock/orchestrator/src/backtest/candidate-sandbox.ts
Normal file
467
apps/stock/orchestrator/src/backtest/candidate-sandbox.ts
Normal file
|
|
@ -0,0 +1,467 @@
|
|||
/** Trusted launcher. Candidate code is never imported in this process. */
|
||||
import { execFile, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdtemp, readFile, realpath, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { promisify } from 'node:util';
|
||||
import {
|
||||
candidateExecutionSchema,
|
||||
candidateSandboxLimits,
|
||||
type CandidateExecution,
|
||||
} from '@stock-bot/stock-config/candidate-execution';
|
||||
import type { CanonicalRunRequest } from '@stock-bot/stock-config/canonical-research';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import { parseFinancialStrategyDecision } from '@stock-bot/types';
|
||||
import type { ReplaySubmissionOutcome } from '../contracts/native-replay';
|
||||
import {
|
||||
candidateResponseSchema,
|
||||
readCandidateFrames,
|
||||
writeCandidateFrame,
|
||||
type CandidateResponse,
|
||||
} from './candidate-protocol';
|
||||
import type {
|
||||
AsyncReplayController,
|
||||
DecisionContext,
|
||||
PublishedObservation,
|
||||
ReplayIdentity,
|
||||
} from './native-replay';
|
||||
|
||||
const runFile = promisify(execFile);
|
||||
const docker = '/usr/bin/docker';
|
||||
const daemon = ['--host', 'unix:///var/run/docker.sock'];
|
||||
const environment = (config: string) => ({ PATH: '/usr/bin:/bin', DOCKER_CONFIG: config });
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.resolve('@stock-bot/engine'))), '../../..');
|
||||
export const candidateDescriptorPath = resolve(
|
||||
root,
|
||||
'apps/stock/orchestrator/dist/candidate-sandbox.json'
|
||||
);
|
||||
export class CandidateSandboxUnavailable extends Error {
|
||||
readonly code = 'candidate_sandbox_unavailable';
|
||||
}
|
||||
|
||||
async function dockerRead(args: string[]) {
|
||||
const config = await mkdtemp(join(tmpdir(), 'stock-bot-docker-client-'));
|
||||
try {
|
||||
return (
|
||||
await runFile(docker, [...daemon, ...args], {
|
||||
env: environment(config),
|
||||
timeout: 10000,
|
||||
maxBuffer: 65536,
|
||||
})
|
||||
).stdout.trim();
|
||||
} finally {
|
||||
await rm(config, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
export async function readCandidateExecution(): Promise<CandidateExecution> {
|
||||
try {
|
||||
if (process.platform !== 'linux' || process.arch !== 'x64') {
|
||||
throw new Error('Unsupported candidate platform');
|
||||
}
|
||||
const execution = candidateExecutionSchema.parse(
|
||||
JSON.parse(await readFile(candidateDescriptorPath, 'utf8'))
|
||||
);
|
||||
const files = [
|
||||
resolve(root, 'apps/stock/orchestrator/dist/candidate-host.js'),
|
||||
resolve(root, 'apps/stock/orchestrator/dist/candidate-guardian'),
|
||||
await realpath(process.execPath),
|
||||
];
|
||||
const hashes = await Promise.all(
|
||||
files.map(async path =>
|
||||
createHash('sha256')
|
||||
.update(await readFile(path))
|
||||
.digest('hex')
|
||||
)
|
||||
);
|
||||
if (
|
||||
hashes[0] !== execution.profile.hostSha256 ||
|
||||
hashes[1] !== execution.profile.guardianSha256 ||
|
||||
hashes[2] !== execution.profile.bunSha256
|
||||
) {
|
||||
throw new Error('Candidate installed host/runtime bytes differ');
|
||||
}
|
||||
const info = JSON.parse(await dockerRead(['info', '--format', '{{json .}}'])) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
if (
|
||||
info.OSType !== 'linux' ||
|
||||
info.CgroupVersion !== '2' ||
|
||||
info.MemoryLimit !== true ||
|
||||
info.SwapLimit !== true ||
|
||||
info.CpuCfsQuota !== true ||
|
||||
info.PidsLimit !== true ||
|
||||
!Array.isArray(info.SecurityOptions) ||
|
||||
!info.SecurityOptions.some(v => String(v).startsWith('name=seccomp')) ||
|
||||
!info.SecurityOptions.some(v => String(v).startsWith('name=apparmor'))
|
||||
) {
|
||||
throw new Error('Candidate cgroup/seccomp/AppArmor isolation is unavailable');
|
||||
}
|
||||
if (
|
||||
(await dockerRead(['image', 'inspect', execution.imageId, '--format', '{{.Id}}'])) !==
|
||||
execution.imageId
|
||||
) {
|
||||
throw new Error('Candidate exact image is unavailable');
|
||||
}
|
||||
return execution;
|
||||
} catch (cause) {
|
||||
throw new CandidateSandboxUnavailable('The exact isolated candidate runtime is unavailable', {
|
||||
cause,
|
||||
});
|
||||
}
|
||||
}
|
||||
export async function verifyCandidateExecution(expected: CandidateExecution): Promise<void> {
|
||||
if (
|
||||
canonicalStrategyJson(await readCandidateExecution()) !==
|
||||
canonicalStrategyJson(candidateExecutionSchema.parse(expected))
|
||||
) {
|
||||
throw new CandidateSandboxUnavailable(
|
||||
'The retained isolated candidate runtime is not installed'
|
||||
);
|
||||
}
|
||||
}
|
||||
export function validateCandidateContainerName(value: string): string {
|
||||
if (!/^stock-bot-candidate-[0-9a-f-]{36}$/.test(value)) {
|
||||
throw new Error('Invalid owned candidate container name');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
/** Removal is exact-name only; never touches other research or operator containers. */
|
||||
export async function removeCandidateContainer(name: string): Promise<void> {
|
||||
validateCandidateContainerName(name);
|
||||
try {
|
||||
await dockerRead(['rm', '--force', name]);
|
||||
} catch (cause) {
|
||||
// A successful --rm exit races explicit cancellation cleanup. Confirm absence.
|
||||
if ((await dockerRead(['ps', '--all', '--quiet', '--filter', `name=^/${name}$`])) !== '') {
|
||||
throw cause;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class IsolatedCandidateController implements AsyncReplayController {
|
||||
private readonly child: ChildProcessWithoutNullStreams;
|
||||
private readonly closed: Promise<{ code: number | null; signal: NodeJS.Signals | null }>;
|
||||
private failure: Error | undefined;
|
||||
private pending:
|
||||
| {
|
||||
sequence: number;
|
||||
type: CandidateResponse['type'];
|
||||
resolve(value: CandidateResponse): void;
|
||||
reject(error: Error): void;
|
||||
}
|
||||
| undefined;
|
||||
private sequence = 0;
|
||||
private decisionSequence = 0;
|
||||
private stderr = Buffer.alloc(0);
|
||||
private readonly timer: ReturnType<typeof setTimeout>;
|
||||
private disposed = false;
|
||||
private expectedExit = false;
|
||||
private hasClosed = false;
|
||||
private readonly identity: ReplayIdentity | undefined;
|
||||
private constructor(
|
||||
private readonly request: CandidateRequest | null,
|
||||
private readonly name: string,
|
||||
deadlineAt: number,
|
||||
private readonly dockerConfig: string,
|
||||
execution: CandidateExecution
|
||||
) {
|
||||
this.identity = request
|
||||
? { version: 1, sessionId: request.runId, datasetHash: request.datasetHash }
|
||||
: undefined;
|
||||
const limits = candidateSandboxLimits;
|
||||
this.child = spawn(
|
||||
docker,
|
||||
[
|
||||
...daemon,
|
||||
'run',
|
||||
'--rm',
|
||||
'--interactive',
|
||||
'--pull=never',
|
||||
'--name',
|
||||
name,
|
||||
'--network',
|
||||
'none',
|
||||
'--ipc',
|
||||
'none',
|
||||
'--read-only',
|
||||
'--tmpfs',
|
||||
`/tmp:rw,nosuid,nodev,noexec,size=${limits.tmpBytes}`,
|
||||
'--memory',
|
||||
String(limits.memoryBytes),
|
||||
'--memory-swap',
|
||||
String(limits.memoryBytes),
|
||||
'--cpus',
|
||||
String(limits.cpuQuota),
|
||||
'--pids-limit',
|
||||
String(limits.pids),
|
||||
'--cap-drop',
|
||||
'ALL',
|
||||
'--cap-add',
|
||||
'SETUID',
|
||||
'--cap-add',
|
||||
'SETGID',
|
||||
'--cap-add',
|
||||
'KILL',
|
||||
'--security-opt',
|
||||
'no-new-privileges=true',
|
||||
'--log-driver',
|
||||
'none',
|
||||
execution.imageId,
|
||||
String(deadlineAt),
|
||||
],
|
||||
{ env: environment(dockerConfig), stdio: ['pipe', 'pipe', 'pipe'] }
|
||||
);
|
||||
this.child.stdin.on('error', cause => this.fail(cause));
|
||||
this.child.stderr.on('data', (chunk: Buffer) => {
|
||||
this.stderr = Buffer.concat([this.stderr, chunk]).subarray(-limits.stderrBytes);
|
||||
});
|
||||
this.closed = new Promise(resolveClosed => {
|
||||
this.child.once('error', cause => this.fail(cause));
|
||||
this.child.once('close', (code, signal) => {
|
||||
this.hasClosed = true;
|
||||
if (!this.disposed && (!this.expectedExit || this.pending)) {
|
||||
this.fail(
|
||||
new Error(`Candidate host exited before completion (code ${code}, signal ${signal})`)
|
||||
);
|
||||
}
|
||||
resolveClosed({ code, signal });
|
||||
});
|
||||
});
|
||||
this.timer = setTimeout(
|
||||
() => this.fail(new Error('Candidate host exceeded its wall deadline')),
|
||||
Math.max(1, deadlineAt - Date.now())
|
||||
);
|
||||
void this.readResponses();
|
||||
}
|
||||
static async start(
|
||||
request: CanonicalRunRequest,
|
||||
name: string,
|
||||
suppliedDeadline?: number
|
||||
): Promise<IsolatedCandidateController> {
|
||||
if (request.strategy.origin !== 'candidate') {
|
||||
throw new Error('Only candidates may use the isolated controller');
|
||||
}
|
||||
validateCandidateContainerName(name);
|
||||
await verifyCandidateExecution(request.strategy.execution);
|
||||
const deadlineAt = Math.min(
|
||||
Date.now() + candidateSandboxLimits.wallMs,
|
||||
suppliedDeadline ?? Infinity
|
||||
);
|
||||
if (!Number.isSafeInteger(deadlineAt) || deadlineAt <= Date.now()) {
|
||||
throw new Error('Candidate execution deadline is expired or invalid');
|
||||
}
|
||||
const config = await mkdtemp(join(tmpdir(), 'stock-bot-docker-client-'));
|
||||
const controller = new IsolatedCandidateController(
|
||||
request as CandidateRequest,
|
||||
name,
|
||||
deadlineAt,
|
||||
config,
|
||||
request.strategy.execution
|
||||
);
|
||||
try {
|
||||
await controller.exchange('ready', {
|
||||
type: 'init',
|
||||
identity: controller.identity,
|
||||
package: request.strategy.package,
|
||||
selection: request.strategy.selection,
|
||||
});
|
||||
return controller;
|
||||
} catch (cause) {
|
||||
try {
|
||||
await controller.dispose();
|
||||
} catch (cleanup) {
|
||||
throw new AggregateError([cause, cleanup], 'Candidate initialization and cleanup failed');
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
}
|
||||
static async transpile(
|
||||
source: string,
|
||||
name: string
|
||||
): Promise<{ content: string; runtimeVersion: string; execution: CandidateExecution }> {
|
||||
validateCandidateContainerName(name);
|
||||
const execution = await readCandidateExecution();
|
||||
const config = await mkdtemp(join(tmpdir(), 'stock-bot-docker-client-'));
|
||||
const controller = new IsolatedCandidateController(
|
||||
null,
|
||||
name,
|
||||
Date.now() + candidateSandboxLimits.wallMs,
|
||||
config,
|
||||
execution
|
||||
);
|
||||
try {
|
||||
const response = await controller.exchange('transpiled', { type: 'transpile', source });
|
||||
const status = await controller.closed;
|
||||
if (response.type !== 'transpiled' || controller.failure || status.code !== 0) {
|
||||
throw controller.failure ?? new Error('Candidate packaging failed');
|
||||
}
|
||||
return { content: response.content, runtimeVersion: response.runtimeVersion, execution };
|
||||
} finally {
|
||||
await controller.dispose();
|
||||
}
|
||||
}
|
||||
private fail(error: Error) {
|
||||
this.failure ??= error;
|
||||
const pending = this.pending;
|
||||
this.pending = undefined;
|
||||
pending?.reject(this.failure);
|
||||
this.child.stdin.destroy();
|
||||
}
|
||||
private async readResponses() {
|
||||
try {
|
||||
for await (const raw of readCandidateFrames(this.child.stdout)) {
|
||||
const response = candidateResponseSchema.parse(raw);
|
||||
const pending = this.pending;
|
||||
if (
|
||||
!pending ||
|
||||
response.sequence !== pending.sequence ||
|
||||
(response.type !== pending.type && response.type !== 'error')
|
||||
) {
|
||||
throw new Error('Unsolicited or mismatched candidate response');
|
||||
}
|
||||
if (response.type === 'error') {
|
||||
throw new Error(`Candidate strategy failed: ${response.message}`);
|
||||
}
|
||||
if (response.type === 'finished' || response.type === 'transpiled') {
|
||||
this.expectedExit = true;
|
||||
}
|
||||
this.pending = undefined;
|
||||
pending.resolve(response);
|
||||
}
|
||||
if (!this.disposed && !this.expectedExit) {
|
||||
this.fail(new Error('Candidate protocol closed before completion'));
|
||||
}
|
||||
} catch (cause) {
|
||||
this.fail(cause instanceof Error ? cause : new Error(String(cause)));
|
||||
}
|
||||
}
|
||||
private async exchange(
|
||||
type: CandidateResponse['type'],
|
||||
message: Record<string, unknown>
|
||||
): Promise<CandidateResponse> {
|
||||
if (this.failure) {
|
||||
throw this.failure;
|
||||
}
|
||||
if (this.pending || this.disposed || this.hasClosed || this.expectedExit) {
|
||||
throw new Error('Candidate controller is unavailable or busy');
|
||||
}
|
||||
const sequence = this.sequence++;
|
||||
const response = new Promise<CandidateResponse>((resolveResponse, reject) => {
|
||||
this.pending = { sequence, type, resolve: resolveResponse, reject };
|
||||
});
|
||||
void response.catch(() => undefined);
|
||||
try {
|
||||
await writeCandidateFrame(this.child.stdin, { version: 1, sequence, ...message });
|
||||
} catch (cause) {
|
||||
this.fail(cause instanceof Error ? cause : new Error(String(cause)));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
async stage(context: DecisionContext, observations: readonly PublishedObservation[]) {
|
||||
const response = await this.exchange('decisions', {
|
||||
type: 'stage',
|
||||
published: { identity: this.identity, step: context, observations },
|
||||
});
|
||||
if (response.type !== 'decisions') {
|
||||
throw new Error('Expected candidate decisions');
|
||||
}
|
||||
const decision = parseFinancialStrategyDecision(response.decisions[0]);
|
||||
if (!this.request || !this.identity) {
|
||||
throw new Error('Packaging host cannot make decisions');
|
||||
}
|
||||
const selected = this.request.strategy.selection;
|
||||
const expectedId = JSON.stringify([
|
||||
'strategy',
|
||||
selected.ownerId,
|
||||
selected.strategyId,
|
||||
selected.strategyVersion,
|
||||
this.decisionSequence,
|
||||
]);
|
||||
if (
|
||||
context.barrier.owner_ids.length !== 1 ||
|
||||
context.barrier.owner_ids[0] !== selected.ownerId ||
|
||||
decision.sessionId !== this.identity.sessionId ||
|
||||
decision.barrierId !== context.barrier.barrier_id ||
|
||||
decision.revision !== context.barrier.revision ||
|
||||
decision.decision.ownerId !== selected.ownerId ||
|
||||
decision.decision.sequence !== this.decisionSequence ||
|
||||
decision.decision.decisionId !== expectedId ||
|
||||
decision.intent.mode !== 'target'
|
||||
) {
|
||||
throw new Error('Candidate returned a forged decision identity or mode');
|
||||
}
|
||||
return [decision];
|
||||
}
|
||||
async committed(outcome: ReplaySubmissionOutcome): Promise<void> {
|
||||
if (!this.identity) {
|
||||
throw new Error('Packaging host cannot accept financial acknowledgements');
|
||||
}
|
||||
await this.exchange('ack', {
|
||||
type: 'committed',
|
||||
admitted: { identity: this.identity, outcome },
|
||||
});
|
||||
this.decisionSequence++;
|
||||
}
|
||||
async finish(): Promise<void> {
|
||||
await this.exchange('finished', { type: 'finish' });
|
||||
const status = await this.closed;
|
||||
if (this.failure || status.code !== 0) {
|
||||
throw this.failure ?? new Error(`Candidate host did not exit successfully: ${this.stderr}`);
|
||||
}
|
||||
}
|
||||
async dispose(): Promise<void> {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
this.disposed = true;
|
||||
if (this.pending) {
|
||||
this.fail(new Error('Candidate controller disposed before acknowledgement'));
|
||||
}
|
||||
clearTimeout(this.timer);
|
||||
this.child.stdin.destroy();
|
||||
const errors: unknown[] = [];
|
||||
// Always attempt every cleanup stage, including when the daemon is unavailable.
|
||||
// The independent guardian still enforces its frozen wall deadline in that case.
|
||||
try {
|
||||
await removeCandidateContainer(this.name);
|
||||
} catch (error) {
|
||||
errors.push(error);
|
||||
}
|
||||
if (!this.hasClosed) {
|
||||
this.child.kill('SIGKILL');
|
||||
}
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
await Promise.race([
|
||||
this.closed,
|
||||
new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(
|
||||
() => reject(new Error('Candidate Docker client did not close during cleanup')),
|
||||
10000
|
||||
);
|
||||
}),
|
||||
]);
|
||||
} catch (error) {
|
||||
errors.push(error);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
try {
|
||||
await rm(this.dockerConfig, { recursive: true, force: true });
|
||||
} catch (error) {
|
||||
errors.push(error);
|
||||
}
|
||||
if (errors.length) {
|
||||
throw new AggregateError(
|
||||
this.failure ? [this.failure, ...errors] : errors,
|
||||
'Candidate cleanup failed'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
type CandidateRequest = CanonicalRunRequest & {
|
||||
strategy: Extract<CanonicalRunRequest['strategy'], { origin: 'candidate' }>;
|
||||
};
|
||||
|
|
@ -17,7 +17,8 @@ export interface BacktestExecutionEngine extends Pick<EventEmitter, 'on' | 'off'
|
|||
): Promise<BacktestResult | NativeBacktestResult>;
|
||||
runCanonical?(
|
||||
request: CanonicalRunRequest,
|
||||
resolveDataset: (signal: AbortSignal) => Promise<HistoricalDatasetV2>
|
||||
resolveDataset: (signal: AbortSignal) => Promise<HistoricalDatasetV2>,
|
||||
controls?: { executionDeadlineAt?: number }
|
||||
): Promise<Pick<CanonicalRunResult, 'financial' | 'analytics'>>;
|
||||
stopBacktest(): Promise<void>;
|
||||
pauseBacktest(): Promise<void>;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,8 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
candidateExecutionSchema,
|
||||
type CandidateExecution,
|
||||
} from '@stock-bot/stock-config/candidate-execution';
|
||||
import {
|
||||
canonicalBuildIdentitySchema,
|
||||
canonicalRunRequestSchema,
|
||||
|
|
@ -19,6 +23,11 @@ export const retainedStrategyRequestSchema = z
|
|||
type: z.literal('runRetainedStrategy'),
|
||||
request: canonicalRunRequestSchema,
|
||||
dataset: z.unknown(),
|
||||
executionDeadlineAt: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
|
||||
candidateContainerName: z
|
||||
.string()
|
||||
.regex(/^stock-bot-candidate-[0-9a-f-]{36}$/)
|
||||
.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
|
|
@ -33,6 +42,7 @@ export interface RetainedStrategyResult {
|
|||
version: 1;
|
||||
build: CanonicalBuildIdentity;
|
||||
artifactHash: string;
|
||||
execution?: CandidateExecution;
|
||||
financial: ReplayReportResult;
|
||||
analytics: CanonicalBacktestAnalytics;
|
||||
}
|
||||
|
|
@ -43,6 +53,7 @@ const retainedStrategyResultSchema = z
|
|||
version: z.literal(1),
|
||||
build: canonicalBuildIdentitySchema,
|
||||
artifactHash: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
execution: candidateExecutionSchema.optional(),
|
||||
financial: z.unknown(),
|
||||
analytics: z.unknown(),
|
||||
})
|
||||
|
|
@ -60,6 +71,14 @@ export function parseRetainedStrategyResult(
|
|||
) {
|
||||
throw new Error('Retained strategy result build/artifact identity mismatch');
|
||||
}
|
||||
if (
|
||||
request.strategy.origin === 'candidate'
|
||||
? canonicalStrategyJson(envelope.execution) !==
|
||||
canonicalStrategyJson(request.strategy.execution)
|
||||
: envelope.execution !== undefined
|
||||
) {
|
||||
throw new Error('Retained strategy result execution identity mismatch');
|
||||
}
|
||||
const financial = parseCanonicalFinancialResult(envelope.financial, request);
|
||||
const analytics = buildCanonicalBacktestReport(financial, request.analyticsPolicy).analytics;
|
||||
if (canonicalStrategyJson(envelope.analytics) !== canonicalStrategyJson(analytics)) {
|
||||
|
|
|
|||
|
|
@ -1,14 +1,21 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import type { StrategyProgram } from '../contracts/canonical-strategy';
|
||||
import type { StrategyReplayResult } from '../contracts/strategy-replay';
|
||||
import {
|
||||
createBuiltinStrategy,
|
||||
validateBuiltinStrategyBindings,
|
||||
} from '../strategies/canonical-builtins';
|
||||
import { freeze } from '../strategies/strategy-decision';
|
||||
import {
|
||||
importRetainedProgram,
|
||||
verifyRetainedProgramPackage,
|
||||
} from '../strategies/retained-program';
|
||||
import { IsolatedCandidateController } from './candidate-sandbox';
|
||||
import { verifyCanonicalWorkerBuild } from './canonical-build';
|
||||
import { buildCanonicalBacktestReport } from './canonical-result';
|
||||
import { executeReplayTrace, prepareReplayLoad } from './native-replay';
|
||||
import {
|
||||
executeReplayTrace,
|
||||
NativeReplaySession,
|
||||
prepareReplayLoad,
|
||||
runReplaySessionAsync,
|
||||
} from './native-replay';
|
||||
import {
|
||||
nativeWorkerRequestSchema,
|
||||
type NativeWorkerMessage,
|
||||
|
|
@ -34,17 +41,7 @@ process.once('message', async (input: unknown) => {
|
|||
const admitted = request.request;
|
||||
// Identity checks precede bundle import, including any top-level module side effects.
|
||||
const build = await verifyCanonicalWorkerBuild(admitted.build, import.meta.url);
|
||||
const pkg = admitted.strategy.package;
|
||||
const hash = (content: string) => createHash('sha256').update(content, 'utf8').digest('hex');
|
||||
if (
|
||||
hash(pkg.artifact.content) !== pkg.artifact.sha256 ||
|
||||
hash(pkg.dependencyLock.content) !== pkg.dependencyLock.sha256
|
||||
) {
|
||||
throw new Error('Retained strategy artifact or dependency lock hash mismatch');
|
||||
}
|
||||
if (pkg.program.apiVersion !== 'canonical-ts/v1') {
|
||||
throw new Error('Unsupported retained strategy API version');
|
||||
}
|
||||
const pkg = verifyRetainedProgramPackage(admitted.strategy.package);
|
||||
const load = prepareReplayLoad(request.dataset, admitted.policy);
|
||||
if (
|
||||
load.identity.datasetHash !== admitted.datasetHash ||
|
||||
|
|
@ -53,50 +50,48 @@ process.once('message', async (input: unknown) => {
|
|||
) {
|
||||
throw new Error('Retained strategy requires its exact eligible single-series dataset');
|
||||
}
|
||||
const selection = admitted.strategy.selection;
|
||||
validateBuiltinStrategyBindings([selection], load);
|
||||
// Only server-admitted built-ins reach this trusted worker path. Candidate
|
||||
// execution requires separate isolation; import is never performed by an API.
|
||||
// Bun's data-URL loader rejects real bundle-sized specifiers. A Blob keeps
|
||||
// these exact UTF-8 bytes in memory without temporary files surviving SIGKILL.
|
||||
const moduleUrl = URL.createObjectURL(
|
||||
new Blob([pkg.artifact.content], { type: 'text/javascript' })
|
||||
);
|
||||
let module: Record<string, unknown>;
|
||||
try {
|
||||
module = await import(moduleUrl);
|
||||
} finally {
|
||||
URL.revokeObjectURL(moduleUrl);
|
||||
}
|
||||
const factory = module[pkg.artifact.entryExport];
|
||||
if (typeof factory !== 'function') {
|
||||
throw new Error('Retained strategy factory export is missing');
|
||||
}
|
||||
const program = factory(freeze(structuredClone(selection))) as StrategyProgram;
|
||||
if (
|
||||
!program ||
|
||||
typeof program !== 'object' ||
|
||||
program.ownerId !== selection.ownerId ||
|
||||
program.strategyId !== selection.strategyId ||
|
||||
program.strategyVersion !== selection.strategyVersion ||
|
||||
program.seed !== selection.seed ||
|
||||
program.mode !== 'target' ||
|
||||
typeof program.decide !== 'function'
|
||||
) {
|
||||
throw new Error('Retained strategy factory identity or API mismatch');
|
||||
}
|
||||
await send({
|
||||
type: 'progress',
|
||||
progress: 0,
|
||||
message: 'Retained canonical strategy replay started',
|
||||
});
|
||||
const { result } = runStrategyReplay(load, [program], { resultFormat: 'report' });
|
||||
let result;
|
||||
if (admitted.strategy.origin === 'candidate') {
|
||||
if (!request.candidateContainerName) {
|
||||
throw new Error('Isolated candidate lacks its owned container identity');
|
||||
}
|
||||
const controller = await IsolatedCandidateController.start(
|
||||
admitted,
|
||||
request.candidateContainerName,
|
||||
request.executionDeadlineAt
|
||||
);
|
||||
try {
|
||||
result = (
|
||||
await runReplaySessionAsync(new NativeReplaySession(load), controller, {
|
||||
resultFormat: 'report',
|
||||
})
|
||||
).result;
|
||||
await controller.finish();
|
||||
} finally {
|
||||
await controller.dispose();
|
||||
}
|
||||
} else {
|
||||
validateBuiltinStrategyBindings([admitted.strategy.selection], load);
|
||||
const program = await importRetainedProgram(pkg, admitted.strategy.selection);
|
||||
result = runStrategyReplay(load, [program], { resultFormat: 'report' }).result;
|
||||
}
|
||||
if (!('format' in result) || result.format !== 'report') {
|
||||
throw new Error('Retained replay requires the canonical report format');
|
||||
}
|
||||
const report = buildCanonicalBacktestReport(result, admitted.analyticsPolicy);
|
||||
const envelope: RetainedStrategyResult = {
|
||||
type: 'retainedStrategyResult',
|
||||
version: 1,
|
||||
build,
|
||||
artifactHash: pkg.artifact.sha256,
|
||||
...(admitted.strategy.origin === 'candidate'
|
||||
? { execution: admitted.strategy.execution }
|
||||
: {}),
|
||||
financial: report.financial,
|
||||
analytics: report.analytics,
|
||||
};
|
||||
|
|
|
|||
218
apps/stock/orchestrator/src/backtest/sandbox/guardian.rs
Normal file
218
apps/stock/orchestrator/src/backtest/sandbox/guardian.rs
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
//! Minimal Linux x86_64 PID1. This executable contains no strategy/data logic.
|
||||
use std::{
|
||||
os::{fd::FromRawFd, unix::process::CommandExt},
|
||||
process::{Command, Stdio},
|
||||
sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
},
|
||||
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
#[repr(C)]
|
||||
struct Filter {
|
||||
code: u16,
|
||||
jt: u8,
|
||||
jf: u8,
|
||||
k: u32,
|
||||
}
|
||||
#[repr(C)]
|
||||
struct Program {
|
||||
len: u16,
|
||||
filter: *const Filter,
|
||||
}
|
||||
#[repr(C)]
|
||||
struct PollFd {
|
||||
fd: i32,
|
||||
events: i16,
|
||||
revents: i16,
|
||||
}
|
||||
#[repr(C)]
|
||||
struct Limit {
|
||||
current: u64,
|
||||
maximum: u64,
|
||||
}
|
||||
unsafe extern "C" {
|
||||
fn prctl(option: i32, ...) -> i32;
|
||||
fn setgid(gid: u32) -> i32;
|
||||
fn setuid(uid: u32) -> i32;
|
||||
fn setgroups(size: usize, list: *const u32) -> i32;
|
||||
fn setrlimit(resource: i32, limit: *const Limit) -> i32;
|
||||
fn poll(fds: *mut PollFd, nfds: usize, timeout: i32) -> i32;
|
||||
fn kill(pid: i32, signal: i32) -> i32;
|
||||
}
|
||||
fn stmt(code: u16, k: u32) -> Filter {
|
||||
Filter {
|
||||
code,
|
||||
jt: 0,
|
||||
jf: 0,
|
||||
k,
|
||||
}
|
||||
}
|
||||
fn equal(k: u32, jt: u8, jf: u8) -> Filter {
|
||||
Filter {
|
||||
code: 0x15,
|
||||
jt,
|
||||
jf,
|
||||
k,
|
||||
}
|
||||
}
|
||||
fn error() -> std::io::Error {
|
||||
std::io::Error::last_os_error()
|
||||
}
|
||||
fn main() {
|
||||
if !cfg!(all(target_os = "linux", target_arch = "x86_64")) {
|
||||
std::process::exit(126);
|
||||
}
|
||||
let deadline: u128 = std::env::args()
|
||||
.nth(1)
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0);
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.expect("system clock")
|
||||
.as_millis();
|
||||
if deadline <= now || deadline - now > 300_000 {
|
||||
std::process::exit(124);
|
||||
}
|
||||
let remaining = Duration::from_millis((deadline - now) as u64);
|
||||
let clock = Instant::now();
|
||||
let mut command = Command::new("/usr/bin/bun");
|
||||
command
|
||||
.arg("/app/candidate-host.js")
|
||||
.current_dir("/tmp")
|
||||
.env_clear()
|
||||
.stdin(Stdio::inherit())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit());
|
||||
unsafe {
|
||||
command.pre_exec(|| {
|
||||
if setgroups(0, std::ptr::null()) != 0 || setgid(65534) != 0 || setuid(65534) != 0 {
|
||||
return Err(error());
|
||||
}
|
||||
if setrlimit(
|
||||
0,
|
||||
&Limit {
|
||||
current: 300,
|
||||
maximum: 300,
|
||||
},
|
||||
) != 0
|
||||
|| setrlimit(
|
||||
4,
|
||||
&Limit {
|
||||
current: 0,
|
||||
maximum: 0,
|
||||
},
|
||||
) != 0
|
||||
{
|
||||
return Err(error());
|
||||
}
|
||||
if prctl(38, 1, 0, 0, 0) != 0 {
|
||||
return Err(error());
|
||||
}
|
||||
// Check architecture and reject x32 syscall-number aliases before any allow rule.
|
||||
let mut filter = vec![
|
||||
stmt(0x20, 4),
|
||||
equal(0xc000003e, 1, 0),
|
||||
stmt(0x06, 0x80000000),
|
||||
stmt(0x20, 0),
|
||||
Filter {
|
||||
code: 0x35,
|
||||
jt: 0,
|
||||
jf: 1,
|
||||
k: 0x40000000,
|
||||
},
|
||||
stmt(0x06, 0x00050001),
|
||||
];
|
||||
// fork, vfork, socket, ptrace, mount, umount2, unshare, setns, bpf, perf_event_open.
|
||||
for nr in [57, 58, 41, 101, 165, 166, 272, 308, 321, 298] {
|
||||
filter.push(equal(nr, 0, 1));
|
||||
filter.push(stmt(0x06, 0x00050001));
|
||||
}
|
||||
// clone3 cannot inspect the pointed-to flags; make libc use checked clone instead.
|
||||
filter.push(equal(435, 0, 1));
|
||||
filter.push(stmt(0x06, 0x00050026));
|
||||
filter.push(equal(56, 0, 4));
|
||||
filter.push(stmt(0x20, 16));
|
||||
filter.push(Filter {
|
||||
code: 0x45,
|
||||
jt: 0,
|
||||
jf: 1,
|
||||
k: 0x00010000,
|
||||
});
|
||||
filter.push(stmt(0x06, 0x7fff0000));
|
||||
filter.push(stmt(0x06, 0x00050001));
|
||||
filter.push(stmt(0x06, 0x7fff0000));
|
||||
let program = Program {
|
||||
len: filter.len() as u16,
|
||||
filter: filter.as_ptr(),
|
||||
};
|
||||
if prctl(22, 2, &program as *const Program) != 0 {
|
||||
return Err(error());
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.expect("restricted host initialization failed");
|
||||
let mut output = child.stdout.take().expect("restricted host stdout missing");
|
||||
let output_closed = Arc::new(AtomicBool::new(false));
|
||||
let relay_closed = Arc::clone(&output_closed);
|
||||
// A bounded std::io::copy buffer relays bytes only. A separate watchdog remains
|
||||
// responsive even if the child floods stdout or the consumer stops reading.
|
||||
// Direct File writes avoid line-buffering the binary protocol.
|
||||
std::thread::spawn(move || {
|
||||
let mut destination = unsafe { std::fs::File::from_raw_fd(1) };
|
||||
let _ = std::io::copy(&mut output, &mut destination);
|
||||
relay_closed.store(true, Ordering::Release);
|
||||
});
|
||||
let mut exit_status = None;
|
||||
let mut stdout_closed_at = None;
|
||||
loop {
|
||||
if exit_status.is_none() {
|
||||
if let Some(status) = child.try_wait().expect("restricted host wait failed") {
|
||||
exit_status = Some(status.code().unwrap_or(125));
|
||||
}
|
||||
}
|
||||
if output_closed.load(Ordering::Acquire) {
|
||||
if let Some(code) = exit_status {
|
||||
// Drain the complete final frame before ending a normal finish/transpile.
|
||||
std::process::exit(code);
|
||||
}
|
||||
stdout_closed_at.get_or_insert_with(Instant::now);
|
||||
}
|
||||
// EOF can precede the child's normal exit by a few scheduler turns.
|
||||
let protocol_closed =
|
||||
stdout_closed_at.is_some_and(|at| at.elapsed() >= Duration::from_millis(100));
|
||||
let mut input = PollFd {
|
||||
fd: 0,
|
||||
events: 0,
|
||||
revents: 0,
|
||||
};
|
||||
let ready = unsafe { poll(&mut input, 1, 0) };
|
||||
let disconnected = ready < 0 || input.revents & (0x10 | 0x08 | 0x20) != 0;
|
||||
if disconnected || protocol_closed || clock.elapsed() >= remaining {
|
||||
unsafe {
|
||||
kill(child.id() as i32, 9);
|
||||
}
|
||||
let _ = child.wait();
|
||||
eprintln!(
|
||||
"Candidate host {}",
|
||||
if disconnected {
|
||||
"supervisor disconnected"
|
||||
} else if protocol_closed {
|
||||
"protocol stdout closed"
|
||||
} else {
|
||||
"wall deadline exceeded"
|
||||
}
|
||||
);
|
||||
// Exiting namespace PID1 kills remaining threads/processes independently of JS.
|
||||
std::process::exit(if disconnected || protocol_closed {
|
||||
125
|
||||
} else {
|
||||
124
|
||||
});
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
import { asValue, type AwilixContainer } from 'awilix';
|
||||
import { z } from 'zod';
|
||||
import type { ServiceCradle as ServiceDefinitions } from '@stock-bot/di';
|
||||
import { BacktestRunner } from './backtest/BacktestRunner';
|
||||
import { PostgresBacktestRunRepository } from './backtest/PostgresBacktestRunRepository';
|
||||
|
|
@ -10,6 +11,7 @@ import { PostgresCanonicalExecutionRepository } from './execution/PostgresCanoni
|
|||
import { BacktestHandler } from './handlers/backtest/backtest.handler';
|
||||
import { CanonicalPaperRuntime } from './paper/CanonicalPaperRuntime';
|
||||
import { validatePaperConfiguration } from './paper/feed';
|
||||
import { PaperDeploymentHost } from './paper/PaperDeploymentHost';
|
||||
import { AnalyticsService } from './services/AnalyticsService';
|
||||
import { StorageService } from './services/StorageService';
|
||||
import { createBuiltinStrategy } from './strategies/canonical-builtins';
|
||||
|
|
@ -29,6 +31,45 @@ export function assertSupportedComposition(role: OrchestratorRole, useRustEngine
|
|||
}
|
||||
}
|
||||
|
||||
/** Validate before opening resources as well as before registering runtime services. */
|
||||
export function resolvePaperComposition(
|
||||
role: OrchestratorRole,
|
||||
canonicalInput?: PaperConfigurationInput,
|
||||
deploymentInput?: unknown
|
||||
) {
|
||||
if ((canonicalInput !== undefined || deploymentInput !== undefined) && role !== 'paper') {
|
||||
throw new Error('Canonical paper configuration requires a paper composition');
|
||||
}
|
||||
if (canonicalInput !== undefined && deploymentInput !== undefined) {
|
||||
throw new Error('Choose canonicalPaper or paperDeploymentHost, never two account owners');
|
||||
}
|
||||
const canonicalPaper =
|
||||
canonicalInput === undefined ? undefined : validatePaperConfiguration(canonicalInput);
|
||||
if (canonicalPaper && canonicalPaper.version !== 1) {
|
||||
throw new Error('Promoted paper strategies require an explicitly reviewed deployment host');
|
||||
}
|
||||
const paperDeploymentHost =
|
||||
deploymentInput === undefined
|
||||
? undefined
|
||||
: z
|
||||
.object({
|
||||
enabled: z.literal(true),
|
||||
deploymentId: z
|
||||
.string()
|
||||
.uuid()
|
||||
.transform(id => id.toLowerCase())
|
||||
.optional(),
|
||||
})
|
||||
.strict()
|
||||
.parse(deploymentInput);
|
||||
if (role === 'paper' && !canonicalPaper && !paperDeploymentHost) {
|
||||
throw new Error(
|
||||
'Paper composition requires explicit canonicalPaper or paperDeploymentHost configuration; accounts are never migrated automatically'
|
||||
);
|
||||
}
|
||||
return { canonicalPaper, paperDeploymentHost };
|
||||
}
|
||||
|
||||
/**
|
||||
* Register orchestrator-specific services in the DI container
|
||||
*/
|
||||
|
|
@ -43,6 +84,7 @@ export async function registerOrchestratorServices(
|
|||
nativeExecutionTimeoutMs?: number;
|
||||
maxConcurrent?: number;
|
||||
canonicalPaper?: PaperConfigurationInput;
|
||||
paperDeploymentHost?: { enabled: true; deploymentId?: string };
|
||||
} = {}
|
||||
): Promise<void> {
|
||||
const role = options.role === undefined ? 'research-only' : options.role;
|
||||
|
|
@ -50,18 +92,11 @@ export async function registerOrchestratorServices(
|
|||
assertSupportedComposition(role, useRustEngine);
|
||||
const maxConcurrent = options.maxConcurrent === undefined ? 1 : options.maxConcurrent;
|
||||
assertResearchConcurrency(maxConcurrent);
|
||||
if (options.canonicalPaper !== undefined && role !== 'paper') {
|
||||
throw new Error('Canonical paper configuration requires a paper composition');
|
||||
}
|
||||
const canonicalPaper =
|
||||
options.canonicalPaper === undefined
|
||||
? undefined
|
||||
: validatePaperConfiguration(options.canonicalPaper);
|
||||
if (role === 'paper' && !canonicalPaper) {
|
||||
throw new Error(
|
||||
'Paper composition requires explicit canonicalPaper configuration; accounts are never migrated automatically'
|
||||
);
|
||||
}
|
||||
const { canonicalPaper, paperDeploymentHost } = resolvePaperComposition(
|
||||
role,
|
||||
options.canonicalPaper,
|
||||
options.paperDeploymentHost
|
||||
);
|
||||
|
||||
// Create a service adapter that provides the expected interface
|
||||
const services = container.resolve('serviceContainer') as IServiceContainer;
|
||||
|
|
@ -72,6 +107,7 @@ export async function registerOrchestratorServices(
|
|||
if (
|
||||
[
|
||||
'CanonicalPaperRuntime',
|
||||
'PaperDeploymentHost',
|
||||
'ModeManager',
|
||||
'ExecutionService',
|
||||
'MarketDataService',
|
||||
|
|
@ -93,7 +129,7 @@ export async function registerOrchestratorServices(
|
|||
options
|
||||
);
|
||||
|
||||
if (canonicalPaper && !services.postgres) {
|
||||
if ((canonicalPaper || paperDeploymentHost) && !services.postgres) {
|
||||
throw new Error('Canonical paper requires durable PostgreSQL custody');
|
||||
}
|
||||
const paper =
|
||||
|
|
@ -103,6 +139,13 @@ export async function registerOrchestratorServices(
|
|||
programs: canonicalPaper.strategies.map(createBuiltinStrategy),
|
||||
})
|
||||
: undefined;
|
||||
const deploymentHost =
|
||||
paperDeploymentHost && services.postgres
|
||||
? new PaperDeploymentHost({
|
||||
database: services.postgres,
|
||||
repository: new PostgresCanonicalExecutionRepository(services.postgres),
|
||||
})
|
||||
: undefined;
|
||||
const runner = new ResearchBacktestPool({
|
||||
runners: Array.from(
|
||||
{ length: maxConcurrent },
|
||||
|
|
@ -129,12 +172,14 @@ export async function registerOrchestratorServices(
|
|||
AnalyticsService: analytics,
|
||||
BacktestRunner: runner,
|
||||
...(paper ? { CanonicalPaperRuntime: paper } : {}),
|
||||
...(deploymentHost ? { PaperDeploymentHost: deploymentHost } : {}),
|
||||
});
|
||||
const canonicalContainer = container as AwilixContainer<
|
||||
ServiceDefinitions & {
|
||||
StorageService: StorageService;
|
||||
AnalyticsService: AnalyticsService;
|
||||
CanonicalPaperRuntime: PaperRuntime;
|
||||
PaperDeploymentHost: PaperDeploymentHost;
|
||||
BacktestRunner: ResearchBacktestPool;
|
||||
orchestratorServices: IServiceContainer;
|
||||
}
|
||||
|
|
@ -145,6 +190,7 @@ export async function registerOrchestratorServices(
|
|||
BacktestRunner: asValue(runner),
|
||||
orchestratorServices: asValue(services),
|
||||
...(paper ? { CanonicalPaperRuntime: asValue(paper) } : {}),
|
||||
...(deploymentHost ? { PaperDeploymentHost: asValue(deploymentHost) } : {}),
|
||||
});
|
||||
container
|
||||
.resolve('handlerScanner')
|
||||
|
|
@ -153,10 +199,14 @@ export async function registerOrchestratorServices(
|
|||
if (paper && canonicalPaper && options.initializeMode !== false) {
|
||||
await paper.initialize(canonicalPaper);
|
||||
}
|
||||
if (deploymentHost && paperDeploymentHost?.deploymentId && options.initializeMode !== false) {
|
||||
await deploymentHost.bind(paperDeploymentHost.deploymentId);
|
||||
}
|
||||
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: maxConcurrent });
|
||||
} catch (error) {
|
||||
await runner.shutdown().catch(() => {});
|
||||
await paper?.shutdown().catch(() => {});
|
||||
await deploymentHost?.shutdown().catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,54 +1,22 @@
|
|||
/** Explicit trusted producer boundary. No legacy timestamp repair or broker capabilities. */
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
deployedPaperConfigurationSchema,
|
||||
paperPolicySchema,
|
||||
} from '@stock-bot/stock-config/paper-deployments';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import { builtinStrategySelectionSchema } from './builtin-strategy';
|
||||
import { canonicalMatchingConfigSchema, matchingCommandSchema } from './canonical-execution';
|
||||
import { replayConfigSchema, stepSchema } from './native-replay';
|
||||
import { stepSchema } from './native-replay';
|
||||
|
||||
const id = matchingCommandSchema.shape.key.shape.instrumentId;
|
||||
const time = matchingCommandSchema.shape.key.shape.at;
|
||||
const counter = matchingCommandSchema.shape.key.shape.sourceSequence;
|
||||
const duration = counter.refine(value => value > 0, 'Duration must be positive');
|
||||
const decimal = z.string().transform(value => parseFinancialDecimal(value));
|
||||
|
||||
export const paperPolicySchema = z
|
||||
.object({
|
||||
version: z.literal(1),
|
||||
sourceId: id,
|
||||
priceBasis: z.literal('raw'),
|
||||
maxFeedAgeMs: duration,
|
||||
observations: z.array(
|
||||
z
|
||||
.object({
|
||||
seriesId: id,
|
||||
instrumentId: id,
|
||||
intervalMs: duration,
|
||||
staleAfterMs: counter,
|
||||
})
|
||||
.strict()
|
||||
),
|
||||
cadence: z.array(z.object({ ownerId: id, seriesIds: z.array(id).min(1) }).strict()),
|
||||
calendars: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
instrumentId: id,
|
||||
calendarId: id,
|
||||
revision: id,
|
||||
sessions: z
|
||||
.array(z.object({ sessionId: id, opensAt: time, closesAt: time }).strict())
|
||||
.min(1),
|
||||
})
|
||||
.strict()
|
||||
)
|
||||
.min(1),
|
||||
riskBoundaries: z.array(
|
||||
replayConfigSchema.shape.matching.shape.risk.shape.ledger.shape.riskSession
|
||||
),
|
||||
})
|
||||
.strict();
|
||||
export { paperPolicySchema } from '@stock-bot/stock-config/paper-deployments';
|
||||
|
||||
export const paperConfigurationSchema = z
|
||||
const legacyPaperConfigurationSchema = z
|
||||
.object({
|
||||
version: z.literal(1),
|
||||
matching: canonicalMatchingConfigSchema,
|
||||
|
|
@ -57,6 +25,11 @@ export const paperConfigurationSchema = z
|
|||
})
|
||||
.strict();
|
||||
|
||||
export const paperConfigurationSchema = z.union([
|
||||
legacyPaperConfigurationSchema,
|
||||
deployedPaperConfigurationSchema,
|
||||
]);
|
||||
|
||||
/** availableAt is the producer's atomic release time for the whole quote frame.
|
||||
* Quotes retain their original physical timestamp and source sequence. The
|
||||
* supplied completed bars were available by this release; quotes never synthesize bars. */
|
||||
|
|
|
|||
|
|
@ -98,12 +98,14 @@ export class PostgresCanonicalExecutionRepository implements CanonicalExecutionR
|
|||
config: account.checkpoint.config,
|
||||
definitions: account.definitions,
|
||||
hostConfiguration: account.host?.configuration ?? null,
|
||||
deployment: account.host?.deployment ?? null,
|
||||
}) !==
|
||||
canonicalJson({
|
||||
identity: expected.identity,
|
||||
config: expected.checkpoint.config,
|
||||
definitions: expected.definitions,
|
||||
hostConfiguration: expected.host?.configuration ?? null,
|
||||
deployment: expected.host?.deployment ?? null,
|
||||
})
|
||||
) {
|
||||
throw new ExecutionConflictError(
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
/** Durable custody contracts. Financial values and transitions belong to Rust. */
|
||||
import { z } from 'zod';
|
||||
import type { PostgresClient } from '@stock-bot/services';
|
||||
import { paperDeploymentBindingSchema } from '@stock-bot/stock-config/paper-deployments';
|
||||
import {
|
||||
canonicalExecutionCheckpointSchema,
|
||||
financialTransactionResultSchema,
|
||||
|
|
@ -29,6 +30,7 @@ export const canonicalPaperHostSchema = z
|
|||
.object({
|
||||
version: z.literal(1),
|
||||
configuration: paperConfigurationSchema,
|
||||
deployment: paperDeploymentBindingSchema.optional(),
|
||||
generation: z.string().min(1),
|
||||
active: z.boolean(),
|
||||
operatorHalted: z.boolean(),
|
||||
|
|
|
|||
|
|
@ -13,7 +13,11 @@ import { createContainer } from './simple-container';
|
|||
|
||||
// Initialize configuration with service-specific overrides
|
||||
const config = initializeStockConfig('orchestrator');
|
||||
const security = createHttpSecurity({ ...httpSecurityOptions(), environment: config.environment });
|
||||
const security = createHttpSecurity({
|
||||
...httpSecurityOptions(),
|
||||
environment: config.environment,
|
||||
browserSessions: true,
|
||||
});
|
||||
const logger = getLogger('orchestrator');
|
||||
|
||||
// Get service-specific config
|
||||
|
|
@ -71,7 +75,7 @@ async function main() {
|
|||
});
|
||||
|
||||
// Create and mount routes (without Socket.IO for now)
|
||||
const routes = createRoutes(services);
|
||||
const routes = createRoutes(services, undefined, security.allowedOrigins);
|
||||
app.route('/', routes);
|
||||
|
||||
// Start Bun server
|
||||
|
|
@ -153,6 +157,7 @@ async function main() {
|
|||
try {
|
||||
const failures: unknown[] = [];
|
||||
for (const close of [
|
||||
() => services.custom?.PaperDeploymentHost?.shutdown(),
|
||||
() => services.custom?.CanonicalPaperRuntime?.shutdown(),
|
||||
() => services.custom?.BacktestRunner?.shutdown(),
|
||||
() => services.queueManager?.shutdown(),
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import type { PaperDeploymentBinding } from '@stock-bot/stock-config/paper-deployments';
|
||||
import type { StrategyProgram } from '../contracts/canonical-strategy';
|
||||
import {
|
||||
paperActivationSchema,
|
||||
|
|
@ -43,6 +44,7 @@ export class CanonicalPaperRuntime implements PaperRuntime {
|
|||
constructor(
|
||||
private readonly options: {
|
||||
repository: CanonicalExecutionRepository;
|
||||
deployment?: PaperDeploymentBinding;
|
||||
programs: readonly StrategyProgram[];
|
||||
now?: () => number;
|
||||
publish?: (entries: readonly CanonicalJournalEntry[]) => void | Promise<void>;
|
||||
|
|
@ -84,6 +86,7 @@ export class CanonicalPaperRuntime implements PaperRuntime {
|
|||
const host: CanonicalPaperHost = {
|
||||
version: 1,
|
||||
configuration,
|
||||
...(this.options.deployment ? { deployment: structuredClone(this.options.deployment) } : {}),
|
||||
generation: this.generation,
|
||||
active: false,
|
||||
operatorHalted: true,
|
||||
|
|
|
|||
145
apps/stock/orchestrator/src/paper/PaperDeploymentHost.ts
Normal file
145
apps/stock/orchestrator/src/paper/PaperDeploymentHost.ts
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
import { z } from 'zod';
|
||||
import type { PaperDeploymentStatus } from '@stock-bot/stock-config/paper-deployments';
|
||||
import type { PaperReadiness, PaperRuntime } from '../contracts/paper-runtime';
|
||||
import type { CanonicalExecutionRepository, CanonicalPostgres } from '../execution/canonical-paper';
|
||||
import {
|
||||
authorizedPaperPackage,
|
||||
PaperDeploymentError,
|
||||
paperHash,
|
||||
readPaperDeployment,
|
||||
verifyPaperEvidenceCustody,
|
||||
} from './paper-deployment-custody';
|
||||
import type { createPromotedPaperRuntime } from './paper-host';
|
||||
import { paperHostUrl, readPaperHostIdentity } from './paper-host-identity';
|
||||
|
||||
export const unboundPaperReadiness = (reason = 'deployment-not-bound'): PaperReadiness => ({
|
||||
configured: false,
|
||||
accountId: null,
|
||||
sourceId: null,
|
||||
active: false,
|
||||
ready: false,
|
||||
operatorHalted: true,
|
||||
connected: false,
|
||||
reasons: [reason],
|
||||
lastReceivedAt: null,
|
||||
lastAvailableAt: null,
|
||||
requiresHistoricalRecovery: false,
|
||||
pendingInput: null,
|
||||
pendingBatch: null,
|
||||
pendingDecisionSequence: null,
|
||||
nativeStatus: null,
|
||||
risk: null,
|
||||
});
|
||||
|
||||
/** One explicit paper host. No default account, scheduler, automatic activation or strategy hot swap. */
|
||||
export class PaperDeploymentHost {
|
||||
private bound?: { id: string; runtime: PaperRuntime };
|
||||
private tail: Promise<unknown> = Promise.resolve();
|
||||
private readonly startupIdentity = readPaperHostIdentity().catch(() => null);
|
||||
constructor(
|
||||
private readonly options: {
|
||||
database: CanonicalPostgres;
|
||||
repository: CanonicalExecutionRepository;
|
||||
now?: () => number;
|
||||
}
|
||||
) {}
|
||||
private serial<T>(work: () => Promise<T>): Promise<T> {
|
||||
const next = this.tail.then(work, work);
|
||||
this.tail = next.catch(() => undefined);
|
||||
return next;
|
||||
}
|
||||
private async authorized(id: string) {
|
||||
return this.options.database.transaction(async tx => {
|
||||
const deployment = await readPaperDeployment(tx, id);
|
||||
const { pkg } = await authorizedPaperPackage(tx, deployment, true);
|
||||
await verifyPaperEvidenceCustody(tx, deployment);
|
||||
const startup = await this.startupIdentity;
|
||||
if (
|
||||
!startup ||
|
||||
paperHash(startup) !== paperHash(deployment.preview.host) ||
|
||||
paperHash(await readPaperHostIdentity()) !== paperHash(deployment.preview.host)
|
||||
) {
|
||||
throw new PaperDeploymentError(
|
||||
409,
|
||||
'Installed paper host/native/runtime differs from the reviewed promotion'
|
||||
);
|
||||
}
|
||||
return { deployment, pkg };
|
||||
});
|
||||
}
|
||||
async bind(id: string): Promise<PaperDeploymentStatus> {
|
||||
id = z.string().uuid().parse(id).toLowerCase();
|
||||
return this.serial(async () => {
|
||||
if (this.bound) {
|
||||
if (this.bound.id !== id) {
|
||||
throw new PaperDeploymentError(
|
||||
409,
|
||||
'This paper host is already bound; restart with the explicit deployment configuration to change it'
|
||||
);
|
||||
}
|
||||
return this.status(id);
|
||||
}
|
||||
const { deployment, pkg } = await this.authorized(id);
|
||||
const url = new URL(paperHostUrl);
|
||||
url.searchParams.set('sha256', deployment.preview.host.hostSha256);
|
||||
const module = (await import(url.href)) as {
|
||||
createPromotedPaperRuntime: typeof createPromotedPaperRuntime;
|
||||
};
|
||||
const runtime = await module.createPromotedPaperRuntime({
|
||||
deployment,
|
||||
pkg,
|
||||
repository: this.options.repository,
|
||||
now: this.options.now,
|
||||
});
|
||||
this.bound = { id, runtime };
|
||||
return this.status(id);
|
||||
});
|
||||
}
|
||||
async activate(id: string, recoverPending = false): Promise<PaperDeploymentStatus> {
|
||||
id = z.string().uuid().parse(id).toLowerCase();
|
||||
return this.serial(async () => {
|
||||
await this.authorized(id);
|
||||
const runtime = this.runtime(id);
|
||||
await runtime.activate({ recoverPending });
|
||||
return this.status(id);
|
||||
});
|
||||
}
|
||||
async halt(id: string, reason: string): Promise<PaperDeploymentStatus> {
|
||||
id = z.string().uuid().parse(id).toLowerCase();
|
||||
// Emergency halt remains available even if evidence/build/review later becomes unavailable.
|
||||
return this.serial(async () => {
|
||||
await this.runtime(id).halt(reason);
|
||||
return this.status(id);
|
||||
});
|
||||
}
|
||||
async readiness(): Promise<PaperReadiness> {
|
||||
return this.bound ? this.bound.runtime.status() : unboundPaperReadiness();
|
||||
}
|
||||
|
||||
async status(id: string): Promise<PaperDeploymentStatus> {
|
||||
id = z.string().uuid().parse(id).toLowerCase();
|
||||
await this.options.database.transaction(tx => readPaperDeployment(tx, id));
|
||||
return {
|
||||
deploymentId: id,
|
||||
boundDeploymentId: this.bound?.id ?? null,
|
||||
readiness:
|
||||
this.bound?.id === id
|
||||
? await this.bound.runtime.status()
|
||||
: unboundPaperReadiness(
|
||||
this.bound ? 'host-bound-to-another-deployment' : 'deployment-not-bound'
|
||||
),
|
||||
};
|
||||
}
|
||||
runtime(id?: string): PaperRuntime {
|
||||
if (!this.bound || (id !== undefined && this.bound.id !== id)) {
|
||||
throw new PaperDeploymentError(409, 'Deployment is not bound to this paper host');
|
||||
}
|
||||
return this.bound.runtime;
|
||||
}
|
||||
async shutdown() {
|
||||
return this.serial(async () => {
|
||||
await this.bound?.runtime.shutdown();
|
||||
this.bound = undefined;
|
||||
});
|
||||
}
|
||||
}
|
||||
190
apps/stock/orchestrator/src/paper/paper-deployment-custody.ts
Normal file
190
apps/stock/orchestrator/src/paper/paper-deployment-custody.ts
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
/** Read-only promotion custody. This module cannot import or execute strategy code. */
|
||||
import { createHash } from 'node:crypto';
|
||||
import type { QueryResultRow } from 'pg';
|
||||
import {
|
||||
paperDeploymentSchema,
|
||||
type PaperDeployment,
|
||||
type PaperPromotionPreview,
|
||||
} from '@stock-bot/stock-config/paper-deployments';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import { verifyRetainedProgramPackage } from '../strategies/retained-program';
|
||||
|
||||
export interface PaperDeploymentDatabase {
|
||||
query(text: string, values?: unknown[]): Promise<{ rows: QueryResultRow[] }>;
|
||||
}
|
||||
export class PaperDeploymentError extends Error {
|
||||
constructor(
|
||||
readonly status: 400 | 403 | 404 | 409 | 422 | 503,
|
||||
message: string
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
export const paperHash = (value: unknown) =>
|
||||
createHash('sha256').update(canonicalStrategyJson(value)).digest('hex');
|
||||
export function paperPreviewHash(
|
||||
preview: Omit<PaperPromotionPreview, 'previewHash'> | PaperPromotionPreview
|
||||
) {
|
||||
const { previewHash: _ignored, ...body } = preview as PaperPromotionPreview;
|
||||
return paperHash(body);
|
||||
}
|
||||
export function retainedPaperDeployment(raw: unknown): PaperDeployment {
|
||||
const value = paperDeploymentSchema.parse(raw);
|
||||
const { promotionHash, ...body } = value;
|
||||
if (
|
||||
paperHash(body) !== promotionHash ||
|
||||
paperPreviewHash(value.preview) !== value.preview.previewHash
|
||||
) {
|
||||
throw new Error('Retained paper promotion identity mismatch');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
export async function readPaperDeployment(
|
||||
database: PaperDeploymentDatabase,
|
||||
id: string
|
||||
): Promise<PaperDeployment> {
|
||||
const row = (await database.query('SELECT * FROM paper_deployments WHERE id=$1', [id])).rows[0];
|
||||
if (!row) {
|
||||
throw new PaperDeploymentError(404, 'Paper deployment not found');
|
||||
}
|
||||
const value = retainedPaperDeployment(row.document);
|
||||
if (
|
||||
value.id !== row.id ||
|
||||
value.preview.configuration.matching.risk.ledger.accountId !== row.account_id ||
|
||||
value.preview.strategy.versionId !== row.strategy_version_id ||
|
||||
value.promotionHash !== row.promotion_hash
|
||||
) {
|
||||
throw new Error('Retained paper deployment row identity mismatch');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
/** Admission and activation require a current operator approval. Historical GET stays available. */
|
||||
export async function authorizedPaperPackage(
|
||||
database: PaperDeploymentDatabase,
|
||||
deployment: PaperDeployment | Pick<PaperPromotionPreview, 'strategy'>,
|
||||
lock = false
|
||||
) {
|
||||
const preview = 'preview' in deployment ? deployment.preview : deployment;
|
||||
const version = (
|
||||
await database.query(
|
||||
`SELECT v.envelope,v.origin,s.archived_at FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id WHERE v.id=$1 AND s.id=$2${lock ? ' FOR UPDATE OF s' : ''}`,
|
||||
[preview.strategy.versionId, preview.strategy.familyId]
|
||||
)
|
||||
).rows[0];
|
||||
const review = (
|
||||
await database.query(
|
||||
'SELECT id,decision FROM strategy_review_events WHERE version_id=$1 ORDER BY ordinal DESC LIMIT 1',
|
||||
[preview.strategy.versionId]
|
||||
)
|
||||
).rows[0];
|
||||
if (!version || version.archived_at !== null || review?.decision !== 'approve') {
|
||||
throw new PaperDeploymentError(
|
||||
409,
|
||||
'Paper deployment requires an active family and current operator approval'
|
||||
);
|
||||
}
|
||||
const pkg = verifyRetainedProgramPackage(version.envelope);
|
||||
if (
|
||||
version.origin !== preview.strategy.origin ||
|
||||
pkg.artifact.sha256 !== preview.strategy.artifactSha256 ||
|
||||
pkg.dependencyLock.sha256 !== preview.strategy.dependencyLockSha256
|
||||
) {
|
||||
throw new Error('Paper promotion artifact no longer matches retained bytes');
|
||||
}
|
||||
return { pkg, reviewId: String(review.id) };
|
||||
}
|
||||
|
||||
/** Host-side retained identity check, independent of the web API's full financial source reader. */
|
||||
export async function verifyPaperEvidenceCustody(
|
||||
database: PaperDeploymentDatabase,
|
||||
deployment: PaperDeployment
|
||||
) {
|
||||
const { input, evidence } = deployment.preview,
|
||||
source = input.outOfSample;
|
||||
let report: Record<string, unknown> | undefined;
|
||||
if (source.kind === 'chronological-report/v1') {
|
||||
const row = (
|
||||
await database.query('SELECT validation_report FROM research_experiments WHERE id=$1', [
|
||||
source.validationId,
|
||||
])
|
||||
).rows[0];
|
||||
report = row?.validation_report;
|
||||
if ((report?.test as { runId?: string } | undefined)?.runId !== input.testRunId) {
|
||||
throw new Error('Paper test membership changed');
|
||||
}
|
||||
} else if (source.kind === 'walk-forward-report/v1') {
|
||||
const row = (
|
||||
await database.query('SELECT report FROM research_walk_forwards WHERE id=$1', [
|
||||
source.walkForwardId,
|
||||
])
|
||||
).rows[0];
|
||||
report = row?.report;
|
||||
if (
|
||||
!(report?.segments as Array<{ test: { runId: string } }> | undefined)?.some(
|
||||
segment => segment.test.runId === input.testRunId
|
||||
)
|
||||
) {
|
||||
throw new Error('Paper walk-forward test membership changed');
|
||||
}
|
||||
} else {
|
||||
throw new Error('Paper promotion requires sealed out-of-sample evidence');
|
||||
}
|
||||
if (!report) {
|
||||
throw new Error('Paper source report is missing');
|
||||
}
|
||||
const { _receipt, reportHash, ...body } = report;
|
||||
if (
|
||||
!_receipt ||
|
||||
paperHash(body) !== reportHash ||
|
||||
reportHash !== source.reportHash ||
|
||||
report.id !== source.reportId ||
|
||||
report.previewHash !== source.previewHash
|
||||
) {
|
||||
throw new Error('Paper source report changed');
|
||||
}
|
||||
const cost = (
|
||||
await database.query(
|
||||
'SELECT preview,preview_hash,validation_phase FROM research_experiments WHERE id=$1',
|
||||
[input.costExperimentId]
|
||||
)
|
||||
).rows[0];
|
||||
if (
|
||||
!cost ||
|
||||
cost.validation_phase !== null ||
|
||||
cost.preview?.version !== 'cost-sensitivity-preview/v1' ||
|
||||
cost.preview_hash !== input.costPreviewHash ||
|
||||
cost.preview?.previewHash !== input.costPreviewHash ||
|
||||
cost.preview.candidates.length !== evidence.costs.length
|
||||
) {
|
||||
throw new Error('Paper cost source changed');
|
||||
}
|
||||
const rows = (
|
||||
await database.query('SELECT id FROM runs WHERE experiment_id=$1 ORDER BY trial_index', [
|
||||
input.costExperimentId,
|
||||
])
|
||||
).rows;
|
||||
if (
|
||||
canonicalStrategyJson(rows.map(row => row.id)) !==
|
||||
canonicalStrategyJson(evidence.costs.map(item => item.runId))
|
||||
) {
|
||||
throw new Error('Paper cost membership changed');
|
||||
}
|
||||
for (const item of [evidence.test, ...evidence.costs]) {
|
||||
const row = (
|
||||
await database.query(
|
||||
'SELECT r.status,r.request_snapshot,r.dataset_hash,br.canonical_result FROM runs r JOIN backtest_results br ON br.run_id=r.id WHERE r.id=$1',
|
||||
[item.runId]
|
||||
)
|
||||
).rows[0];
|
||||
if (
|
||||
!row ||
|
||||
row.status !== 'completed' ||
|
||||
row.dataset_hash !== item.datasetHash ||
|
||||
paperHash(row.canonical_result) !== item.resultHash ||
|
||||
canonicalStrategyJson(row.canonical_result.request) !==
|
||||
canonicalStrategyJson(row.request_snapshot)
|
||||
) {
|
||||
throw new Error('Paper retained result identity changed');
|
||||
}
|
||||
}
|
||||
}
|
||||
76
apps/stock/orchestrator/src/paper/paper-host-identity.ts
Normal file
76
apps/stock/orchestrator/src/paper/paper-host-identity.ts
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
/** Read-only build identity. This module never imports the native addon or strategy code. */
|
||||
import { createHash } from 'node:crypto';
|
||||
import { realpathSync } from 'node:fs';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { dirname, isAbsolute, relative, resolve } from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import {
|
||||
paperHostIdentitySchema,
|
||||
type PaperHostIdentity,
|
||||
} from '@stock-bot/stock-config/paper-deployments';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
|
||||
const engineWrapper = realpathSync(fileURLToPath(import.meta.resolve('@stock-bot/engine')));
|
||||
const repositoryRoot = resolve(dirname(engineWrapper), '../../..');
|
||||
const ownPath = relative(repositoryRoot, realpathSync(fileURLToPath(import.meta.url)));
|
||||
if (isAbsolute(ownPath) || ownPath === '..' || ownPath.startsWith('../')) {
|
||||
throw new Error('Paper engine resolves outside this checkout');
|
||||
}
|
||||
if (engineWrapper !== resolve(repositoryRoot, 'apps/stock/engine/index.mjs')) {
|
||||
throw new Error('Unsupported canonical engine wrapper location');
|
||||
}
|
||||
|
||||
export const paperHostUrl = pathToFileURL(
|
||||
resolve(repositoryRoot, 'apps/stock/orchestrator/dist/paper-host.js')
|
||||
);
|
||||
|
||||
async function hashLocalFile(path: string): Promise<string> {
|
||||
if (realpathSync(path) !== path) {
|
||||
throw new Error('Paper build artifacts must belong to this checkout');
|
||||
}
|
||||
return createHash('sha256')
|
||||
.update(await readFile(path))
|
||||
.digest('hex');
|
||||
}
|
||||
|
||||
/** Capture all executable worker/native bytes and the runtime that interprets them. */
|
||||
export async function readPaperHostIdentity(): Promise<PaperHostIdentity> {
|
||||
if (typeof Bun === 'undefined') {
|
||||
throw new Error('Paper deployment requires the Bun runtime');
|
||||
}
|
||||
const [hostSha256, engineWrapperSha256, engineBinarySha256, dependencyLockSha256] =
|
||||
await Promise.all([
|
||||
hashLocalFile(fileURLToPath(paperHostUrl)),
|
||||
hashLocalFile(engineWrapper),
|
||||
hashLocalFile(resolve(repositoryRoot, 'apps/stock/engine/dist/engine.node')),
|
||||
hashLocalFile(resolve(repositoryRoot, 'bun.lock')),
|
||||
]);
|
||||
return paperHostIdentitySchema.parse({
|
||||
version: 'paper-host/v1',
|
||||
hostSha256,
|
||||
engineWrapperSha256,
|
||||
engineBinarySha256,
|
||||
dependencyLockSha256,
|
||||
runtime: 'bun',
|
||||
runtimeVersion: Bun.version,
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
});
|
||||
}
|
||||
|
||||
/** The running child supplies its own module URL, never a URL from the request. */
|
||||
export async function verifyPaperHostBuild(
|
||||
expected: PaperHostIdentity,
|
||||
actualHostUrl: string
|
||||
): Promise<PaperHostIdentity> {
|
||||
if (realpathSync(fileURLToPath(actualHostUrl)) !== realpathSync(fileURLToPath(paperHostUrl))) {
|
||||
throw new Error('Paper deployment requires the bundled paper host from this checkout');
|
||||
}
|
||||
const actual = await readPaperHostIdentity();
|
||||
if (
|
||||
canonicalStrategyJson(actual) !== canonicalStrategyJson(paperHostIdentitySchema.parse(expected))
|
||||
) {
|
||||
throw new Error('Paper host/native/runtime build identity mismatch');
|
||||
}
|
||||
return actual;
|
||||
}
|
||||
53
apps/stock/orchestrator/src/paper/paper-host.ts
Normal file
53
apps/stock/orchestrator/src/paper/paper-host.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
/** Dedicated bundled entry point. Importing it does not start a host or import a strategy. */
|
||||
import { loadedNativeIdentity } from '@stock-bot/engine';
|
||||
import type { PaperDeployment } from '@stock-bot/stock-config/paper-deployments';
|
||||
import type { StrategyVersionPackage } from '@stock-bot/types';
|
||||
import type { CanonicalExecutionRepository } from '../execution/canonical-paper';
|
||||
import { importRetainedProgram } from '../strategies/retained-program';
|
||||
import { CanonicalPaperRuntime } from './CanonicalPaperRuntime';
|
||||
import { retainedPaperDeployment } from './paper-deployment-custody';
|
||||
import { verifyPaperHostBuild } from './paper-host-identity';
|
||||
|
||||
/** Caller must have verified the immutable operator promotion and current permission before calling. */
|
||||
export async function createPromotedPaperRuntime(options: {
|
||||
deployment: PaperDeployment;
|
||||
pkg: StrategyVersionPackage;
|
||||
repository: CanonicalExecutionRepository;
|
||||
now?: () => number;
|
||||
}) {
|
||||
const deployment = retainedPaperDeployment(options.deployment);
|
||||
await verifyPaperHostBuild(deployment.preview.host, import.meta.url);
|
||||
if (
|
||||
loadedNativeIdentity.engineWrapperSha256 !== deployment.preview.host.engineWrapperSha256 ||
|
||||
loadedNativeIdentity.engineBinarySha256 !== deployment.preview.host.engineBinarySha256
|
||||
) {
|
||||
throw new Error(
|
||||
'Loaded native identity differs from paper promotion; restart with immutable build artifacts'
|
||||
);
|
||||
}
|
||||
if (
|
||||
options.pkg.artifact.sha256 !== deployment.preview.strategy.artifactSha256 ||
|
||||
options.pkg.dependencyLock.sha256 !== deployment.preview.strategy.dependencyLockSha256
|
||||
) {
|
||||
throw new Error('Paper host artifact does not match the operator promotion');
|
||||
}
|
||||
const program = await importRetainedProgram(
|
||||
options.pkg,
|
||||
deployment.preview.configuration.strategies[0]
|
||||
);
|
||||
const runtime = new CanonicalPaperRuntime({
|
||||
repository: options.repository,
|
||||
programs: [program],
|
||||
now: options.now,
|
||||
deployment: {
|
||||
deploymentId: deployment.id,
|
||||
promotionHash: deployment.promotionHash,
|
||||
strategyVersionId: deployment.preview.strategy.versionId,
|
||||
artifactSha256: deployment.preview.strategy.artifactSha256,
|
||||
dependencyLockSha256: deployment.preview.strategy.dependencyLockSha256,
|
||||
host: deployment.preview.host,
|
||||
},
|
||||
});
|
||||
await runtime.initialize(deployment.preview.configuration);
|
||||
return runtime;
|
||||
}
|
||||
23
apps/stock/orchestrator/src/paper/paper-operator.ts
Normal file
23
apps/stock/orchestrator/src/paper/paper-operator.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import { getCredentialHttpPrincipal } from '@stock-bot/di';
|
||||
import { PaperDeploymentError } from './paper-deployment-custody';
|
||||
|
||||
/** Defense in depth for both public services, including bearer requests carrying browser Origin. */
|
||||
export function requirePaperOperator(request: Request, origins: readonly string[]) {
|
||||
if (getCredentialHttpPrincipal(request) !== 'operator') {
|
||||
throw new PaperDeploymentError(
|
||||
403,
|
||||
'Credential-backed human operator required for paper commands'
|
||||
);
|
||||
}
|
||||
const origin = request.headers.get('origin');
|
||||
if (origin && (!origins.length || !origins.includes(origin))) {
|
||||
throw new PaperDeploymentError(
|
||||
403,
|
||||
'Paper commands require an explicitly configured trusted Origin'
|
||||
);
|
||||
}
|
||||
}
|
||||
export const paperAllowedOrigins = () =>
|
||||
process.env.STOCK_BOT_ALLOWED_ORIGINS?.split(',')
|
||||
.map(v => v.trim())
|
||||
.filter(Boolean) ?? [];
|
||||
|
|
@ -3,12 +3,17 @@ import type { Server as SocketIOServer } from 'socket.io';
|
|||
import { createAnalyticsRoutes } from '../api/rest/analytics';
|
||||
import { createBacktestRoutes } from '../api/rest/backtest';
|
||||
import { createPaperRoutes } from '../api/rest/paper';
|
||||
import { createPaperDeploymentHostRoutes } from '../api/rest/paper-deployments';
|
||||
import type { OrchestratorServices as IServiceContainer } from '../types';
|
||||
|
||||
/**
|
||||
* Create all routes for the orchestrator service
|
||||
*/
|
||||
export function createRoutes(services: IServiceContainer, _io?: SocketIOServer): Hono {
|
||||
export function createRoutes(
|
||||
services: IServiceContainer,
|
||||
_io?: SocketIOServer,
|
||||
origins?: readonly string[]
|
||||
): Hono {
|
||||
const app = new Hono();
|
||||
services.logger.info('Creating orchestrator routes');
|
||||
|
||||
|
|
@ -17,8 +22,15 @@ export function createRoutes(services: IServiceContainer, _io?: SocketIOServer):
|
|||
return c.json({
|
||||
status: 'healthy',
|
||||
service: 'orchestrator',
|
||||
mode: services.custom?.CanonicalPaperRuntime ? 'paper' : 'research-only',
|
||||
execution: services.custom?.CanonicalPaperRuntime ? 'canonical-paper' : 'canonical-research',
|
||||
mode:
|
||||
services.custom?.CanonicalPaperRuntime || services.custom?.PaperDeploymentHost
|
||||
? 'paper'
|
||||
: 'research-only',
|
||||
execution: services.custom?.PaperDeploymentHost
|
||||
? 'reviewed-paper-deployment'
|
||||
: services.custom?.CanonicalPaperRuntime
|
||||
? 'canonical-paper'
|
||||
: 'canonical-research',
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
});
|
||||
|
|
@ -32,13 +44,26 @@ export function createRoutes(services: IServiceContainer, _io?: SocketIOServer):
|
|||
...(await services.custom.CanonicalPaperRuntime.status()),
|
||||
});
|
||||
}
|
||||
if (services.custom?.PaperDeploymentHost) {
|
||||
return c.json({
|
||||
engine: 'reviewed-paper-deployment',
|
||||
...(await services.custom.PaperDeploymentHost.readiness()),
|
||||
});
|
||||
}
|
||||
return c.json({ error: 'Research-only runtime has no account execution gateway' }, 503);
|
||||
} catch (error) {
|
||||
services.logger.error('Could not read strategy recovery status', { error });
|
||||
return c.json({ error: 'Strategy recovery status unavailable' }, 503);
|
||||
}
|
||||
});
|
||||
app.route('/api/paper', createPaperRoutes(services));
|
||||
app.route(
|
||||
'/api/paper/deployments',
|
||||
createPaperDeploymentHostRoutes(services.custom?.PaperDeploymentHost, origins)
|
||||
);
|
||||
app.route(
|
||||
'/api/paper',
|
||||
createPaperRoutes(services, { deploymentHost: services.custom?.PaperDeploymentHost, origins })
|
||||
);
|
||||
// Retired gateways remain explicit diagnostics, never a fallback simulator.
|
||||
const unavailable = new Hono().all('*', c =>
|
||||
c.json(
|
||||
|
|
|
|||
|
|
@ -2,10 +2,10 @@ import { ServiceContainerBuilder } from '@stock-bot/di';
|
|||
import type { StockAppConfig } from '@stock-bot/stock-config';
|
||||
import { assertResearchConcurrency } from './backtest/ResearchBacktestPool';
|
||||
import { paperConfigurationSchema } from './contracts/paper-runtime';
|
||||
import { validatePaperConfiguration } from './paper/feed';
|
||||
import {
|
||||
assertSupportedComposition,
|
||||
registerOrchestratorServices,
|
||||
resolvePaperComposition,
|
||||
type OrchestratorRole,
|
||||
} from './container';
|
||||
import type { OrchestratorServices } from './types';
|
||||
|
|
@ -32,21 +32,17 @@ export async function createContainer(
|
|||
const maxConcurrent =
|
||||
settings?.backtesting?.maxConcurrent === undefined ? 1 : settings.backtesting.maxConcurrent;
|
||||
assertResearchConcurrency(maxConcurrent);
|
||||
if (settings?.canonicalPaper !== undefined && role !== 'paper') {
|
||||
throw new Error('Canonical paper configuration requires a paper composition');
|
||||
}
|
||||
const canonicalPaper =
|
||||
const { canonicalPaper, paperDeploymentHost } = resolvePaperComposition(
|
||||
role,
|
||||
settings?.canonicalPaper === undefined
|
||||
? undefined
|
||||
: validatePaperConfiguration(paperConfigurationSchema.parse(settings.canonicalPaper));
|
||||
if (role === 'paper' && !canonicalPaper) {
|
||||
throw new Error(
|
||||
'Paper composition requires explicit canonicalPaper configuration; accounts are never migrated automatically'
|
||||
);
|
||||
}
|
||||
if (canonicalPaper && !config.database?.postgres?.enabled) {
|
||||
: paperConfigurationSchema.parse(settings.canonicalPaper),
|
||||
settings?.paperDeploymentHost
|
||||
);
|
||||
if ((canonicalPaper || paperDeploymentHost) && !config.database?.postgres?.enabled) {
|
||||
throw new Error('Canonical paper requires durable PostgreSQL custody');
|
||||
}
|
||||
|
||||
const container = await new ServiceContainerBuilder()
|
||||
.withConfig(config)
|
||||
.withOptions({
|
||||
|
|
@ -67,6 +63,7 @@ export async function createContainer(
|
|||
syntheticSeed: config.services?.orchestrator?.backtesting?.syntheticSeed ?? 42,
|
||||
nativeExecutionTimeoutMs: config.services?.orchestrator?.backtesting?.executionTimeoutMs,
|
||||
canonicalPaper,
|
||||
paperDeploymentHost,
|
||||
});
|
||||
return container.resolve('serviceContainer') as OrchestratorServices;
|
||||
}
|
||||
|
|
|
|||
70
apps/stock/orchestrator/src/strategies/retained-program.ts
Normal file
70
apps/stock/orchestrator/src/strategies/retained-program.ts
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
/** Executable loader: call only in an OS-isolated candidate host or after a server-owned
|
||||
* trusted builtin/paper-promotion authorization. Metadata never grants that authority. */
|
||||
import { createHash } from 'node:crypto';
|
||||
import {
|
||||
retainedProgramSelectionSchema,
|
||||
type RetainedProgramSelection,
|
||||
} from '@stock-bot/stock-config/candidate-execution';
|
||||
import { parseStrategyVersionPackage } from '@stock-bot/stock-config/strategy';
|
||||
import type { StrategyVersionPackage } from '@stock-bot/types';
|
||||
import type { StrategyProgram } from '../contracts/canonical-strategy';
|
||||
import { freeze } from './strategy-decision';
|
||||
|
||||
export type { RetainedProgramSelection } from '@stock-bot/stock-config/candidate-execution';
|
||||
|
||||
/** Validates bytes and metadata only; never imports, compiles or calls candidate code. */
|
||||
export function verifyRetainedProgramPackage(input: unknown): StrategyVersionPackage {
|
||||
const pkg = parseStrategyVersionPackage(input);
|
||||
const hash = (content: string) => createHash('sha256').update(content, 'utf8').digest('hex');
|
||||
if (
|
||||
hash(pkg.artifact.content) !== pkg.artifact.sha256 ||
|
||||
hash(pkg.dependencyLock.content) !== pkg.dependencyLock.sha256
|
||||
) {
|
||||
throw new Error('Retained strategy artifact or dependency lock hash mismatch');
|
||||
}
|
||||
if (pkg.program.apiVersion !== 'canonical-ts/v1') {
|
||||
throw new Error('Unsupported retained strategy API version');
|
||||
}
|
||||
return pkg;
|
||||
}
|
||||
|
||||
export async function importRetainedProgram(
|
||||
input: StrategyVersionPackage,
|
||||
rawSelection: RetainedProgramSelection
|
||||
): Promise<StrategyProgram> {
|
||||
const pkg = verifyRetainedProgramPackage(input);
|
||||
const selection = retainedProgramSelectionSchema.parse(rawSelection);
|
||||
if (
|
||||
pkg.program.strategyId !== selection.strategyId ||
|
||||
pkg.program.strategyVersion !== selection.strategyVersion
|
||||
) {
|
||||
throw new Error('Retained strategy selection identity mismatch');
|
||||
}
|
||||
const moduleUrl = URL.createObjectURL(
|
||||
new Blob([pkg.artifact.content], { type: 'text/javascript' })
|
||||
);
|
||||
let module: Record<string, unknown>;
|
||||
try {
|
||||
module = await import(moduleUrl);
|
||||
} finally {
|
||||
URL.revokeObjectURL(moduleUrl);
|
||||
}
|
||||
const factory = module[pkg.artifact.entryExport];
|
||||
if (typeof factory !== 'function') {
|
||||
throw new Error('Retained strategy factory export is missing');
|
||||
}
|
||||
const program = factory(freeze(structuredClone(selection))) as StrategyProgram;
|
||||
if (
|
||||
!program ||
|
||||
typeof program !== 'object' ||
|
||||
program.ownerId !== selection.ownerId ||
|
||||
program.strategyId !== selection.strategyId ||
|
||||
program.strategyVersion !== selection.strategyVersion ||
|
||||
program.seed !== selection.seed ||
|
||||
program.mode !== 'target' ||
|
||||
typeof program.decide !== 'function'
|
||||
) {
|
||||
throw new Error('Retained strategy factory identity or API mismatch');
|
||||
}
|
||||
return program;
|
||||
}
|
||||
|
|
@ -12,7 +12,6 @@ import {
|
|||
nativeAdmissionOrders,
|
||||
type DecisionContext,
|
||||
type PublishedObservation,
|
||||
type replayConfigSchema,
|
||||
type ReplayIdentity,
|
||||
type ReplaySubmissionOutcome,
|
||||
} from '../contracts/native-replay';
|
||||
|
|
@ -48,7 +47,7 @@ export class StrategyController {
|
|||
constructor(
|
||||
private readonly identity: ReplayIdentity,
|
||||
programs: readonly StrategyProgram[],
|
||||
config: ReturnType<typeof replayConfigSchema.parse>
|
||||
config: { matching: { owners: { ownerId: string; mode: 'Target' | 'Orders' }[] } }
|
||||
) {
|
||||
this.slots = new Map(
|
||||
programs.map(program => {
|
||||
|
|
|
|||
|
|
@ -56,6 +56,7 @@ export type OrchestratorServices = import('@stock-bot/services').IServiceContain
|
|||
PaperTradingManager: import('./paper/PaperTradingManager').PaperTradingManager;
|
||||
ModeManager: import('./core/ModeManager').ModeManager;
|
||||
CanonicalPaperRuntime: import('./contracts/paper-runtime').PaperRuntime;
|
||||
PaperDeploymentHost: import('./paper/PaperDeploymentHost').PaperDeploymentHost;
|
||||
}>;
|
||||
};
|
||||
export type { BacktestResult } from './backtest/RustBacktestAdapter';
|
||||
|
|
|
|||
|
|
@ -68,7 +68,10 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
f === '25-walk-forward.sql' ||
|
||||
f === '26-cost-sensitivity.sql' ||
|
||||
f === '27-research-evidence-sources.sql' ||
|
||||
f === '28-research-agents.sql')
|
||||
f === '28-research-agents.sql' ||
|
||||
f === '29-isolated-candidates.sql' ||
|
||||
f === '30-paper-deployments.sql' ||
|
||||
f === '31-research-agent-project-links.sql')
|
||||
) // Explicit additive migration allowlist; never replay destructive init migrations
|
||||
.sort();
|
||||
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import { createExchangeRoutes } from './exchange.routes';
|
|||
import { createExperimentRoutes } from './experiments.routes';
|
||||
import { createHealthRoutes } from './health.routes';
|
||||
import { createMonitoringRoutes } from './monitoring.routes';
|
||||
import { createPaperDeploymentRoutes } from './paper-deployments.routes';
|
||||
import { createPipelineRoutes } from './pipeline.routes';
|
||||
import { createResearchAgentRoutes } from './research-agents.routes';
|
||||
import { createResearchRoutes } from './research.routes';
|
||||
|
|
@ -24,7 +25,11 @@ import { createStrategyRoutes } from './strategies.routes';
|
|||
// the old 1 MiB restriction; normalizers still validate every submitted record.
|
||||
export const WEB_API_MAX_REQUEST_BODY_SIZE = Number.MAX_SAFE_INTEGER;
|
||||
|
||||
export function createRoutes(container: IServiceContainer, suppliedSecurity?: HttpSecurity): Hono {
|
||||
export function createRoutes(
|
||||
container: IServiceContainer,
|
||||
suppliedSecurity?: HttpSecurity,
|
||||
integrations?: { paperOrchestratorOrigin?: string }
|
||||
): Hono {
|
||||
const agents = new ResearchAgentsService(container);
|
||||
const security =
|
||||
suppliedSecurity ??
|
||||
|
|
@ -67,6 +72,13 @@ export function createRoutes(container: IServiceContainer, suppliedSecurity?: Ht
|
|||
app.route('/', createResearchRoutes(container));
|
||||
app.route('/', createResearchAgentRoutes(container, security.researchEnabled));
|
||||
app.route('/', createExperimentRoutes(container));
|
||||
app.route(
|
||||
'/',
|
||||
createPaperDeploymentRoutes(container, {
|
||||
origin: integrations ? integrations.paperOrchestratorOrigin : process.env.ORCHESTRATOR_URL,
|
||||
origins: security.allowedOrigins,
|
||||
})
|
||||
);
|
||||
|
||||
return app;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -75,7 +75,10 @@ export function createExperimentRoutes(container: IServiceContainer) {
|
|||
};
|
||||
app.post('/api/v2/experiments/cost-sensitivity/preview', async c =>
|
||||
c.json({
|
||||
preview: await service.previewCosts(parseCostSensitivityInput(await body(c.req.raw))),
|
||||
preview: await service.previewCosts(
|
||||
parseCostSensitivityInput(await body(c.req.raw)),
|
||||
getResearchHttpPrincipal(c.req.raw) ?? ''
|
||||
),
|
||||
})
|
||||
);
|
||||
app.post('/api/v2/experiments/cost-sensitivity', async c => {
|
||||
|
|
@ -91,7 +94,12 @@ export function createExperimentRoutes(container: IServiceContainer) {
|
|||
return c.json({ experiment }, 202);
|
||||
});
|
||||
app.post('/api/v2/experiments/walk-forward/preview', async c =>
|
||||
c.json({ preview: await walkForwards.preview(parseWalkForwardInput(await body(c.req.raw))) })
|
||||
c.json({
|
||||
preview: await walkForwards.preview(
|
||||
parseWalkForwardInput(await body(c.req.raw)),
|
||||
getResearchHttpPrincipal(c.req.raw) ?? ''
|
||||
),
|
||||
})
|
||||
);
|
||||
app.post('/api/v2/experiments/walk-forward', async c => {
|
||||
const input = parseWalkForwardSubmission(await body(c.req.raw));
|
||||
|
|
@ -140,7 +148,9 @@ export function createExperimentRoutes(container: IServiceContainer) {
|
|||
});
|
||||
app.post('/api/v2/experiments/validation/preview', async c => {
|
||||
const input = parseChronologicalValidation(await body(c.req.raw));
|
||||
return c.json({ preview: await service.previewValidation(input) });
|
||||
return c.json({
|
||||
preview: await service.previewValidation(input, getResearchHttpPrincipal(c.req.raw) ?? ''),
|
||||
});
|
||||
});
|
||||
app.post('/api/v2/experiments/validation', async c => {
|
||||
const input = parseValidationSubmission(await body(c.req.raw));
|
||||
|
|
@ -204,7 +214,9 @@ export function createExperimentRoutes(container: IServiceContainer) {
|
|||
});
|
||||
app.post('/api/v2/experiments/preview', async c => {
|
||||
const input = parseExperimentInput(await body(c.req.raw));
|
||||
return c.json({ preview: await service.preview(input) });
|
||||
return c.json({
|
||||
preview: await service.preview(input, getResearchHttpPrincipal(c.req.raw) ?? ''),
|
||||
});
|
||||
});
|
||||
app.post('/api/v2/experiments', async c => {
|
||||
const input = parseExperimentSubmission(await body(c.req.raw));
|
||||
|
|
|
|||
178
apps/stock/web-api/src/routes/paper-deployments.routes.ts
Normal file
178
apps/stock/web-api/src/routes/paper-deployments.routes.ts
Normal file
|
|
@ -0,0 +1,178 @@
|
|||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { paperDeploymentStatusSchema } from '@stock-bot/stock-config/paper-deployments';
|
||||
import {
|
||||
paperActivationSchema,
|
||||
paperHaltSchema,
|
||||
PaperRuntimeError,
|
||||
} from '../../../orchestrator/src/contracts/paper-runtime';
|
||||
import { PaperDeploymentError } from '../../../orchestrator/src/paper/paper-deployment-custody';
|
||||
import {
|
||||
paperAllowedOrigins,
|
||||
requirePaperOperator,
|
||||
} from '../../../orchestrator/src/paper/paper-operator';
|
||||
import { PaperDeploymentsService } from '../services/paper-deployments.service';
|
||||
import { ResearchError } from '../services/research-errors';
|
||||
|
||||
/** Forwards the original human credential; never substitutes a service token. */
|
||||
export async function forwardPaperCommand(
|
||||
request: Request,
|
||||
id: string,
|
||||
operation: 'bind' | 'activate' | 'halt' | 'readiness',
|
||||
body: unknown,
|
||||
options: {
|
||||
origin?: string;
|
||||
request?: (url: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
||||
}
|
||||
) {
|
||||
if (!options.origin) {
|
||||
throw new PaperDeploymentError(503, 'Paper orchestrator origin is not configured');
|
||||
}
|
||||
let base: URL;
|
||||
try {
|
||||
base = new URL(options.origin);
|
||||
} catch {
|
||||
throw new PaperDeploymentError(503, 'Paper orchestrator origin is invalid');
|
||||
}
|
||||
if (
|
||||
!['http:', 'https:'].includes(base.protocol) ||
|
||||
base.username ||
|
||||
base.password ||
|
||||
base.pathname !== '/' ||
|
||||
base.search ||
|
||||
base.hash
|
||||
) {
|
||||
throw new PaperDeploymentError(503, 'Paper orchestrator requires a fixed HTTP origin');
|
||||
}
|
||||
const headers = new Headers({ 'Content-Type': 'application/json' });
|
||||
for (const name of ['authorization', 'cookie', 'origin']) {
|
||||
const value = request.headers.get(name);
|
||||
if (value) {
|
||||
headers.set(name, value);
|
||||
}
|
||||
}
|
||||
let response: Response;
|
||||
try {
|
||||
response = await (options.request ?? fetch)(
|
||||
new URL(`/api/paper/deployments/${id}/${operation}`, base),
|
||||
{
|
||||
method: operation === 'readiness' ? 'GET' : 'POST',
|
||||
headers,
|
||||
...(operation === 'readiness' ? {} : { body: JSON.stringify(body) }),
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(15000),
|
||||
}
|
||||
);
|
||||
} catch {
|
||||
throw new PaperDeploymentError(
|
||||
503,
|
||||
'Paper orchestrator could not confirm the command; check readiness before retrying'
|
||||
);
|
||||
}
|
||||
const value: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
const status = [400, 403, 404, 409, 422, 503].includes(response.status) ? response.status : 503;
|
||||
const message =
|
||||
value && typeof value === 'object' && 'error' in value && typeof value.error === 'string'
|
||||
? value.error
|
||||
: 'Paper orchestrator rejected the request';
|
||||
throw new PaperDeploymentError(status as 400 | 403 | 404 | 409 | 422 | 503, message);
|
||||
}
|
||||
const status = paperDeploymentStatusSchema.parse(value);
|
||||
if (status.deploymentId !== id) {
|
||||
throw new Error('Paper orchestrator returned another deployment');
|
||||
}
|
||||
return status;
|
||||
}
|
||||
export function createPaperDeploymentRoutes(
|
||||
container: IServiceContainer,
|
||||
options: {
|
||||
origin?: string;
|
||||
origins?: readonly string[];
|
||||
request?: (url: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
||||
service?: PaperDeploymentsService;
|
||||
} = {}
|
||||
) {
|
||||
const app = new Hono(),
|
||||
service = options.service ?? new PaperDeploymentsService(container),
|
||||
origins = options.origins ?? paperAllowedOrigins();
|
||||
app.use('*', async (c, next) => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
if (c.req.method !== 'GET' || c.req.path.endsWith('/readiness')) {
|
||||
requirePaperOperator(c.req.raw, origins);
|
||||
}
|
||||
await next();
|
||||
});
|
||||
app.onError((error, c) => {
|
||||
if (error instanceof PaperDeploymentError || error instanceof ResearchError) {
|
||||
return c.json({ error: error.message }, error.status);
|
||||
}
|
||||
if (
|
||||
error instanceof z.ZodError ||
|
||||
error instanceof SyntaxError ||
|
||||
error instanceof PaperRuntimeError
|
||||
) {
|
||||
return c.json(
|
||||
{
|
||||
error:
|
||||
error instanceof PaperRuntimeError ? error.message : 'Invalid paper promotion request',
|
||||
},
|
||||
400
|
||||
);
|
||||
}
|
||||
container.logger.error('Paper deployment operation failed', { error });
|
||||
return c.json({ error: 'Paper deployment evidence or storage unavailable' }, 500);
|
||||
});
|
||||
app.get('/api/v2/paper-deployments', async c => c.json({ deployments: await service.list() }));
|
||||
app.post('/api/v2/paper-deployments/preview', async c =>
|
||||
c.json(await service.preview(await c.req.json()))
|
||||
);
|
||||
app.post('/api/v2/paper-deployments', async c =>
|
||||
c.json(await service.create(await c.req.json(), c.req.header('Idempotency-Key') ?? ''), 201)
|
||||
);
|
||||
app.get('/api/v2/paper-deployments/:id', async c =>
|
||||
c.json(
|
||||
await service.get(
|
||||
z
|
||||
.string()
|
||||
.uuid()
|
||||
.transform(value => value.toLowerCase())
|
||||
.parse(c.req.param('id'))
|
||||
)
|
||||
)
|
||||
);
|
||||
for (const operation of ['bind', 'activate', 'halt', 'readiness'] as const) {
|
||||
const path = `/api/v2/paper-deployments/:id/${operation}`;
|
||||
app.on(operation === 'readiness' ? 'GET' : 'POST', path, async c => {
|
||||
const id = z
|
||||
.string()
|
||||
.uuid()
|
||||
.transform(value => value.toLowerCase())
|
||||
.parse(c.req.param('id'));
|
||||
const body =
|
||||
operation === 'readiness'
|
||||
? undefined
|
||||
: operation === 'activate'
|
||||
? paperActivationSchema.parse(await c.req.json())
|
||||
: operation === 'halt'
|
||||
? paperHaltSchema.parse(await c.req.json())
|
||||
: z
|
||||
.object({})
|
||||
.strict()
|
||||
.parse(await c.req.json());
|
||||
if (operation === 'bind' || operation === 'activate') {
|
||||
await service.authorizeCommand(id);
|
||||
} else {
|
||||
await service.get(id);
|
||||
}
|
||||
return c.json(
|
||||
await forwardPaperCommand(c.req.raw, id, operation, body, {
|
||||
origin: options.origin ?? process.env.ORCHESTRATOR_URL,
|
||||
request: options.request,
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
return app;
|
||||
}
|
||||
|
|
@ -15,6 +15,7 @@ import {
|
|||
} from '@stock-bot/stock-config/backtest';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
canonicalStrategyExecution,
|
||||
parseCanonicalFinancialResult,
|
||||
type CanonicalReproductionComparison,
|
||||
type CanonicalReproductionPreview,
|
||||
|
|
@ -862,7 +863,7 @@ export class BacktestServiceV2 {
|
|||
saved.backtestId !== row.backtest_id ||
|
||||
saved.status !== 'completed' ||
|
||||
saved.financialEngine !== 'rust' ||
|
||||
saved.strategyExecution !== 'typescript-retained-builtin/v1' ||
|
||||
saved.strategyExecution !== canonicalStrategyExecution(request) ||
|
||||
!Number.isFinite(Date.parse(saved.completedAt)) ||
|
||||
!Number.isFinite(saved.executionTime) ||
|
||||
saved.executionTime < 0 ||
|
||||
|
|
@ -884,15 +885,21 @@ export class BacktestServiceV2 {
|
|||
|
||||
async canonicalCapability(id: string): Promise<CanonicalRunCapability> {
|
||||
try {
|
||||
await this.container.postgres.transaction(async client => {
|
||||
const execution = await this.container.postgres.transaction(async client => {
|
||||
const row = (await client.query('SELECT * FROM backtests WHERE id=$1 FOR UPDATE', [id]))
|
||||
.rows[0];
|
||||
if (!row || row.archived_at !== null) {
|
||||
throw new Error('Backtest is missing or archived');
|
||||
}
|
||||
await admitCanonicalRequest(client, this.container, this.mapBacktest(row), id);
|
||||
const request = await admitCanonicalRequest(
|
||||
client,
|
||||
this.container,
|
||||
this.mapBacktest(row),
|
||||
id
|
||||
);
|
||||
return request.strategy.origin === 'candidate' ? request.strategy.execution : undefined;
|
||||
});
|
||||
return { available: true, reason: null };
|
||||
return { available: true, reason: null, ...(execution ? { execution } : {}) };
|
||||
} catch (error) {
|
||||
return {
|
||||
available: false,
|
||||
|
|
|
|||
|
|
@ -1,19 +1,27 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import type { PoolClient } from 'pg';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import {
|
||||
retainedProgramSelectionSchema,
|
||||
type CandidateExecution,
|
||||
} from '@stock-bot/stock-config/candidate-execution';
|
||||
import {
|
||||
canonicalResearchSettingsSchema,
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalDatasetCatalogEntry,
|
||||
type CanonicalRunRequest,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { builtinStrategySelectionSchema } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
builtinStrategySelectionSchema,
|
||||
validateStrategyParameters,
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
HistoricalDataRequestError,
|
||||
parseFinancialDecimal,
|
||||
type HistoricalDatasetV2,
|
||||
type StrategyParameterValue,
|
||||
} from '@stock-bot/types';
|
||||
import { readCandidateExecution } from '../../../orchestrator/src/backtest/candidate-sandbox';
|
||||
import { readCanonicalBuildIdentity } from '../../../orchestrator/src/backtest/canonical-build';
|
||||
import { validateDatasetV2 } from '../../../orchestrator/src/data/historical-dataset-v2';
|
||||
import { canonicalRiskSessionClock } from './canonical-risk-clock';
|
||||
|
|
@ -155,8 +163,34 @@ export async function admitCanonicalRequest(
|
|||
container: IServiceContainer,
|
||||
template: CanonicalTemplate,
|
||||
backtestId: string,
|
||||
runId = randomUUID()
|
||||
runId = randomUUID(),
|
||||
override?: { versionId: string; parameters: Record<string, StrategyParameterValue> },
|
||||
baselineVersionId = template.strategyVersionId
|
||||
): Promise<CanonicalRunRequest> {
|
||||
if (override) {
|
||||
await client.query(
|
||||
'SELECT s.id FROM strategies s WHERE s.id IN (SELECT strategy_id FROM strategy_versions WHERE id=ANY($1::uuid[])) ORDER BY s.id FOR UPDATE',
|
||||
[[template.strategyVersionId, override.versionId].filter(Boolean)]
|
||||
);
|
||||
await admitCanonicalRequest(client, container, template, backtestId, runId);
|
||||
const candidate = await admitCanonicalRequest(
|
||||
client,
|
||||
container,
|
||||
{
|
||||
...template,
|
||||
strategyVersionId: override.versionId,
|
||||
strategyParameters: override.parameters,
|
||||
},
|
||||
backtestId,
|
||||
runId,
|
||||
undefined,
|
||||
template.strategyVersionId
|
||||
);
|
||||
if (candidate.strategy.origin !== 'candidate') {
|
||||
return invalid('Candidate override requires an immutable candidate version');
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
if (!template.strategyVersionId || !template.strategyParameters) {
|
||||
return invalid('Select an immutable strategy version and validated parameters');
|
||||
}
|
||||
|
|
@ -167,10 +201,12 @@ export async function admitCanonicalRequest(
|
|||
[template.strategyVersionId]
|
||||
)
|
||||
).rows[0];
|
||||
if (!selected || selected.archived_at !== null || selected.origin !== 'builtin') {
|
||||
return invalid(
|
||||
'Only active, server-seeded built-in versions can execute; candidates require isolation'
|
||||
);
|
||||
if (
|
||||
!selected ||
|
||||
selected.archived_at !== null ||
|
||||
!['builtin', 'candidate'].includes(selected.origin)
|
||||
) {
|
||||
return invalid('Select an active retained strategy version');
|
||||
}
|
||||
const review = (
|
||||
await client.query(
|
||||
|
|
@ -178,17 +214,45 @@ export async function admitCanonicalRequest(
|
|||
[template.strategyVersionId]
|
||||
)
|
||||
).rows[0];
|
||||
if (review?.decision !== 'approve') {
|
||||
return invalid('An operator must approve this built-in version before execution');
|
||||
if (
|
||||
selected.origin === 'builtin' ? review?.decision !== 'approve' : review?.decision === 'revoke'
|
||||
) {
|
||||
return invalid(
|
||||
selected.origin === 'builtin'
|
||||
? 'An operator must approve this built-in version before execution'
|
||||
: 'The candidate version is revoked'
|
||||
);
|
||||
}
|
||||
const pkg = await new StrategyCatalogService(container).getVersionArtifact(
|
||||
template.strategyVersionId,
|
||||
client
|
||||
);
|
||||
let candidateExecution: CandidateExecution | undefined;
|
||||
if (selected.origin === 'candidate') {
|
||||
if (
|
||||
pkg.execution?.kind !== 'isolated-candidate/v1' ||
|
||||
pkg.program.apiVersion !== 'canonical-ts/v1'
|
||||
) {
|
||||
return invalid(
|
||||
'Candidate requires a retained isolated execution declaration and supported API'
|
||||
);
|
||||
}
|
||||
try {
|
||||
candidateExecution = await readCandidateExecution();
|
||||
} catch (error) {
|
||||
return invalid(error instanceof Error ? error.message : 'Candidate isolation unavailable');
|
||||
}
|
||||
} else if (pkg.execution !== undefined) {
|
||||
return invalid('Built-in origin cannot select a candidate execution profile');
|
||||
}
|
||||
const { settings, dataset, execution, initial } = await validateCanonicalSetup(client, template);
|
||||
const clock = canonicalRiskSessionClock(dataset);
|
||||
const ownerId = `strategy:${template.strategyVersionId}`;
|
||||
const selection = builtinStrategySelectionSchema.parse({
|
||||
const selection = (
|
||||
selected.origin === 'candidate'
|
||||
? retainedProgramSelectionSchema
|
||||
: builtinStrategySelectionSchema
|
||||
).parse({
|
||||
strategyId: pkg.program.strategyId,
|
||||
strategyVersion: pkg.program.strategyVersion,
|
||||
ownerId,
|
||||
|
|
@ -196,7 +260,7 @@ export async function admitCanonicalRequest(
|
|||
instrumentId: execution.instrumentId,
|
||||
seriesId: execution.seriesId,
|
||||
ownerBudget: settings.ownerBudget,
|
||||
parameters: template.strategyParameters,
|
||||
parameters: validateStrategyParameters(pkg, template.strategyParameters),
|
||||
// API/checkpoint identities are retained in the package, not selection fields.
|
||||
});
|
||||
return canonicalRunRequestSchema.parse({
|
||||
|
|
@ -207,8 +271,9 @@ export async function admitCanonicalRequest(
|
|||
strategy: {
|
||||
familyId: selected.strategy_id,
|
||||
versionId: template.strategyVersionId,
|
||||
origin: 'builtin',
|
||||
reviewId: review.id,
|
||||
origin: selected.origin,
|
||||
reviewId: review?.id ?? null,
|
||||
...(candidateExecution ? { execution: candidateExecution, baselineVersionId } : {}),
|
||||
package: pkg,
|
||||
selection,
|
||||
},
|
||||
|
|
|
|||
|
|
@ -120,7 +120,7 @@ export class ChronologicalValidationService {
|
|||
return concurrent;
|
||||
}
|
||||
const { recipe: _recipe, ...sourceInput } = input;
|
||||
const source = await this.experiments.lockedPreview(client, sourceInput);
|
||||
const source = await this.experiments.lockedPreview(client, sourceInput, identity.principal);
|
||||
const sourceDataset = await readCanonicalDataset(client, source.request.datasetHash);
|
||||
const prepared = prepareChronologicalValidation(input, source, sourceDataset);
|
||||
if (prepared.preview.previewHash !== previewHash) {
|
||||
|
|
|
|||
|
|
@ -40,7 +40,12 @@ export function buildCostSensitivityPreview(
|
|||
const input = parseCostSensitivityInput(raw),
|
||||
source = retainedExperimentPreview(baseline);
|
||||
if (
|
||||
!equal(source.input, { backtestId: input.backtestId, name: input.name, grid: {} }) ||
|
||||
!equal(source.input, {
|
||||
backtestId: input.backtestId,
|
||||
name: input.name,
|
||||
grid: {},
|
||||
...(input.candidate ? { candidate: input.candidate } : {}),
|
||||
}) ||
|
||||
source.candidates.length !== 1
|
||||
) {
|
||||
throw new Error('Cost sensitivity requires the unchanged empty-grid source');
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { z } from 'zod';
|
||||
import { retainedProgramSelectionSchema } from '@stock-bot/stock-config/candidate-execution';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalRunRequest,
|
||||
|
|
@ -108,7 +109,11 @@ export function experimentCandidates(
|
|||
return combinations.map((parameters, index) => {
|
||||
try {
|
||||
const validated = validateStrategyParameters(request.strategy.package, parameters);
|
||||
const selection = builtinStrategySelectionSchema.parse({
|
||||
const selection = (
|
||||
request.strategy.origin === 'candidate'
|
||||
? retainedProgramSelectionSchema
|
||||
: builtinStrategySelectionSchema
|
||||
).parse({
|
||||
...request.strategy.selection,
|
||||
parameters: validated,
|
||||
});
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';
|
|||
import type { PoolClient, QueryResultRow } from 'pg';
|
||||
import { z } from 'zod';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import { canonicalStrategyExecution } from '@stock-bot/stock-config/canonical-research';
|
||||
import type {
|
||||
CostSensitivityInput,
|
||||
WorkbenchExperimentDetail,
|
||||
|
|
@ -39,7 +40,11 @@ import {
|
|||
PREVIEW_RUN_ID,
|
||||
} from './experiment-input';
|
||||
import { mapExperimentRetry, parseExperimentRetry, retryColumns } from './experiment-retry';
|
||||
import { lockExperimentResearchAgent, lockResearchAgent } from './research-agent-budget';
|
||||
import {
|
||||
lockExperimentResearchAgent,
|
||||
lockResearchAgent,
|
||||
verifyCandidateGrant,
|
||||
} from './research-agent-budget';
|
||||
import { RunReproductionError, verifyReproductionInputs } from './run-reproduction';
|
||||
import { StrategyCatalogError } from './strategy-catalog.service';
|
||||
import { parseChronologicalValidation, prepareChronologicalValidation } from './validation-preview';
|
||||
|
|
@ -118,32 +123,52 @@ export class ExperimentsService {
|
|||
constructor(private readonly container: IServiceContainer) {
|
||||
this.database = requireServices(container, 'postgres').postgres;
|
||||
}
|
||||
async preview(raw: unknown): Promise<ExperimentPreview> {
|
||||
async preview(raw: unknown, principal = 'operator'): Promise<ExperimentPreview> {
|
||||
const input = parseExperimentInput(raw);
|
||||
return this.database.transaction(client => this.lockedPreview(client, input));
|
||||
}
|
||||
async previewCosts(raw: unknown) {
|
||||
const input = parseCostSensitivityInput(raw);
|
||||
return this.database.transaction(client => this.lockedCostPreview(client, input));
|
||||
}
|
||||
private async lockedCostPreview(client: PoolClient, input: CostSensitivityInput) {
|
||||
const source = await this.lockedPreview(client, {
|
||||
backtestId: input.backtestId,
|
||||
name: input.name,
|
||||
grid: {},
|
||||
return this.database.transaction(async client => {
|
||||
await lockResearchAgent(client, principal);
|
||||
return this.lockedPreview(client, input, principal);
|
||||
});
|
||||
}
|
||||
async previewCosts(raw: unknown, principal = 'operator') {
|
||||
const input = parseCostSensitivityInput(raw);
|
||||
return this.database.transaction(async client => {
|
||||
await lockResearchAgent(client, principal);
|
||||
return this.lockedCostPreview(client, input, principal);
|
||||
});
|
||||
}
|
||||
private async lockedCostPreview(
|
||||
client: PoolClient,
|
||||
input: CostSensitivityInput,
|
||||
principal = 'operator'
|
||||
) {
|
||||
const source = await this.lockedPreview(
|
||||
client,
|
||||
{
|
||||
backtestId: input.backtestId,
|
||||
name: input.name,
|
||||
grid: {},
|
||||
...(input.candidate ? { candidate: input.candidate } : {}),
|
||||
},
|
||||
principal
|
||||
);
|
||||
return buildCostSensitivityPreview(input, source);
|
||||
}
|
||||
async previewValidation(raw: unknown) {
|
||||
async previewValidation(raw: unknown, principal = 'operator') {
|
||||
const input = parseChronologicalValidation(raw);
|
||||
const { recipe: _recipe, ...sourceInput } = input;
|
||||
return this.database.transaction(async client => {
|
||||
const source = await this.lockedPreview(client, sourceInput);
|
||||
await lockResearchAgent(client, principal);
|
||||
const source = await this.lockedPreview(client, sourceInput, principal);
|
||||
const dataset = await readCanonicalDataset(client, source.request.datasetHash);
|
||||
return prepareChronologicalValidation(input, source, dataset).preview;
|
||||
});
|
||||
}
|
||||
async lockedPreview(client: PoolClient, input: ExperimentInput): Promise<ExperimentPreview> {
|
||||
async lockedPreview(
|
||||
client: PoolClient,
|
||||
input: ExperimentInput,
|
||||
principal = 'operator'
|
||||
): Promise<ExperimentPreview> {
|
||||
const parent = (
|
||||
await client.query('SELECT * FROM backtests WHERE id=$1 FOR UPDATE', [input.backtestId])
|
||||
).rows[0];
|
||||
|
|
@ -172,7 +197,8 @@ export class ExperimentsService {
|
|||
config: parent.config,
|
||||
},
|
||||
input.backtestId,
|
||||
PREVIEW_RUN_ID
|
||||
PREVIEW_RUN_ID,
|
||||
input.candidate
|
||||
);
|
||||
} catch (cause) {
|
||||
if (
|
||||
|
|
@ -192,6 +218,7 @@ export class ExperimentsService {
|
|||
}
|
||||
throw cause;
|
||||
}
|
||||
await verifyCandidateGrant(client, request, principal);
|
||||
return buildExperimentPreview(
|
||||
input,
|
||||
request,
|
||||
|
|
@ -251,8 +278,8 @@ export class ExperimentsService {
|
|||
}
|
||||
const preview: WorkbenchExperimentPreview =
|
||||
'scenarios' in input
|
||||
? await this.lockedCostPreview(client, input)
|
||||
: await this.lockedPreview(client, input);
|
||||
? await this.lockedCostPreview(client, input, receipt.principal)
|
||||
: await this.lockedPreview(client, input, receipt.principal);
|
||||
if (preview.previewHash !== previewHash) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
|
|
@ -648,7 +675,7 @@ export class ExperimentsService {
|
|||
run.result_run_id !== run.id ||
|
||||
run.result_backtest_id !== expected.backtestId ||
|
||||
run.financial_engine !== 'rust' ||
|
||||
run.strategy_execution !== 'typescript-retained-builtin/v1' ||
|
||||
run.strategy_execution !== canonicalStrategyExecution(expected) ||
|
||||
!equal(run.result_request, expected) ||
|
||||
run.analytics_version !== 1 ||
|
||||
!equal(run.analytics_policy, expectedPolicy) ||
|
||||
|
|
|
|||
361
apps/stock/web-api/src/services/paper-deployments.service.ts
Normal file
361
apps/stock/web-api/src/services/paper-deployments.service.ts
Normal file
|
|
@ -0,0 +1,361 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import type {
|
||||
CanonicalRunRequest,
|
||||
CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
paperPromotionInputSchema,
|
||||
paperPromotionPreviewSchema,
|
||||
paperPromotionSubmissionSchema,
|
||||
type PaperDeployment,
|
||||
type PaperPromotionInput,
|
||||
type PaperPromotionPreview,
|
||||
} from '@stock-bot/stock-config/paper-deployments';
|
||||
import { assertStrategyJsonText, canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import type { ResearchEvidenceReference } from '@stock-bot/types';
|
||||
import { validatePaperConfiguration } from '../../../orchestrator/src/paper/feed';
|
||||
import {
|
||||
authorizedPaperPackage,
|
||||
PaperDeploymentError,
|
||||
paperHash,
|
||||
paperPreviewHash,
|
||||
readPaperDeployment,
|
||||
retainedPaperDeployment,
|
||||
} from '../../../orchestrator/src/paper/paper-deployment-custody';
|
||||
import { readPaperHostIdentity } from '../../../orchestrator/src/paper/paper-host-identity';
|
||||
import { BacktestServiceV2, type BacktestResultQuery } from './backtest-v2.service';
|
||||
import { retainedCostSensitivityPreview } from './cost-sensitivity-input';
|
||||
import { canonicalReproductionHash } from './reproduction-comparison';
|
||||
import { verifyResearchSource } from './research-source-evidence';
|
||||
|
||||
const equal = (a: unknown, b: unknown) => canonicalStrategyJson(a) === canonicalStrategyJson(b);
|
||||
const reference = (runId: string): ResearchEvidenceReference => ({
|
||||
runId,
|
||||
metricsVersion: 'canonical-analytics/v1',
|
||||
metricPath: 'analytics.metrics.totalReturn',
|
||||
});
|
||||
const inputError = (message: string): never => {
|
||||
throw new PaperDeploymentError(422, message);
|
||||
};
|
||||
/** Explicit economic comparison: only run identity, dates, and the two studied cost rates may vary. */
|
||||
export function paperEconomicProfile(request: CanonicalRunRequest) {
|
||||
const { ledger, feeRate: _fee, ...risk } = request.policy.matching.risk;
|
||||
const { sessionId: _session, accountId: _account, riskSession: _clock, ...capital } = ledger;
|
||||
const { risk: _risk, slippageRate: _slippage, ...execution } = request.policy.matching;
|
||||
const { matching: _matching, risk_boundaries: _boundaries, ...policy } = request.policy;
|
||||
const { reviewId: _review, ...strategy } = request.strategy;
|
||||
return {
|
||||
strategy,
|
||||
capital,
|
||||
risk,
|
||||
execution,
|
||||
policy,
|
||||
analyticsPolicy: request.analyticsPolicy,
|
||||
build: request.build,
|
||||
modelArtifacts: request.modelArtifacts,
|
||||
};
|
||||
}
|
||||
function evidence(result: CanonicalRunResult) {
|
||||
return {
|
||||
runId: result.runId,
|
||||
datasetHash: result.request.datasetHash,
|
||||
economicHash: canonicalReproductionHash(result),
|
||||
resultHash: paperHash(result),
|
||||
metrics: { ...result.analytics.metrics },
|
||||
fillCount: result.analytics.fillCount,
|
||||
limitations: [...result.financial.limitations, ...result.financial.modelLimitations],
|
||||
};
|
||||
}
|
||||
|
||||
export class PaperDeploymentsService {
|
||||
private readonly database;
|
||||
private readonly results;
|
||||
constructor(
|
||||
private readonly container: IServiceContainer,
|
||||
private readonly identity = readPaperHostIdentity
|
||||
) {
|
||||
this.database = requireServices(container, 'postgres').postgres;
|
||||
this.results = new BacktestServiceV2(container);
|
||||
}
|
||||
private async prepare(
|
||||
input: PaperPromotionInput,
|
||||
db: BacktestResultQuery,
|
||||
lock = false
|
||||
): Promise<PaperPromotionPreview> {
|
||||
const selected = paperPromotionInputSchema.parse(input),
|
||||
source = selected.outOfSample;
|
||||
const results = await verifyResearchSource(
|
||||
source,
|
||||
[reference(selected.testRunId)],
|
||||
db,
|
||||
(id, tx) => this.results.getRunResults(id, tx)
|
||||
);
|
||||
const test = results.get(selected.testRunId);
|
||||
if (!test) {
|
||||
return inputError('Selected test evidence is unavailable');
|
||||
}
|
||||
let sourceHash: string | undefined;
|
||||
if (source.kind === 'chronological-report/v1') {
|
||||
const row = (
|
||||
await db.query(
|
||||
'SELECT validation_report,validation_manifest FROM research_experiments WHERE id=$1',
|
||||
[source.validationId]
|
||||
)
|
||||
).rows[0];
|
||||
if (row?.validation_report?.test?.runId !== test.runId) {
|
||||
return inputError('Select the sealed test run, not training or validation');
|
||||
}
|
||||
sourceHash = row.validation_manifest?.source?.request?.datasetHash;
|
||||
} else {
|
||||
const row = (
|
||||
await db.query('SELECT report,preview FROM research_walk_forwards WHERE id=$1', [
|
||||
source.walkForwardId,
|
||||
])
|
||||
).rows[0];
|
||||
if (
|
||||
!row?.report?.segments?.some(
|
||||
(segment: { test?: { runId: string } }) => segment.test?.runId === test.runId
|
||||
)
|
||||
) {
|
||||
return inputError('Select a sealed walk-forward test run');
|
||||
}
|
||||
sourceHash = row.preview?.source?.request?.datasetHash;
|
||||
}
|
||||
const costRow = (
|
||||
await db.query('SELECT * FROM research_experiments WHERE id=$1', [selected.costExperimentId])
|
||||
).rows[0];
|
||||
if (
|
||||
!costRow ||
|
||||
costRow.validation_phase !== null ||
|
||||
costRow.preview?.version !== 'cost-sensitivity-preview/v1'
|
||||
) {
|
||||
return inputError('Select a standalone cost-sensitivity study');
|
||||
}
|
||||
const costs = retainedCostSensitivityPreview(costRow.preview);
|
||||
if (
|
||||
costs.previewHash !== selected.costPreviewHash ||
|
||||
costRow.preview_hash !== costs.previewHash ||
|
||||
costs.source.request.datasetHash !== sourceHash
|
||||
) {
|
||||
return inputError('Cost evidence must use the exact common source dataset and preview');
|
||||
}
|
||||
const rows = (
|
||||
await db.query(
|
||||
'SELECT id,status,trial_index FROM runs WHERE experiment_id=$1 ORDER BY trial_index',
|
||||
[selected.costExperimentId]
|
||||
)
|
||||
).rows;
|
||||
if (
|
||||
rows.length !== costs.candidates.length ||
|
||||
rows.some((r, i) => r.status !== 'completed' || r.trial_index !== i)
|
||||
) {
|
||||
return inputError('Every cost scenario must have a completed retained result');
|
||||
}
|
||||
const costResults = await verifyResearchSource(
|
||||
{ kind: 'experiment/v1', experimentId: costRow.id, previewHash: costs.previewHash },
|
||||
rows.map(r => reference(r.id)),
|
||||
db,
|
||||
(id, tx) => this.results.getRunResults(id, tx)
|
||||
);
|
||||
const cost = costResults.get(selected.costRunId);
|
||||
if (!cost) {
|
||||
return inputError('Selected cost scenario is not a completed member');
|
||||
}
|
||||
for (const item of costResults.values()) {
|
||||
if (!equal(paperEconomicProfile(test.request), paperEconomicProfile(item.request))) {
|
||||
return inputError(
|
||||
'Test and cost evidence must share the exact version, parameters, seed, capital, risk, execution and research build'
|
||||
);
|
||||
}
|
||||
}
|
||||
const selection = structuredClone(cost.request.strategy.selection),
|
||||
matching = structuredClone(cost.request.policy.matching);
|
||||
const { transport } = selected;
|
||||
matching.risk.ledger.accountId = transport.accountId;
|
||||
matching.risk.ledger.sessionId = transport.sessionId;
|
||||
matching.risk.ledger.riskSession = transport.riskSession;
|
||||
const configuration = validatePaperConfiguration({
|
||||
version: 2,
|
||||
matching: {
|
||||
...matching,
|
||||
series: [
|
||||
{
|
||||
instrumentId: selection.instrumentId,
|
||||
seriesId: transport.quoteSeriesId,
|
||||
mode: 'Quote',
|
||||
},
|
||||
],
|
||||
},
|
||||
strategies: [selection],
|
||||
policy: transport.policy,
|
||||
});
|
||||
if (configuration.version !== 2) {
|
||||
throw new Error('Promotion requires deployment configuration');
|
||||
}
|
||||
const interval = costs.dataset.series.find(s => s.id === selection.seriesId)?.interval;
|
||||
if (interval === '1d') {
|
||||
return inputError(
|
||||
'Paper promotion currently requires an explicit intraday observation interval'
|
||||
);
|
||||
}
|
||||
const retainedInterval = interval
|
||||
? { '1m': 60000, '5m': 300000, '15m': 900000, '1h': 3600000, '1d': 86400000 }[interval]
|
||||
: undefined;
|
||||
if (
|
||||
configuration.policy.observations.length !== 1 ||
|
||||
configuration.policy.observations[0]?.intervalMs !== retainedInterval
|
||||
) {
|
||||
return inputError('Paper observation interval must equal the retained research series');
|
||||
}
|
||||
const strategy = {
|
||||
familyId: test.request.strategy.familyId,
|
||||
versionId: test.request.strategy.versionId,
|
||||
origin: test.request.strategy.origin,
|
||||
reviewId: test.request.strategy.reviewId as string,
|
||||
artifactSha256: test.request.strategy.package.artifact.sha256,
|
||||
dependencyLockSha256: test.request.strategy.package.dependencyLock.sha256,
|
||||
};
|
||||
const host = await this.identity();
|
||||
const sharedBuildFields = [
|
||||
'engineWrapperSha256',
|
||||
'engineBinarySha256',
|
||||
'dependencyLockSha256',
|
||||
'runtime',
|
||||
'runtimeVersion',
|
||||
'platform',
|
||||
'arch',
|
||||
] as const;
|
||||
if (sharedBuildFields.some(field => host[field] !== test.request.build[field])) {
|
||||
throw new PaperDeploymentError(
|
||||
409,
|
||||
'Paper and research require the same native, dependency and runtime build; rerun evidence on the installed build'
|
||||
);
|
||||
}
|
||||
const draft = {
|
||||
version: 'paper-promotion-preview/v1' as const,
|
||||
input: selected,
|
||||
strategy,
|
||||
configuration,
|
||||
host,
|
||||
evidence: {
|
||||
test: evidence(test),
|
||||
costs: rows.map(r => {
|
||||
const result = costResults.get(r.id);
|
||||
if (!result) {
|
||||
throw new Error('Missing verified cost result');
|
||||
}
|
||||
return evidence(result);
|
||||
}),
|
||||
},
|
||||
limitations: [
|
||||
'Human promotion authorizes these exact strategy bytes to execute as trusted paper-host code; research isolation does not carry over.',
|
||||
'Paper uses explicit quotes and displayed sizes instead of historical Open prices and volume participation; fills may differ.',
|
||||
'Future feed timing, sessions, corporate-action handling and liquidity are operator-supplied. No live broker is connected.',
|
||||
'Paper starts with the factory initial strategy state and empty positions; historical strategy checkpoints are not copied.',
|
||||
'Sealed reset-account holdouts and cost studies are evidence, not a guarantee of future performance.',
|
||||
],
|
||||
};
|
||||
const authorization = await authorizedPaperPackage(db, draft, lock);
|
||||
draft.strategy.reviewId = authorization.reviewId;
|
||||
return paperPromotionPreviewSchema.parse({ ...draft, previewHash: paperPreviewHash(draft) });
|
||||
}
|
||||
async preview(raw: unknown) {
|
||||
assertStrategyJsonText(raw);
|
||||
const input = paperPromotionInputSchema.parse(raw);
|
||||
return this.database.transaction(async tx => {
|
||||
await tx.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
return this.prepare(input, tx);
|
||||
});
|
||||
}
|
||||
async create(raw: unknown, key: string): Promise<PaperDeployment> {
|
||||
if (!/^[!-~]{1,200}$/.test(key)) {
|
||||
throw new PaperDeploymentError(400, 'A printable Idempotency-Key is required');
|
||||
}
|
||||
assertStrategyJsonText(raw);
|
||||
const input = paperPromotionSubmissionSchema.parse(raw),
|
||||
requestHash = paperHash(input);
|
||||
return this.database.transaction(async tx => {
|
||||
await tx.query("SELECT pg_advisory_xact_lock(hashtextextended('paper-promotion:'||$1,0))", [
|
||||
key,
|
||||
]);
|
||||
const old = (
|
||||
await tx.query(
|
||||
'SELECT document,request_hash FROM paper_deployments WHERE idempotency_key=$1',
|
||||
[key]
|
||||
)
|
||||
).rows[0];
|
||||
if (old) {
|
||||
if (old.request_hash !== requestHash) {
|
||||
throw new PaperDeploymentError(409, 'Paper promotion key already names another request');
|
||||
}
|
||||
return retainedPaperDeployment(old.document);
|
||||
}
|
||||
const { previewHash, ...rawInput } = input;
|
||||
const preview = await this.prepare(rawInput, tx, true);
|
||||
if (preview.previewHash !== previewHash) {
|
||||
throw new PaperDeploymentError(
|
||||
409,
|
||||
'Paper preview changed; review the evidence and host identity again'
|
||||
);
|
||||
}
|
||||
const body = {
|
||||
id: randomUUID(),
|
||||
version: 'paper-deployment/v1' as const,
|
||||
principal: 'operator' as const,
|
||||
createdAt: new Date().toISOString(),
|
||||
preview,
|
||||
};
|
||||
const document = { ...body, promotionHash: paperHash(body) };
|
||||
try {
|
||||
await tx.query(
|
||||
'INSERT INTO paper_deployments(id,account_id,strategy_version_id,promotion_hash,idempotency_key,request_hash,document) VALUES($1,$2,$3,$4,$5,$6,$7::jsonb)',
|
||||
[
|
||||
document.id,
|
||||
preview.configuration.matching.risk.ledger.accountId,
|
||||
preview.strategy.versionId,
|
||||
document.promotionHash,
|
||||
key,
|
||||
requestHash,
|
||||
JSON.stringify(document),
|
||||
]
|
||||
);
|
||||
} catch (error) {
|
||||
if ((error as { code?: string }).code === '23505') {
|
||||
throw new PaperDeploymentError(409, 'Paper account already has an immutable deployment');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return document;
|
||||
});
|
||||
}
|
||||
async list(): Promise<PaperDeployment[]> {
|
||||
return (
|
||||
await this.database.query(
|
||||
'SELECT document FROM paper_deployments ORDER BY created_at DESC,id'
|
||||
)
|
||||
).rows.map(r => retainedPaperDeployment(r.document));
|
||||
}
|
||||
async get(id: string) {
|
||||
return readPaperDeployment(this.database, id);
|
||||
}
|
||||
/** Recheck full retained financial evidence before forwarding a human bind or activation. */
|
||||
async authorizeCommand(id: string) {
|
||||
return this.database.transaction(async tx => {
|
||||
await tx.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
const saved = await readPaperDeployment(tx, id);
|
||||
const current = await this.prepare(saved.preview.input, tx);
|
||||
const oldBody = {
|
||||
...saved.preview,
|
||||
strategy: { ...saved.preview.strategy, reviewId: current.strategy.reviewId },
|
||||
};
|
||||
if (paperPreviewHash(oldBody) !== current.previewHash) {
|
||||
throw new PaperDeploymentError(
|
||||
409,
|
||||
'Retained deployment evidence or installed paper host changed'
|
||||
);
|
||||
}
|
||||
return saved;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
canonicalStrategyExecution,
|
||||
parseCanonicalFinancialResult,
|
||||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
|
|
@ -16,7 +17,7 @@ export function canonicalReproductionHash(result: CanonicalRunResult): string {
|
|||
result.kind !== 'canonical-result/v1' ||
|
||||
result.status !== 'completed' ||
|
||||
result.financialEngine !== 'rust' ||
|
||||
result.strategyExecution !== 'typescript-retained-builtin/v1' ||
|
||||
result.strategyExecution !== canonicalStrategyExecution(request) ||
|
||||
result.runId !== request.runId ||
|
||||
result.backtestId !== request.backtestId
|
||||
) {
|
||||
|
|
|
|||
|
|
@ -20,9 +20,18 @@ export function researchGrantPolicy(request: CanonicalRunRequest) {
|
|||
const policy = structuredClone(request.policy);
|
||||
policy.matching.risk.ledger.sessionId = 'agent-grant-run';
|
||||
policy.matching.risk.ledger.accountId = 'agent-grant-account';
|
||||
if (request.strategy.origin === 'candidate') {
|
||||
const ownerId = `strategy:${request.strategy.baselineVersionId}`;
|
||||
policy.matching.risk.ledger.ownerIds = [ownerId];
|
||||
policy.matching.owners = [{ ownerId, mode: 'Target' }];
|
||||
policy.cadence = [{ owner_id: ownerId, series_ids: [request.strategy.selection.seriesId] }];
|
||||
}
|
||||
return {
|
||||
datasetHash: request.datasetHash,
|
||||
versionId: request.strategy.versionId,
|
||||
versionId:
|
||||
request.strategy.origin === 'candidate'
|
||||
? request.strategy.baselineVersionId
|
||||
: request.strategy.versionId,
|
||||
ownerBudget: request.strategy.selection.ownerBudget,
|
||||
seed: request.strategy.selection.seed,
|
||||
policy,
|
||||
|
|
@ -92,3 +101,18 @@ export async function lockExperimentResearchAgent(
|
|||
await lockResearchAgent(database, owner);
|
||||
}
|
||||
}
|
||||
|
||||
/** SQL remains authoritative; this preflight never executes candidate code or changes grants. */
|
||||
export async function verifyCandidateGrant(
|
||||
database: AgentQuery,
|
||||
request: CanonicalRunRequest,
|
||||
principal: string
|
||||
): Promise<void> {
|
||||
if (!isResearchAgent(principal) || request.strategy.origin !== 'candidate') {
|
||||
return;
|
||||
}
|
||||
await database.query(
|
||||
'SELECT assert_research_agent_grant(a,$2,$3::jsonb) FROM research_agents a WHERE id=$1',
|
||||
[principal, request.backtestId, request]
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,10 +27,13 @@ function record(row: QueryResultRow): ResearchAgentRecord {
|
|||
enabled: row.enabled,
|
||||
revision: row.revision,
|
||||
allowedProjectIds: row.policy.allowedProjectIds,
|
||||
grants: row.policy.grants.map((grant: { backtestId: string; policyHash: string }) => ({
|
||||
backtestId: grant.backtestId,
|
||||
policyHash: grant.policyHash,
|
||||
})),
|
||||
grants: row.policy.grants.map(
|
||||
(grant: { backtestId: string; policyHash: string; allowOwnCandidates?: boolean }) => ({
|
||||
backtestId: grant.backtestId,
|
||||
policyHash: grant.policyHash,
|
||||
...(grant.allowOwnCandidates ? { allowOwnCandidates: true } : {}),
|
||||
})
|
||||
),
|
||||
limits: row.policy.limits,
|
||||
createdAt: new Date(row.created_at).toISOString(),
|
||||
updatedAt: new Date(row.updated_at).toISOString(),
|
||||
|
|
@ -78,9 +81,13 @@ export class ResearchAgentsService {
|
|||
input: {
|
||||
allowedProjectIds: string[];
|
||||
allowedBacktestIds: string[];
|
||||
allowOwnCandidateBacktestIds?: string[];
|
||||
limits: ResearchAgentRecord['limits'];
|
||||
}
|
||||
) {
|
||||
if (input.allowOwnCandidateBacktestIds?.some(id => !input.allowedBacktestIds.includes(id))) {
|
||||
throw new ResearchAgentError(400, 'Candidate opt-ins must be a subset of granted backtests');
|
||||
}
|
||||
for (const id of input.allowedProjectIds) {
|
||||
if (
|
||||
!(
|
||||
|
|
@ -148,7 +155,12 @@ export class ResearchAgentsService {
|
|||
);
|
||||
}
|
||||
const policy = researchGrantPolicy(request);
|
||||
grants.push({ backtestId: id, policyHash: researchGrantHash(policy), policy });
|
||||
grants.push({
|
||||
backtestId: id,
|
||||
policyHash: researchGrantHash(policy),
|
||||
policy,
|
||||
...(input.allowOwnCandidateBacktestIds?.includes(id) ? { allowOwnCandidates: true } : {}),
|
||||
});
|
||||
}
|
||||
return { version: 1, allowedProjectIds: input.allowedProjectIds, grants, limits: input.limits };
|
||||
}
|
||||
|
|
@ -200,8 +212,33 @@ export class ResearchAgentsService {
|
|||
: await this.policy(client, {
|
||||
allowedProjectIds: input.allowedProjectIds ?? old.policy.allowedProjectIds,
|
||||
allowedBacktestIds: input.allowedBacktestIds,
|
||||
allowOwnCandidateBacktestIds: input.allowOwnCandidateBacktestIds ?? [],
|
||||
limits: input.limits ?? old.policy.limits,
|
||||
});
|
||||
if (
|
||||
input.allowedBacktestIds === undefined &&
|
||||
input.allowOwnCandidateBacktestIds !== undefined
|
||||
) {
|
||||
const allowed = new Set(
|
||||
policy.grants.map((grant: { backtestId: string }) => grant.backtestId)
|
||||
);
|
||||
if (input.allowOwnCandidateBacktestIds.some(id => !allowed.has(id))) {
|
||||
throw new ResearchAgentError(
|
||||
400,
|
||||
'Candidate opt-ins must be a subset of granted backtests'
|
||||
);
|
||||
}
|
||||
const candidateOptIns = input.allowOwnCandidateBacktestIds;
|
||||
policy.grants = policy.grants.map(
|
||||
(grant: { backtestId: string; allowOwnCandidates?: boolean }) => {
|
||||
const { allowOwnCandidates: _old, ...frozen } = grant;
|
||||
return {
|
||||
...frozen,
|
||||
...(candidateOptIns.includes(grant.backtestId) ? { allowOwnCandidates: true } : {}),
|
||||
};
|
||||
}
|
||||
);
|
||||
}
|
||||
if (input.allowedProjectIds) {
|
||||
for (const projectId of input.allowedProjectIds) {
|
||||
if (
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import type { IServiceContainer } from '@stock-bot/services';
|
|||
import type { CanonicalRunRequest } from '@stock-bot/stock-config/canonical-research';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
||||
import { verifyCandidateExecution } from '../../../orchestrator/src/backtest/candidate-sandbox';
|
||||
import { readCanonicalBuildIdentity } from '../../../orchestrator/src/backtest/canonical-build';
|
||||
import { readCanonicalDataset } from './canonical-research.service';
|
||||
import { StrategyCatalogError, StrategyCatalogService } from './strategy-catalog.service';
|
||||
|
|
@ -22,7 +23,7 @@ export async function verifyReproductionInputs(
|
|||
client: PoolClient,
|
||||
container: IServiceContainer,
|
||||
request: CanonicalRunRequest
|
||||
): Promise<string> {
|
||||
): Promise<string | null> {
|
||||
const selected = (
|
||||
await client.query(
|
||||
`SELECT v.strategy_id,v.origin,s.archived_at FROM strategy_versions v
|
||||
|
|
@ -33,9 +34,9 @@ export async function verifyReproductionInputs(
|
|||
if (
|
||||
!selected ||
|
||||
selected.strategy_id !== request.strategy.familyId ||
|
||||
selected.origin !== 'builtin'
|
||||
selected.origin !== request.strategy.origin
|
||||
) {
|
||||
throw new RunReproductionError(409, 'The original retained built-in version is unavailable');
|
||||
throw new RunReproductionError(409, 'The original retained strategy version is unavailable');
|
||||
}
|
||||
if (selected.archived_at !== null) {
|
||||
throw new RunReproductionError(409, 'The original strategy family is archived');
|
||||
|
|
@ -46,10 +47,16 @@ export async function verifyReproductionInputs(
|
|||
[request.strategy.versionId]
|
||||
)
|
||||
).rows[0];
|
||||
if (review?.decision !== 'approve') {
|
||||
if (
|
||||
request.strategy.origin === 'builtin'
|
||||
? review?.decision !== 'approve'
|
||||
: review?.decision === 'revoke'
|
||||
) {
|
||||
throw new RunReproductionError(
|
||||
409,
|
||||
'The original strategy version requires current operator approval'
|
||||
request.strategy.origin === 'builtin'
|
||||
? 'The original strategy version requires current operator approval'
|
||||
: 'The original candidate version is explicitly revoked'
|
||||
);
|
||||
}
|
||||
try {
|
||||
|
|
@ -100,5 +107,15 @@ export async function verifyReproductionInputs(
|
|||
'The original worker/native/runtime build is not installed; historical build execution is unavailable'
|
||||
);
|
||||
}
|
||||
return review.id;
|
||||
if (request.strategy.origin === 'candidate') {
|
||||
try {
|
||||
await verifyCandidateExecution(request.strategy.execution);
|
||||
} catch {
|
||||
throw new RunReproductionError(
|
||||
409,
|
||||
'The retained isolated candidate runtime is not installed'
|
||||
);
|
||||
}
|
||||
}
|
||||
return review?.id ?? null;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -111,7 +111,11 @@ const version = (row: QueryResultRow): StrategyVersionSummary => ({
|
|||
? row.review_status === 'approved'
|
||||
? 'Configure a supported canonical dataset and explicit financial policy before execution.'
|
||||
: 'An operator must approve this built-in version before configuring execution.'
|
||||
: 'Candidate execution requires isolation (A02); publication and approval do not execute code.',
|
||||
: row.review_status === 'revoked'
|
||||
? 'Candidate is revoked; new research admissions are unavailable.'
|
||||
: row.package.execution?.kind === 'isolated-candidate/v1'
|
||||
? 'Candidate runs only in the isolated research host. Configure retained data and financial policy; approval never selects trusted execution.'
|
||||
: 'Publish a new immutable version with an isolated execution declaration and author-declared warmup before execution.',
|
||||
});
|
||||
class ReceiptRace extends Error {}
|
||||
|
||||
|
|
|
|||
|
|
@ -76,7 +76,7 @@ export function validationPhasePreview(
|
|||
preview: ChronologicalValidationPreview,
|
||||
phase: ValidationPhase,
|
||||
winner?: ExperimentCandidate,
|
||||
reviewId?: string
|
||||
reviewId?: string | null
|
||||
) {
|
||||
const partition = preview.partitions.find(p => p.phase === phase);
|
||||
if (!partition) {
|
||||
|
|
@ -84,7 +84,11 @@ export function validationPhasePreview(
|
|||
}
|
||||
const request = structuredClone(partition.request);
|
||||
if (phase !== 'train') {
|
||||
if (!winner || !reviewId) {
|
||||
if (
|
||||
!winner ||
|
||||
reviewId === undefined ||
|
||||
(request.strategy.origin === 'builtin' && reviewId === null)
|
||||
) {
|
||||
throw new Error('Holdout admission requires a frozen winner and current approval');
|
||||
}
|
||||
request.strategy.selection.parameters = structuredClone(
|
||||
|
|
@ -97,6 +101,14 @@ export function validationPhasePreview(
|
|||
backtestId: preview.input.backtestId,
|
||||
name: `${preview.input.name} · ${phase}`,
|
||||
grid: phase === 'train' ? preview.input.grid : {},
|
||||
...(preview.input.candidate
|
||||
? {
|
||||
candidate: {
|
||||
...preview.input.candidate,
|
||||
parameters: structuredClone(request.strategy.selection.parameters),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
canonicalRunRequestSchema.parse(request),
|
||||
partition.dataset
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
chronologicalPolicyForOrigin,
|
||||
chronologicalValidationInputSchema,
|
||||
chronologicalValidationPolicy,
|
||||
type ChronologicalValidationInput,
|
||||
type ChronologicalValidationPreview,
|
||||
type ValidationPartitionPreview,
|
||||
|
|
@ -33,6 +33,13 @@ export function parseChronologicalValidation(input: unknown): ChronologicalValid
|
|||
}
|
||||
}
|
||||
function requiredHistory(source: ExperimentPreview): number {
|
||||
if (source.request.strategy.origin === 'candidate') {
|
||||
const execution = source.request.strategy.package.execution;
|
||||
if (!execution) {
|
||||
throw new ExperimentError(409, 'Candidate is missing its author-declared warmup');
|
||||
}
|
||||
return execution.warmupBars;
|
||||
}
|
||||
return Math.max(
|
||||
...source.candidates.map(candidate => {
|
||||
const selection = builtinStrategySelectionSchema.parse({
|
||||
|
|
@ -136,6 +143,11 @@ export function prepareChronologicalValidation(
|
|||
);
|
||||
}
|
||||
const warnings: string[] = [];
|
||||
if (source.request.strategy.origin === 'candidate') {
|
||||
warnings.push(
|
||||
'Candidate warmup is author-declared; input checks do not establish absence of leakage, model fitting validity, or reproducible strategy decisions'
|
||||
);
|
||||
}
|
||||
if (counts.unavailableAtEnd) {
|
||||
warnings.push(
|
||||
`${counts.unavailableAtEnd} completed-bar observations arrive after the evaluation end and cannot inform decisions or terminal marks`
|
||||
|
|
@ -170,7 +182,7 @@ export function prepareChronologicalValidation(
|
|||
execution: 'preview-only' as const,
|
||||
input,
|
||||
source,
|
||||
policy: chronologicalValidationPolicy,
|
||||
policy: chronologicalPolicyForOrigin(source.request.strategy.origin),
|
||||
partitions,
|
||||
};
|
||||
return { preview: { ...manifest, previewHash: experimentHash(manifest) }, datasets };
|
||||
|
|
|
|||
|
|
@ -78,13 +78,20 @@ export class WalkForwardService {
|
|||
this.experiments = new ExperimentsService(container);
|
||||
this.validations = new ChronologicalValidationService(container);
|
||||
}
|
||||
async preview(raw: unknown) {
|
||||
async preview(raw: unknown, principal = 'operator') {
|
||||
const input = parseWalkForwardInput(raw);
|
||||
return this.database.transaction(async client => (await this.prepare(client, input)).preview);
|
||||
return this.database.transaction(async client => {
|
||||
await lockResearchAgent(client, principal);
|
||||
return (await this.prepare(client, input, principal)).preview;
|
||||
});
|
||||
}
|
||||
private async prepare(client: PoolClient, input: ReturnType<typeof parseWalkForwardInput>) {
|
||||
private async prepare(
|
||||
client: PoolClient,
|
||||
input: ReturnType<typeof parseWalkForwardInput>,
|
||||
principal = 'operator'
|
||||
) {
|
||||
const { windows: _windows, ...sourceInput } = input;
|
||||
const source = await this.experiments.lockedPreview(client, sourceInput);
|
||||
const source = await this.experiments.lockedPreview(client, sourceInput, principal);
|
||||
const dataset = await readCanonicalDataset(client, source.request.datasetHash);
|
||||
return prepareWalkForward(input, source, dataset);
|
||||
}
|
||||
|
|
@ -122,7 +129,7 @@ export class WalkForwardService {
|
|||
if (concurrent) {
|
||||
return concurrent;
|
||||
}
|
||||
const prepared = await this.prepare(client, input);
|
||||
const prepared = await this.prepare(client, input, identity.principal);
|
||||
if (prepared.preview.previewHash !== previewHash) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import {
|
|||
WalkForwardDetailPage,
|
||||
} from '@/features/experiments';
|
||||
import { MonitoringPage } from '@/features/monitoring';
|
||||
import { PaperDeploymentPage, PaperDeploymentsPage } from '@/features/paper';
|
||||
import { PipelinePage } from '@/features/pipeline';
|
||||
import { ResearchAgentsPage, ResearchListPage, ResearchProjectPage } from '@/features/research';
|
||||
import { StrategyDetailPage, StrategyListPage, StrategyVersionPage } from '@/features/strategies';
|
||||
|
|
@ -51,6 +52,10 @@ export function App() {
|
|||
<Route path="run/:runId" element={<BacktestDetailPageV2 />} />
|
||||
</Route>
|
||||
</Route>
|
||||
<Route path="paper">
|
||||
<Route index element={<PaperDeploymentsPage />} />
|
||||
<Route path=":deploymentId" element={<PaperDeploymentPage />} />
|
||||
</Route>
|
||||
<Route path="research">
|
||||
<Route index element={<ResearchListPage />} />
|
||||
<Route path="agents" element={<ResearchAgentsPage />} />
|
||||
|
|
|
|||
|
|
@ -550,6 +550,13 @@ export function BacktestDetailPageV2() {
|
|||
>
|
||||
Retry execution eligibility
|
||||
</button>
|
||||
{canonicalCapability?.execution && !isCapabilityLoading && (
|
||||
<span className="block break-all">
|
||||
Isolated candidate sandbox: {canonicalCapability.execution.imageId}. Limit{' '}
|
||||
{canonicalCapability.execution.profile.limits.wallMs / 1000}s per container; agent
|
||||
attempt deadlines may be shorter.
|
||||
</span>
|
||||
)}
|
||||
{backtest?.strategyVersionId && (
|
||||
<>
|
||||
{' '}
|
||||
|
|
|
|||
|
|
@ -68,9 +68,19 @@ export function CanonicalResults({
|
|||
>
|
||||
<h3 className="font-semibold">Canonical research result</h3>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Rust financial simulation · retained TypeScript built-in. Completion does not establish
|
||||
strategy profitability or authorize trading.
|
||||
Rust financial simulation ·{' '}
|
||||
{request.strategy.origin === 'candidate'
|
||||
? 'isolated TypeScript candidate'
|
||||
: 'retained TypeScript built-in'}
|
||||
. Completion does not establish strategy profitability or authorize trading.
|
||||
</p>
|
||||
{request.strategy.origin === 'candidate' && (
|
||||
<p className="text-sm break-all">
|
||||
Sandbox {request.strategy.execution.imageId} · Author-declared warmup{' '}
|
||||
{request.strategy.package.execution?.warmupBars} bars. Candidate code is unverified;
|
||||
retained seeds and inputs support an actual reproduction comparison.
|
||||
</p>
|
||||
)}
|
||||
<dl className="grid gap-3 text-sm sm:grid-cols-2 break-all">
|
||||
<div>
|
||||
<dt>Run</dt>
|
||||
|
|
|
|||
|
|
@ -32,9 +32,10 @@ const policyFields: {
|
|||
{
|
||||
key: 'ownerBudget',
|
||||
label: 'Owner budget',
|
||||
group: 'Capital allocation',
|
||||
group: 'Strategy sizing',
|
||||
kind: 'decimal',
|
||||
description: 'USD allocated to this strategy; it cannot exceed initial capital.',
|
||||
description:
|
||||
'USD sizing input supplied to the strategy. Rust enforces the separate position, exposure and cash constraints. This input cannot exceed initial capital.',
|
||||
},
|
||||
{
|
||||
key: 'feeRate',
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { z } from 'zod';
|
||||
import { candidateExecutionSchema } from '@stock-bot/stock-config/candidate-execution';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import type {
|
||||
CanonicalDatasetCatalogEntry,
|
||||
|
|
@ -562,7 +563,18 @@ export const backtestApiV2 = {
|
|||
if (!response.ok) {
|
||||
throw await requestError(response, 'Could not check canonical execution eligibility');
|
||||
}
|
||||
return response.json();
|
||||
const capability = z
|
||||
.object({
|
||||
available: z.boolean(),
|
||||
reason: z.string().nullable(),
|
||||
execution: candidateExecutionSchema.optional(),
|
||||
})
|
||||
.strict()
|
||||
.parse(await response.json());
|
||||
if (capability.execution && !capability.available) {
|
||||
throw new Error('Unavailable execution cannot advertise an admitted sandbox profile');
|
||||
}
|
||||
return capability;
|
||||
},
|
||||
async listCanonicalDatasets(signal?: AbortSignal): Promise<CanonicalDatasetCatalogEntry[]> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/datasets/canonical?limit=50&offset=0`, {
|
||||
|
|
|
|||
|
|
@ -348,6 +348,7 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
|
|||
experimentId={experiment.id}
|
||||
backtestId={experiment.backtestId}
|
||||
previewHash={experiment.previewHash}
|
||||
strategyOrigin={experiment.preview.request.strategy.origin}
|
||||
experimentCancelled={experiment.cancelRequested}
|
||||
trial={trial}
|
||||
disabled={mutating || loading}
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ export function ChronologicalValidationPreflight({
|
|||
backtestId,
|
||||
name,
|
||||
grid,
|
||||
candidate,
|
||||
disabled,
|
||||
eligible,
|
||||
onDirty,
|
||||
|
|
@ -44,6 +45,7 @@ export function ChronologicalValidationPreflight({
|
|||
backtestId: string;
|
||||
name: string;
|
||||
grid: string;
|
||||
candidate?: ChronologicalValidationSubmission['candidate'];
|
||||
disabled: boolean;
|
||||
eligible: boolean;
|
||||
onDirty: (dirty: boolean) => void;
|
||||
|
|
@ -72,7 +74,15 @@ export function ChronologicalValidationPreflight({
|
|||
const request = useRef<AbortController | null>(null);
|
||||
const pending = useRef(false);
|
||||
const alive = useRef(false);
|
||||
const identity = JSON.stringify({ backtestId, name, grid, windows, disabled, eligible });
|
||||
const identity = JSON.stringify({
|
||||
backtestId,
|
||||
name,
|
||||
grid,
|
||||
candidate,
|
||||
windows,
|
||||
disabled,
|
||||
eligible,
|
||||
});
|
||||
const currentIdentity = useRef(identity);
|
||||
currentIdentity.current = identity;
|
||||
const preview =
|
||||
|
|
@ -123,6 +133,7 @@ export function ChronologicalValidationPreflight({
|
|||
backtestId,
|
||||
name,
|
||||
grid: JSON.parse(grid),
|
||||
...(candidate ? { candidate } : {}),
|
||||
recipe: parseValidationWindows(windows),
|
||||
});
|
||||
const value = await chronologicalValidationApi.preview(input, controller.signal);
|
||||
|
|
@ -325,7 +336,9 @@ export function ChronologicalValidationPreflight({
|
|||
</p>
|
||||
<p>
|
||||
Input checks only. Warmup sufficiency is not evidence of profitability or statistical
|
||||
adequacy. Only deterministic, unfitted strategies with zero label horizon are supported.
|
||||
adequacy. Built-in strategies use the declared unfitted model. Candidate warmup is
|
||||
author-declared and candidate behavior is unverified; fitting and nonzero label horizons
|
||||
have no supported validation contract.
|
||||
</p>
|
||||
<div className="grid gap-3 lg:grid-cols-3">
|
||||
{preview.partitions.map(part => (
|
||||
|
|
|
|||
|
|
@ -13,6 +13,10 @@ import {
|
|||
} from '@stock-bot/stock-config/experiments';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { backtestApiV2, type Backtest } from '@/features/backtest/services/backtestApiV2';
|
||||
import {
|
||||
StrategySelection,
|
||||
type CatalogSelection,
|
||||
} from '@/features/strategies/components/StrategySelection';
|
||||
import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning';
|
||||
import {
|
||||
experimentApi,
|
||||
|
|
@ -94,6 +98,19 @@ export function ExperimentEditor({
|
|||
const [backtestId, setBacktestId] = useState(initialBacktestId);
|
||||
const [name, setName] = useState('');
|
||||
const [grid, setGrid] = useState('{}');
|
||||
const [useCandidate, setUseCandidate] = useState(false);
|
||||
const [candidateSelection, setCandidateSelection] = useState<CatalogSelection>({});
|
||||
const [candidateValid, setCandidateValid] = useState(false);
|
||||
const candidateRevision = useRef(0);
|
||||
const candidateValidity = useRef(false);
|
||||
const renderedCandidateRevision = candidateRevision.current;
|
||||
const candidate =
|
||||
useCandidate && candidateSelection.strategyVersionId
|
||||
? {
|
||||
versionId: candidateSelection.strategyVersionId,
|
||||
parameters: candidateSelection.strategyParameters ?? {},
|
||||
}
|
||||
: undefined;
|
||||
const [backtests, setBacktests] = useState<Backtest[]>([]);
|
||||
const [templateLoading, setTemplateLoading] = useState(true);
|
||||
const [templateError, setTemplateError] = useState('');
|
||||
|
|
@ -113,6 +130,7 @@ export function ExperimentEditor({
|
|||
walkForwardDirty ||
|
||||
Boolean(
|
||||
name ||
|
||||
useCandidate ||
|
||||
grid !== '{}' ||
|
||||
backtestId !== initialBacktestId ||
|
||||
mode !== 'parameters' ||
|
||||
|
|
@ -179,7 +197,12 @@ export function ExperimentEditor({
|
|||
change();
|
||||
};
|
||||
const prepare = async () => {
|
||||
if (submissionOwner.current || previewLoading) {
|
||||
if (
|
||||
submissionOwner.current ||
|
||||
previewLoading ||
|
||||
candidateRevision.current !== renderedCandidateRevision ||
|
||||
(useCandidate && !candidateValid)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const current = ++generation.current;
|
||||
|
|
@ -194,11 +217,21 @@ export function ExperimentEditor({
|
|||
const value =
|
||||
modeRef.current === 'cost-sensitivity'
|
||||
? await experimentApi.costPreview(
|
||||
costSensitivityInputSchema.parse({ backtestId, name, scenarios }),
|
||||
costSensitivityInputSchema.parse({
|
||||
backtestId,
|
||||
name,
|
||||
scenarios,
|
||||
...(candidate ? { candidate } : {}),
|
||||
}),
|
||||
controller.signal
|
||||
)
|
||||
: await experimentApi.preview(
|
||||
experimentInputSchema.parse({ backtestId, name, grid: JSON.parse(grid) }),
|
||||
experimentInputSchema.parse({
|
||||
backtestId,
|
||||
name,
|
||||
grid: JSON.parse(grid),
|
||||
...(candidate ? { candidate } : {}),
|
||||
}),
|
||||
controller.signal
|
||||
);
|
||||
if (alive.current && current === generation.current) {
|
||||
|
|
@ -356,6 +389,49 @@ export function ExperimentEditor({
|
|||
Load more backtests
|
||||
</Button>
|
||||
)}
|
||||
<label className="block text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={useCandidate}
|
||||
disabled={Boolean(lockedBy)}
|
||||
onChange={event => {
|
||||
if (submissionOwner.current) {
|
||||
return;
|
||||
}
|
||||
candidateRevision.current++;
|
||||
invalidate(() => setUseCandidate(event.target.checked));
|
||||
}}
|
||||
/>{' '}
|
||||
Use an isolated candidate version
|
||||
</label>
|
||||
{useCandidate && (
|
||||
<section aria-label="Candidate experiment strategy" className="space-y-2">
|
||||
<p className="text-sm">
|
||||
Select an immutable candidate and validate its base parameters. The saved backtest
|
||||
supplies the dataset, capital and financial policy. Preview checks candidate
|
||||
eligibility.
|
||||
</p>
|
||||
<StrategySelection
|
||||
value={candidateSelection}
|
||||
onChange={value => {
|
||||
if (submissionOwner.current) {
|
||||
return;
|
||||
}
|
||||
candidateRevision.current++;
|
||||
invalidate(() => setCandidateSelection(value));
|
||||
}}
|
||||
onValidityChange={valid => {
|
||||
if (submissionOwner.current || valid === candidateValidity.current) {
|
||||
return;
|
||||
}
|
||||
candidateValidity.current = valid;
|
||||
candidateRevision.current++;
|
||||
invalidate(() => setCandidateValid(valid));
|
||||
}}
|
||||
disabled={Boolean(lockedBy)}
|
||||
/>
|
||||
</section>
|
||||
)}
|
||||
<label className="block text-sm">
|
||||
Experiment type
|
||||
<select
|
||||
|
|
@ -469,6 +545,7 @@ export function ExperimentEditor({
|
|||
disabled={
|
||||
Boolean(lockedBy) ||
|
||||
previewLoading ||
|
||||
(useCandidate && !candidateValid) ||
|
||||
!backtests.some(item => item.id === backtestId) ||
|
||||
!name.trim()
|
||||
}
|
||||
|
|
@ -514,8 +591,13 @@ export function ExperimentEditor({
|
|||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
candidate={candidate}
|
||||
disabled={mode !== 'parameters' || (lockedBy !== null && lockedBy !== 'chronological')}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
eligible={
|
||||
!templateLoading &&
|
||||
(!useCandidate || candidateValid) &&
|
||||
backtests.some(item => item.id === backtestId)
|
||||
}
|
||||
onDirty={setValidationDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
|
|
@ -524,8 +606,13 @@ export function ExperimentEditor({
|
|||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
candidate={candidate}
|
||||
disabled={mode !== 'parameters' || (lockedBy !== null && lockedBy !== 'walk-forward')}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
eligible={
|
||||
!templateLoading &&
|
||||
(!useCandidate || candidateValid) &&
|
||||
backtests.some(item => item.id === backtestId)
|
||||
}
|
||||
onDirty={setWalkForwardDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ export function ExperimentInputs({ preview }: { preview: WorkbenchExperimentPrev
|
|||
<dd>{new Date(dataset.bounds.warmupStart).toISOString()}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Initial capital / owner budget (USD)</dt>
|
||||
<dt>Initial capital / strategy sizing budget (USD)</dt>
|
||||
<dd>
|
||||
{request.policy.matching.risk.ledger.initialCapital} /{' '}
|
||||
{request.strategy.selection.ownerBudget}
|
||||
|
|
@ -50,6 +50,27 @@ export function ExperimentInputs({ preview }: { preview: WorkbenchExperimentPrev
|
|||
<dd>{request.strategy.selection.seed}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
{request.strategy.origin === 'candidate' && (
|
||||
<section aria-label="Isolated candidate execution" className="space-y-1 break-all">
|
||||
<p>
|
||||
Isolated TypeScript candidate ·{' '}
|
||||
{request.strategy.reviewId
|
||||
? `Review ${request.strategy.reviewId}`
|
||||
: 'Unreviewed research candidate'}
|
||||
</p>
|
||||
<p>
|
||||
Author-declared warmup: {request.strategy.package.execution?.warmupBars} bars. Arbitrary
|
||||
code may ignore the seeded RNG; reproduction compares actual economic results.
|
||||
</p>
|
||||
<p>Sandbox image: {request.strategy.execution.imageId}</p>
|
||||
<p>
|
||||
Limits: {request.strategy.execution.profile.limits.memoryBytes / 1048576} MiB memory,{' '}
|
||||
{request.strategy.execution.profile.limits.cpuQuota} CPU,{' '}
|
||||
{request.strategy.execution.profile.limits.wallMs / 1000} seconds per container; an
|
||||
agent attempt deadline may be shorter.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
<p>
|
||||
{costs
|
||||
? 'Template cost diagnostics only. Strategy parameters, dataset, seed, capital, half-spread and risk limits remain fixed; each fee/slippage scenario executes independently. No strategy selection or ranking is performed.'
|
||||
|
|
@ -97,6 +118,13 @@ export function ExperimentInputs({ preview }: { preview: WorkbenchExperimentPrev
|
|||
strategy: {
|
||||
versionId: request.strategy.versionId,
|
||||
reviewId: request.strategy.reviewId,
|
||||
origin: request.strategy.origin,
|
||||
...(request.strategy.origin === 'candidate'
|
||||
? {
|
||||
execution: request.strategy.execution,
|
||||
declaredWarmup: request.strategy.package.execution?.warmupBars,
|
||||
}
|
||||
: {}),
|
||||
selection: request.strategy.selection,
|
||||
artifactHash: request.strategy.package.artifact.sha256,
|
||||
dependencyLockHash: request.strategy.package.dependencyLock.sha256,
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ interface Props {
|
|||
experimentId: string;
|
||||
backtestId: string;
|
||||
previewHash: string;
|
||||
strategyOrigin?: 'builtin' | 'candidate';
|
||||
experimentCancelled: boolean;
|
||||
trial: ExperimentTrial;
|
||||
disabled: boolean;
|
||||
|
|
@ -39,6 +40,7 @@ export function ExperimentTrialRecovery({
|
|||
experimentId,
|
||||
backtestId,
|
||||
previewHash,
|
||||
strategyOrigin = 'builtin',
|
||||
experimentCancelled,
|
||||
trial,
|
||||
disabled,
|
||||
|
|
@ -92,7 +94,7 @@ export function ExperimentTrialRecovery({
|
|||
setHistoryLoading(true);
|
||||
setHistoryError('');
|
||||
void experimentApi
|
||||
.retryHistory(experimentId, trial.runId, trial.trialKey, controller.signal)
|
||||
.retryHistory(experimentId, trial.runId, trial.trialKey, controller.signal, strategyOrigin)
|
||||
.then(value => {
|
||||
if (current) {
|
||||
setHistory(value);
|
||||
|
|
@ -112,7 +114,15 @@ export function ExperimentTrialRecovery({
|
|||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [experimentId, trial.runId, trial.trialKey, trial.retryCount, historyOpen, historyReload]);
|
||||
}, [
|
||||
experimentId,
|
||||
trial.runId,
|
||||
trial.trialKey,
|
||||
trial.retryCount,
|
||||
historyOpen,
|
||||
historyReload,
|
||||
strategyOrigin,
|
||||
]);
|
||||
const review = () => {
|
||||
if (disabled || !freshAllowed || !trial.runId || intentRef.current) {
|
||||
return;
|
||||
|
|
@ -323,7 +333,7 @@ export function ExperimentTrialRecovery({
|
|||
</div>
|
||||
<div>
|
||||
<dt>Approval at retry admission</dt>
|
||||
<dd>{item.reviewId}</dd>
|
||||
<dd>{item.reviewId ?? 'Unreviewed isolated candidate'}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</article>
|
||||
|
|
|
|||
|
|
@ -33,6 +33,7 @@ export function WalkForwardPreflight({
|
|||
backtestId,
|
||||
name,
|
||||
grid,
|
||||
candidate,
|
||||
disabled,
|
||||
eligible,
|
||||
onDirty,
|
||||
|
|
@ -42,6 +43,7 @@ export function WalkForwardPreflight({
|
|||
backtestId: string;
|
||||
name: string;
|
||||
grid: string;
|
||||
candidate?: WalkForwardSubmission['candidate'];
|
||||
disabled: boolean;
|
||||
eligible: boolean;
|
||||
onDirty: (value: boolean) => void;
|
||||
|
|
@ -72,7 +74,15 @@ export function WalkForwardPreflight({
|
|||
posting = useRef(false),
|
||||
generation = useRef(0),
|
||||
read = useRef<AbortController | null>(null);
|
||||
const identity = JSON.stringify({ backtestId, name, grid, windows, disabled, eligible }),
|
||||
const identity = JSON.stringify({
|
||||
backtestId,
|
||||
name,
|
||||
grid,
|
||||
candidate,
|
||||
windows,
|
||||
disabled,
|
||||
eligible,
|
||||
}),
|
||||
currentIdentity = useRef(identity);
|
||||
currentIdentity.current = identity;
|
||||
const preview =
|
||||
|
|
@ -125,6 +135,7 @@ export function WalkForwardPreflight({
|
|||
backtestId,
|
||||
name,
|
||||
grid: JSON.parse(grid),
|
||||
...(candidate ? { candidate } : {}),
|
||||
windows: windows.map((window, index) =>
|
||||
parseValidationWindows(window, `Window ${index + 1} `)
|
||||
),
|
||||
|
|
|
|||
|
|
@ -1,131 +1,18 @@
|
|||
import { z } from 'zod';
|
||||
import { type ChronologicalValidationInput } from '@stock-bot/stock-config/chronological-validation';
|
||||
import {
|
||||
chronologicalValidationInputSchema,
|
||||
chronologicalValidationPolicy,
|
||||
type ChronologicalValidationInput,
|
||||
type ChronologicalValidationPreview,
|
||||
type ValidationPartitionPreview,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
invalidValidationPreview as invalid,
|
||||
parseChronologicalValidationPreview,
|
||||
type ChronologicalValidationPreviewView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
import { parseExperimentPreview, type ExperimentPreviewView } from './experimentApi';
|
||||
|
||||
export type ValidationPartitionView = Omit<ValidationPartitionPreview, 'dataset'> & {
|
||||
dataset: ExperimentPreviewView['dataset'];
|
||||
};
|
||||
export type ChronologicalValidationPreviewView = Omit<
|
||||
ChronologicalValidationPreview,
|
||||
'source' | 'partitions'
|
||||
> & {
|
||||
source: ExperimentPreviewView;
|
||||
partitions: [ValidationPartitionView, ValidationPartitionView, ValidationPartitionView];
|
||||
};
|
||||
const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const counts = z.object({
|
||||
totalBars: counter,
|
||||
availableWarmup: counter,
|
||||
admittedWarmup: counter,
|
||||
ignoredLateWarmup: counter,
|
||||
availableEvaluation: counter,
|
||||
terminalAtEnd: counter,
|
||||
unavailableAtEnd: counter,
|
||||
});
|
||||
const partition = z.object({
|
||||
phase: z.enum(['train', 'validation', 'test']),
|
||||
dataset: z.unknown(),
|
||||
request: z.unknown(),
|
||||
counts,
|
||||
requiredWarmup: counter.positive(),
|
||||
warnings: z.array(z.string()),
|
||||
});
|
||||
const prepared = z.object({
|
||||
version: z.literal('chronological-validation-preview/v1'),
|
||||
execution: z.literal('preview-only'),
|
||||
previewHash: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
input: chronologicalValidationInputSchema,
|
||||
source: z.unknown(),
|
||||
policy: z.unknown(),
|
||||
partitions: z.tuple([partition, partition, partition]),
|
||||
});
|
||||
const same = (left: unknown, right: unknown) =>
|
||||
canonicalStrategyJson(left) === canonicalStrategyJson(right);
|
||||
const invalid = () =>
|
||||
new Error(
|
||||
'The chronological validation preview could not be verified. Preview the current inputs again.'
|
||||
);
|
||||
export {
|
||||
parseChronologicalValidationPreview,
|
||||
type ChronologicalValidationPreviewView,
|
||||
type ValidationPartitionView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
|
||||
export function parseChronologicalValidationPreview(
|
||||
body: unknown,
|
||||
input: ChronologicalValidationInput
|
||||
): ChronologicalValidationPreviewView {
|
||||
const value = prepared.parse(z.object({ preview: z.unknown() }).parse(body).preview);
|
||||
const source = parseExperimentPreview(value.source);
|
||||
const { recipe: _recipe, ...sourceInput } = input;
|
||||
if (
|
||||
!same(value.input, input) ||
|
||||
!same(source.input, sourceInput) ||
|
||||
!same(value.policy, chronologicalValidationPolicy)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const phases = ['train', 'validation', 'test'] as const;
|
||||
const partitions = value.partitions.map((part, index): ValidationPartitionView => {
|
||||
const phase = phases[index];
|
||||
if (!phase || part.phase !== phase) {
|
||||
throw invalid();
|
||||
}
|
||||
const decoded = parseExperimentPreview({
|
||||
...source,
|
||||
dataset: part.dataset,
|
||||
request: part.request,
|
||||
});
|
||||
const { request, dataset } = decoded;
|
||||
const expected = {
|
||||
...source.request,
|
||||
datasetHash: dataset.hash,
|
||||
policy: {
|
||||
...source.request.policy,
|
||||
risk_boundaries: request.policy.risk_boundaries,
|
||||
matching: {
|
||||
...source.request.policy.matching,
|
||||
risk: {
|
||||
...source.request.policy.matching.risk,
|
||||
ledger: {
|
||||
...source.request.policy.matching.risk.ledger,
|
||||
riskSession: request.policy.matching.risk.ledger.riskSession,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
const measured = part.counts;
|
||||
const metadata = (manifest: ExperimentPreviewView['dataset']) => {
|
||||
const { hash: _hash, bounds: _bounds, barCount: _barCount, ...retained } = manifest;
|
||||
return retained;
|
||||
};
|
||||
if (
|
||||
!same(request, expected) ||
|
||||
!same(dataset.bounds, input.recipe[phase]) ||
|
||||
!same(metadata(dataset), metadata(source.dataset)) ||
|
||||
measured.totalBars !== dataset.barCount ||
|
||||
dataset.bounds.warmupStart < source.dataset.bounds.warmupStart ||
|
||||
dataset.bounds.tradeStart < source.dataset.bounds.tradeStart ||
|
||||
dataset.bounds.tradeEnd > source.dataset.bounds.tradeEnd ||
|
||||
measured.totalBars !==
|
||||
measured.availableWarmup +
|
||||
measured.availableEvaluation +
|
||||
measured.terminalAtEnd +
|
||||
measured.unavailableAtEnd ||
|
||||
measured.availableWarmup !== measured.admittedWarmup + measured.ignoredLateWarmup ||
|
||||
measured.admittedWarmup < part.requiredWarmup ||
|
||||
measured.availableEvaluation === 0
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...part, phase, request, dataset };
|
||||
}) as [ValidationPartitionView, ValidationPartitionView, ValidationPartitionView];
|
||||
return { ...value, source, policy: chronologicalValidationPolicy, partitions };
|
||||
}
|
||||
export const chronologicalValidationApi = {
|
||||
async preview(
|
||||
input: ChronologicalValidationInput,
|
||||
|
|
|
|||
|
|
@ -1,276 +1,30 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
chronologicalValidationInputSchema,
|
||||
type ChronologicalValidationActionReceipt,
|
||||
type ChronologicalValidationDetail,
|
||||
type ChronologicalValidationFinalizationInput,
|
||||
type ChronologicalValidationSelectionInput,
|
||||
type ChronologicalValidationSubmission,
|
||||
type ChronologicalValidationSummary,
|
||||
type ValidationResultEvidence,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import { researchActorSchema } from '@stock-bot/stock-config/research';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
invalidValidationResponse as invalid,
|
||||
parseValidationDetail,
|
||||
validationReceiptSchema as receipt,
|
||||
sameValidationInput as same,
|
||||
validationSummarySchema as summary,
|
||||
ValidationApiError,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
import {
|
||||
parseChronologicalValidationPreview,
|
||||
type ChronologicalValidationPreviewView,
|
||||
} from './chronologicalValidationApi';
|
||||
import {
|
||||
experimentMetricsSchema,
|
||||
parseExperimentDetail,
|
||||
type ExperimentDetailView,
|
||||
} from './experimentApi';
|
||||
|
||||
export type ValidationDetailView = Omit<ChronologicalValidationDetail, 'preview' | 'phases'> & {
|
||||
preview: ChronologicalValidationPreviewView;
|
||||
phases: Array<{
|
||||
phase: 'train' | 'validation' | 'test';
|
||||
status: 'not-admitted' | 'admitted' | 'missing';
|
||||
experimentId: string | null;
|
||||
experiment: ExperimentDetailView | null;
|
||||
}>;
|
||||
};
|
||||
export class ValidationApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number | null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
get ambiguous() {
|
||||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/),
|
||||
uuid = z.string().uuid(),
|
||||
count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const candidate = z.object({
|
||||
index: count,
|
||||
trialKey: hash,
|
||||
parameters: z.record(z.union([z.string(), z.number().finite(), z.boolean()])),
|
||||
});
|
||||
const actor = researchActorSchema;
|
||||
const summary = z.object({
|
||||
id: uuid,
|
||||
name: z.string().min(1),
|
||||
backtestId: uuid,
|
||||
createdAt: z.string().min(1),
|
||||
cancelRequested: z.boolean(),
|
||||
previewHash: hash,
|
||||
trainingCandidateCount: count.min(1).max(100),
|
||||
stage: z.enum(['training', 'holdouts', 'reported']),
|
||||
});
|
||||
export const validationEvidenceSchema = z.object({
|
||||
phase: z.enum(['train', 'validation', 'test']),
|
||||
experimentId: uuid,
|
||||
runId: uuid,
|
||||
sourceCandidateIndex: count,
|
||||
trialKey: hash,
|
||||
parameters: candidate.shape.parameters,
|
||||
datasetHash: hash,
|
||||
requestHash: hash,
|
||||
economicHash: hash,
|
||||
metrics: experimentMetricsSchema,
|
||||
unavailable: z.record(z.string()),
|
||||
completePeriodCount: count,
|
||||
periodicSampleCount: count,
|
||||
fillCount: count,
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const selection = z.object({
|
||||
version: z.literal('chronological-validation-selection/v1'),
|
||||
id: uuid,
|
||||
validationId: uuid,
|
||||
previewHash: hash,
|
||||
selectionHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: actor,
|
||||
reviewId: uuid,
|
||||
winner: candidate,
|
||||
training: z.array(validationEvidenceSchema).min(1).max(100),
|
||||
holdoutExperimentIds: z.object({ validation: uuid, test: uuid }),
|
||||
});
|
||||
const report = z.object({
|
||||
version: z.literal('chronological-validation-report/v1'),
|
||||
id: uuid,
|
||||
validationId: uuid,
|
||||
previewHash: hash,
|
||||
selectionHash: hash,
|
||||
reportHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: actor,
|
||||
reset: z.literal('initial-capital-empty-positions'),
|
||||
training: z.array(validationEvidenceSchema).min(1).max(100),
|
||||
validation: validationEvidenceSchema,
|
||||
test: validationEvidenceSchema,
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const capability = z.object({ available: z.boolean(), reason: z.string().nullable() });
|
||||
const phase = z.object({
|
||||
phase: z.enum(['train', 'validation', 'test']),
|
||||
status: z.enum(['not-admitted', 'admitted', 'missing']),
|
||||
experimentId: uuid.nullable(),
|
||||
experiment: z.unknown(),
|
||||
});
|
||||
const detail = summary.extend({
|
||||
preview: z.unknown(),
|
||||
phases: z.tuple([phase, phase, phase]),
|
||||
selection: selection.nullable(),
|
||||
report: report.nullable(),
|
||||
actions: z.object({ select: capability, finalize: capability }),
|
||||
});
|
||||
const receipt = z.object({
|
||||
id: uuid,
|
||||
validationId: uuid,
|
||||
operation: z.enum(['select-and-admit-holdouts', 'finalize-report']),
|
||||
previewHash: hash,
|
||||
selectionHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: actor,
|
||||
});
|
||||
const same = (a: unknown, b: unknown) => canonicalStrategyJson(a) === canonicalStrategyJson(b);
|
||||
const invalid = () =>
|
||||
new ValidationApiError(
|
||||
'The saved validation response could not be verified. Refresh or retry the same request.',
|
||||
null
|
||||
);
|
||||
export function parseValidationDetail(raw: unknown): ValidationDetailView {
|
||||
const value = detail.parse(raw);
|
||||
const rawPreview = z.object({ input: chronologicalValidationInputSchema }).parse(value.preview);
|
||||
const preview = parseChronologicalValidationPreview({ preview: value.preview }, rawPreview.input);
|
||||
if (
|
||||
value.backtestId !== preview.input.backtestId ||
|
||||
value.name !== preview.input.name ||
|
||||
value.previewHash !== preview.previewHash ||
|
||||
value.trainingCandidateCount !== preview.source.candidates.length ||
|
||||
(value.stage === 'training') !== (value.selection === null) ||
|
||||
(value.stage === 'reported') !== (value.report !== null)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const phases = value.phases.map((item, index) => {
|
||||
const name = (['train', 'validation', 'test'] as const)[index];
|
||||
if (item.phase !== name || (item.status === 'admitted') !== (item.experiment !== null)) {
|
||||
throw invalid();
|
||||
}
|
||||
const expectedId =
|
||||
name === 'train'
|
||||
? value.id
|
||||
: (value.selection?.holdoutExperimentIds[name ?? 'validation'] ?? null);
|
||||
if (
|
||||
item.experimentId !== expectedId ||
|
||||
(item.status === 'not-admitted') !== (expectedId === null)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const experiment = item.experiment === null ? null : parseExperimentDetail(item.experiment);
|
||||
if (experiment) {
|
||||
const prototype = preview.partitions[index];
|
||||
const parameters =
|
||||
name === 'train'
|
||||
? prototype?.request.strategy.selection.parameters
|
||||
: value.selection?.winner.parameters;
|
||||
if (!prototype || !parameters) {
|
||||
throw invalid();
|
||||
}
|
||||
const expectedRequest = {
|
||||
...prototype.request,
|
||||
strategy: {
|
||||
...prototype.request.strategy,
|
||||
reviewId:
|
||||
name === 'train' ? prototype.request.strategy.reviewId : value.selection?.reviewId,
|
||||
selection: { ...prototype.request.strategy.selection, parameters },
|
||||
},
|
||||
};
|
||||
const expectedCandidates =
|
||||
name === 'train' ? preview.source.candidates : [{ ...value.selection?.winner, index: 0 }];
|
||||
if (
|
||||
experiment.id !== expectedId ||
|
||||
experiment.backtestId !== value.backtestId ||
|
||||
!same(experiment.preview.request, expectedRequest) ||
|
||||
!same(experiment.preview.dataset, prototype.dataset) ||
|
||||
!same(experiment.preview.candidates, expectedCandidates) ||
|
||||
!same(experiment.preview.input.grid, name === 'train' ? preview.input.grid : {})
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
return { ...item, experiment };
|
||||
});
|
||||
const validateEvidence = (
|
||||
item: z.infer<typeof validationEvidenceSchema>,
|
||||
expectedPhase: 'train' | 'validation' | 'test'
|
||||
) => {
|
||||
const index = ['train', 'validation', 'test'].indexOf(expectedPhase);
|
||||
const candidateValue = preview.source.candidates[item.sourceCandidateIndex];
|
||||
const phaseValue = phases[index];
|
||||
const trial = phaseValue?.experiment?.trials.find(
|
||||
trial => trial.runId === item.runId && trial.trialKey === item.trialKey
|
||||
);
|
||||
if (
|
||||
!candidateValue ||
|
||||
!phaseValue ||
|
||||
item.phase !== expectedPhase ||
|
||||
item.experimentId !== phaseValue.experimentId ||
|
||||
item.trialKey !== candidateValue.trialKey ||
|
||||
!same(item.parameters, candidateValue.parameters) ||
|
||||
item.datasetHash !== preview.partitions[index]?.dataset.hash ||
|
||||
(expectedPhase !== 'train' && item.sourceCandidateIndex !== value.selection?.winner.index) ||
|
||||
(phaseValue.experiment &&
|
||||
(!trial ||
|
||||
trial.status !== 'completed' ||
|
||||
!trial.comparable ||
|
||||
!same(trial.metrics, item.metrics) ||
|
||||
!same(trial.unavailable, item.unavailable) ||
|
||||
!same(trial.limitations, item.limitations)))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
};
|
||||
if (value.selection) {
|
||||
const chosen = value.selection;
|
||||
if (
|
||||
chosen.validationId !== value.id ||
|
||||
chosen.previewHash !== value.previewHash ||
|
||||
!same(chosen.winner, preview.source.candidates[chosen.winner.index]) ||
|
||||
chosen.training.length !== value.trainingCandidateCount ||
|
||||
chosen.training.some((item, index) => item.sourceCandidateIndex !== index) ||
|
||||
new Set([value.id, chosen.holdoutExperimentIds.validation, chosen.holdoutExperimentIds.test])
|
||||
.size !== 3
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
for (const item of chosen.training) {
|
||||
validateEvidence(item, 'train');
|
||||
if (item.metrics.totalReturn === null) {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (value.report) {
|
||||
const saved = value.report;
|
||||
if (
|
||||
!value.selection ||
|
||||
saved.validationId !== value.id ||
|
||||
saved.previewHash !== value.previewHash ||
|
||||
saved.selectionHash !== value.selection.selectionHash ||
|
||||
!same(saved.training, value.selection.training)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
validateEvidence(saved.validation, 'validation');
|
||||
validateEvidence(saved.test, 'test');
|
||||
}
|
||||
if (
|
||||
(value.actions.select.available && (value.selection || value.cancelRequested)) ||
|
||||
(value.actions.finalize.available &&
|
||||
(!value.selection || value.report || value.cancelRequested))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...value, preview, phases } as ValidationDetailView;
|
||||
}
|
||||
export {
|
||||
parseValidationDetail,
|
||||
ValidationApiError,
|
||||
validationEvidenceSchema,
|
||||
type ValidationDetailView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
export type { ValidationResultEvidence };
|
||||
|
||||
const envelope = (body: unknown, key: string) => z.record(z.unknown()).parse(body)[key];
|
||||
async function request<T>(
|
||||
path: string,
|
||||
|
|
@ -386,4 +140,3 @@ export const chronologicalValidationDurableApi = {
|
|||
return value;
|
||||
}),
|
||||
};
|
||||
export type { ValidationResultEvidence };
|
||||
|
|
|
|||
|
|
@ -1,341 +1,46 @@
|
|||
import { z } from 'zod';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
costScenarioSchema,
|
||||
costSensitivityInputSchema,
|
||||
type CostSensitivityDetail,
|
||||
type CostSensitivityInput,
|
||||
type CostSensitivityPreview,
|
||||
type CostSensitivitySubmission,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import {
|
||||
experimentInputSchema,
|
||||
experimentRetrySchema,
|
||||
MAX_EXPERIMENT_TRIALS,
|
||||
type ExperimentDetail,
|
||||
type ExperimentInput,
|
||||
type ExperimentPreview,
|
||||
type ExperimentRetryInput,
|
||||
type ExperimentSubmission,
|
||||
type ExperimentSummary,
|
||||
type ExperimentTrialRetry,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
import { researchActorSchema } from '@stock-bot/stock-config/research';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
ExperimentApiError,
|
||||
invalidExperimentResponse as invalid,
|
||||
parseCostSensitivityPreview,
|
||||
parseExperimentDetail,
|
||||
parseExperimentPreview,
|
||||
parseExperimentSummary as parseSummary,
|
||||
parseWorkbenchExperimentDetail,
|
||||
experimentRetryReceiptSchema as retryReceipt,
|
||||
sameExperimentInput as same,
|
||||
type ExperimentRetryTarget,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
|
||||
export class ExperimentApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number | null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
get ambiguous() {
|
||||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/);
|
||||
const count = z.number().int().nonnegative().max(MAX_EXPERIMENT_TRIALS);
|
||||
const counter = z.number().int().nonnegative().max(2147483647);
|
||||
const scalar = z.union([z.string(), z.number().finite(), z.boolean()]);
|
||||
const candidate = z
|
||||
.object({
|
||||
index: count,
|
||||
trialKey: hash,
|
||||
parameters: z.record(scalar),
|
||||
})
|
||||
.strict();
|
||||
const statuses = ['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'] as const;
|
||||
const counts = z.object({
|
||||
pending: count,
|
||||
running: count,
|
||||
paused: count,
|
||||
completed: count,
|
||||
failed: count,
|
||||
cancelled: count,
|
||||
});
|
||||
const summary = z.object({
|
||||
kind: z.enum(['parameters', 'cost-sensitivity']).optional(),
|
||||
id: z.string().uuid(),
|
||||
name: z.string().min(1),
|
||||
backtestId: z.string().uuid(),
|
||||
createdAt: z.string().min(1),
|
||||
cancelRequested: z.boolean(),
|
||||
trialCount: count.min(1),
|
||||
counts,
|
||||
datasetHash: hash,
|
||||
strategyVersionId: z.string().uuid(),
|
||||
previewHash: hash,
|
||||
});
|
||||
const timestamp = z.number().int().min(-8640000000000000).max(8640000000000000);
|
||||
const dataset = z
|
||||
.object({
|
||||
version: z.literal(2),
|
||||
hash,
|
||||
bounds: z.object({
|
||||
warmupStart: timestamp,
|
||||
tradeStart: timestamp,
|
||||
tradeEnd: timestamp,
|
||||
}),
|
||||
series: z.array(
|
||||
z.object({ id: z.string(), instrumentId: z.string(), interval: z.string() }).passthrough()
|
||||
),
|
||||
})
|
||||
.passthrough();
|
||||
/** Only the manifest fields consumed by this UI are structurally decoded here. */
|
||||
export type ExperimentPreviewView = Omit<ExperimentPreview, 'dataset'> & {
|
||||
dataset: z.infer<typeof dataset>;
|
||||
};
|
||||
export type ExperimentDetailView = Omit<ExperimentDetail, 'preview'> & {
|
||||
preview: ExperimentPreviewView;
|
||||
};
|
||||
export type CostSensitivityPreviewView = Omit<CostSensitivityPreview, 'dataset' | 'source'> & {
|
||||
dataset: ExperimentPreviewView['dataset'];
|
||||
source: ExperimentPreviewView;
|
||||
};
|
||||
export type WorkbenchExperimentPreviewView = ExperimentPreviewView | CostSensitivityPreviewView;
|
||||
export type CostSensitivityDetailView = Omit<CostSensitivityDetail, 'preview'> & {
|
||||
preview: CostSensitivityPreviewView;
|
||||
};
|
||||
export type WorkbenchExperimentDetailView = ExperimentDetailView | CostSensitivityDetailView;
|
||||
const preview = z
|
||||
.object({
|
||||
version: z.literal('research-experiment-preview/v1'),
|
||||
previewHash: hash,
|
||||
input: experimentInputSchema,
|
||||
request: canonicalRunRequestSchema,
|
||||
dataset,
|
||||
candidates: z.array(candidate).min(1).max(MAX_EXPERIMENT_TRIALS),
|
||||
})
|
||||
.strict();
|
||||
const metric = z.number().finite().nullable();
|
||||
export const experimentMetricsSchema = z.object({
|
||||
totalReturn: metric,
|
||||
cagr: metric,
|
||||
maxDrawdown: metric,
|
||||
exposureTime: metric,
|
||||
volatility: metric,
|
||||
downsideDeviation: metric,
|
||||
sharpeRatio: metric,
|
||||
sortinoRatio: metric,
|
||||
var95: metric,
|
||||
cvar95: metric,
|
||||
var99: metric,
|
||||
alpha: z.null(),
|
||||
beta: z.null(),
|
||||
informationRatio: z.null(),
|
||||
roundTripCount: z.null(),
|
||||
winRate: z.null(),
|
||||
profitFactor: z.null(),
|
||||
avgWin: z.null(),
|
||||
avgLoss: z.null(),
|
||||
});
|
||||
const trial = candidate.extend({
|
||||
runId: z.string().uuid().nullable(),
|
||||
attemptNumber: counter,
|
||||
retryCount: counter,
|
||||
status: z.enum([...statuses, 'missing']),
|
||||
progress: z.number().finite().min(0).max(100),
|
||||
cancelRequested: z.boolean(),
|
||||
error: z.string().nullable(),
|
||||
comparable: z.boolean(),
|
||||
diagnostic: z.string().nullable(),
|
||||
metrics: experimentMetricsSchema.nullable(),
|
||||
unavailable: z.record(z.string()).nullable(),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const detail = summary.extend({
|
||||
standalone: z.boolean().optional(),
|
||||
preview,
|
||||
trials: z.array(trial).max(MAX_EXPERIMENT_TRIALS),
|
||||
});
|
||||
const retryReceipt = z.object({
|
||||
id: z.string().uuid(),
|
||||
experimentId: z.string().uuid(),
|
||||
runId: z.string().uuid(),
|
||||
trialKey: hash,
|
||||
retryNumber: counter.min(1),
|
||||
previousAttemptNumber: counter,
|
||||
previousAttemptId: z.string().uuid().nullable(),
|
||||
error: z.string().nullable(),
|
||||
progress: z.number().finite().min(0).max(100),
|
||||
currentDate: z.string().nullable(),
|
||||
startedAt: z.string().nullable(),
|
||||
completedAt: z.string().nullable(),
|
||||
pausedAt: z.string().nullable(),
|
||||
failureUpdatedAt: z.string().min(1),
|
||||
recordedAt: z.string().min(1),
|
||||
principal: researchActorSchema,
|
||||
reviewId: z.string().uuid(),
|
||||
});
|
||||
/** Immutable source identity captured when the operator reviews a failed trial. */
|
||||
export interface ExperimentRetryTarget {
|
||||
experimentId: string;
|
||||
backtestId: string;
|
||||
previewHash: string;
|
||||
runId: string;
|
||||
trialKey: string;
|
||||
}
|
||||
const same = (left: unknown, right: unknown) =>
|
||||
canonicalStrategyJson(left) === canonicalStrategyJson(right);
|
||||
const invalid = () =>
|
||||
new ExperimentApiError(
|
||||
'The experiment response could not be verified. Refresh or retry the same submission.',
|
||||
null
|
||||
);
|
||||
export {
|
||||
ExperimentApiError,
|
||||
experimentMetricsSchema,
|
||||
parseCostSensitivityPreview,
|
||||
parseExperimentDetail,
|
||||
parseExperimentPreview,
|
||||
parseWorkbenchExperimentDetail,
|
||||
type CostSensitivityDetailView,
|
||||
type CostSensitivityPreviewView,
|
||||
type ExperimentDetailView,
|
||||
type ExperimentPreviewView,
|
||||
type ExperimentRetryTarget,
|
||||
type WorkbenchExperimentDetailView,
|
||||
type WorkbenchExperimentPreviewView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
|
||||
function parseSummary(value: unknown): ExperimentSummary {
|
||||
const parsed = summary.parse(value);
|
||||
if (Object.values(parsed.counts).reduce((sum, value) => sum + value, 0) > parsed.trialCount) {
|
||||
throw invalid();
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
export function parseExperimentPreview(value: unknown): ExperimentPreviewView {
|
||||
const parsed = preview.parse(value);
|
||||
if (
|
||||
parsed.input.backtestId !== parsed.request.backtestId ||
|
||||
parsed.dataset.hash !== parsed.request.datasetHash ||
|
||||
parsed.dataset.bounds.warmupStart > parsed.dataset.bounds.tradeStart ||
|
||||
parsed.dataset.bounds.tradeStart >= parsed.dataset.bounds.tradeEnd ||
|
||||
!parsed.dataset.series.some(
|
||||
series =>
|
||||
series.id === parsed.request.strategy.selection.seriesId &&
|
||||
series.instrumentId === parsed.request.strategy.selection.instrumentId
|
||||
) ||
|
||||
parsed.candidates.some((item, index) => item.index !== index) ||
|
||||
new Set(parsed.candidates.map(item => item.trialKey)).size !== parsed.candidates.length
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
// The server retains and verifies the complete manifest; the browser only renders its identity/window.
|
||||
return parsed;
|
||||
}
|
||||
const costCandidate = candidate.extend({ costs: costScenarioSchema });
|
||||
const costPreview = preview
|
||||
.omit({ version: true, input: true, candidates: true })
|
||||
.extend({
|
||||
version: z.literal('cost-sensitivity-preview/v1'),
|
||||
input: costSensitivityInputSchema,
|
||||
source: z.unknown(),
|
||||
candidates: z.array(costCandidate).min(2).max(MAX_EXPERIMENT_TRIALS),
|
||||
})
|
||||
.strict();
|
||||
const costDetail = summary.extend({
|
||||
kind: z.literal('cost-sensitivity'),
|
||||
standalone: z.boolean().optional(),
|
||||
preview: z.unknown(),
|
||||
trials: z.array(trial.extend({ costs: costScenarioSchema })).max(MAX_EXPERIMENT_TRIALS),
|
||||
});
|
||||
export function parseCostSensitivityPreview(raw: unknown): CostSensitivityPreviewView {
|
||||
const parsed = costPreview.parse(raw),
|
||||
source = parseExperimentPreview(parsed.source);
|
||||
const costs = [
|
||||
{
|
||||
feeRate: source.request.policy.matching.risk.feeRate,
|
||||
slippageRate: source.request.policy.matching.slippageRate,
|
||||
},
|
||||
...parsed.input.scenarios,
|
||||
];
|
||||
if (
|
||||
!same(source.input, {
|
||||
backtestId: parsed.input.backtestId,
|
||||
name: parsed.input.name,
|
||||
grid: {},
|
||||
}) ||
|
||||
source.candidates.length !== 1 ||
|
||||
!same(source.candidates[0]?.parameters, source.request.strategy.selection.parameters) ||
|
||||
!same(parsed.request, source.request) ||
|
||||
!same(parsed.dataset, source.dataset) ||
|
||||
parsed.candidates.length !== costs.length ||
|
||||
new Set(costs.map(canonicalStrategyJson)).size !== costs.length ||
|
||||
new Set(parsed.candidates.map(item => item.trialKey)).size !== costs.length ||
|
||||
parsed.candidates.some(
|
||||
(item, index) =>
|
||||
item.index !== index ||
|
||||
!same(item.parameters, source.request.strategy.selection.parameters) ||
|
||||
!same(item.costs, costs[index])
|
||||
)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...parsed, source } as CostSensitivityPreviewView;
|
||||
}
|
||||
function checkDetail(
|
||||
parsed: z.infer<typeof detail> | z.infer<typeof costDetail>,
|
||||
retained: WorkbenchExperimentPreviewView
|
||||
) {
|
||||
parseSummary(parsed);
|
||||
if (
|
||||
parsed.backtestId !== retained.input.backtestId ||
|
||||
parsed.name !== retained.input.name ||
|
||||
parsed.previewHash !== retained.previewHash ||
|
||||
parsed.datasetHash !== retained.request.datasetHash ||
|
||||
parsed.strategyVersionId !== retained.request.strategy.versionId ||
|
||||
parsed.trialCount !== retained.candidates.length ||
|
||||
parsed.trials.length !== parsed.trialCount
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const costKind = retained.version === 'cost-sensitivity-preview/v1';
|
||||
if (
|
||||
(costKind && parsed.kind !== 'cost-sensitivity') ||
|
||||
(!costKind && parsed.kind === 'cost-sensitivity')
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const runIds = new Set<string>();
|
||||
for (const [index, item] of parsed.trials.entries()) {
|
||||
const expected = retained.candidates[index];
|
||||
if (
|
||||
!expected ||
|
||||
item.index !== expected.index ||
|
||||
item.trialKey !== expected.trialKey ||
|
||||
!same(item.parameters, expected.parameters) ||
|
||||
(costKind &&
|
||||
(!('costs' in item) || !('costs' in expected) || !same(item.costs, expected.costs))) ||
|
||||
(item.status === 'missing') !== (item.runId === null) ||
|
||||
(item.status === 'missing' && (item.attemptNumber !== 0 || item.retryCount !== 0)) ||
|
||||
(item.comparable && (item.status !== 'completed' || !item.metrics || !item.unavailable)) ||
|
||||
(item.runId !== null && runIds.has(item.runId))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
if (item.runId) {
|
||||
runIds.add(item.runId);
|
||||
}
|
||||
}
|
||||
if (
|
||||
statuses.some(
|
||||
status =>
|
||||
parsed.counts[status] !== parsed.trials.filter(item => item.status === status).length
|
||||
)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
|
||||
return { ...parsed, preview: retained };
|
||||
}
|
||||
export function parseExperimentDetail(value: unknown): ExperimentDetailView {
|
||||
const parsed = detail.parse(value);
|
||||
return checkDetail(parsed, parseExperimentPreview(parsed.preview)) as ExperimentDetailView;
|
||||
}
|
||||
export function parseWorkbenchExperimentDetail(value: unknown): WorkbenchExperimentDetailView {
|
||||
const version = z.object({ preview: z.object({ version: z.string() }) }).parse(value)
|
||||
.preview.version;
|
||||
if (version === 'research-experiment-preview/v1') {
|
||||
return parseExperimentDetail(value);
|
||||
}
|
||||
if (version !== 'cost-sensitivity-preview/v1') {
|
||||
throw invalid();
|
||||
}
|
||||
const parsed = costDetail.parse(value);
|
||||
return checkDetail(
|
||||
parsed,
|
||||
parseCostSensitivityPreview(parsed.preview)
|
||||
) as CostSensitivityDetailView;
|
||||
}
|
||||
async function request<T>(
|
||||
path: string,
|
||||
init: RequestInit,
|
||||
|
|
@ -433,6 +138,8 @@ export const experimentApi = {
|
|||
experiment.id !== target.experimentId ||
|
||||
experiment.backtestId !== target.backtestId ||
|
||||
experiment.previewHash !== target.previewHash ||
|
||||
(receipt.reviewId === null &&
|
||||
experiment.preview.request.strategy.origin !== 'candidate') ||
|
||||
!current ||
|
||||
current.retryCount < receipt.retryNumber ||
|
||||
current.attemptNumber < receipt.previousAttemptNumber
|
||||
|
|
@ -443,7 +150,13 @@ export const experimentApi = {
|
|||
return { retry: receipt as ExperimentTrialRetry, experiment };
|
||||
}
|
||||
),
|
||||
retryHistory: (experimentId: string, runId: string, trialKey: string, signal?: AbortSignal) =>
|
||||
retryHistory: (
|
||||
experimentId: string,
|
||||
runId: string,
|
||||
trialKey: string,
|
||||
signal?: AbortSignal,
|
||||
origin: 'builtin' | 'candidate' = 'builtin'
|
||||
) =>
|
||||
request(
|
||||
`/${encodeURIComponent(experimentId)}/trials/${encodeURIComponent(runId)}/retries`,
|
||||
{ signal },
|
||||
|
|
@ -457,6 +170,7 @@ export const experimentApi = {
|
|||
item.experimentId !== experimentId ||
|
||||
item.runId !== runId ||
|
||||
item.trialKey !== trialKey ||
|
||||
(item.reviewId === null && origin !== 'candidate') ||
|
||||
item.retryNumber !== index + 1
|
||||
)
|
||||
) {
|
||||
|
|
|
|||
|
|
@ -1,119 +1,20 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
experimentComparisonDimensions,
|
||||
experimentComparisonInputSchema,
|
||||
type ExperimentComparison,
|
||||
type ExperimentComparisonInput,
|
||||
} from '@stock-bot/stock-config/experiment-comparison';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
import {
|
||||
parseWorkbenchExperimentDetail,
|
||||
type WorkbenchExperimentDetailView,
|
||||
} from './experimentApi';
|
||||
invalidExperimentComparison as invalid,
|
||||
parseExperimentComparison,
|
||||
type ExperimentComparisonView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
|
||||
export type ExperimentComparisonView = Omit<ExperimentComparison, 'experiments'> & {
|
||||
experiments: [WorkbenchExperimentDetailView, WorkbenchExperimentDetailView];
|
||||
};
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/),
|
||||
uuid = z.string().uuid();
|
||||
const schema = z.object({
|
||||
version: z.literal('experiment-comparison/v1'),
|
||||
policy: z.literal('retained-input-compatibility/v1'),
|
||||
selection: z.object({ leftId: uuid, rightId: uuid, referenceTrialKey: hash }).strict(),
|
||||
reference: z.object({
|
||||
experimentId: uuid,
|
||||
trialKey: hash,
|
||||
index: z.number().int().nonnegative(),
|
||||
runId: uuid.nullable(),
|
||||
summaryAvailable: z.boolean(),
|
||||
diagnostic: z.string().nullable(),
|
||||
}),
|
||||
experiments: z.tuple([z.unknown(), z.unknown()]),
|
||||
rows: z
|
||||
.array(
|
||||
z.object({
|
||||
experimentId: uuid,
|
||||
trialKey: hash,
|
||||
inputCompatibility: z.enum(['match', 'mismatch']),
|
||||
differences: z.array(z.enum(experimentComparisonDimensions)),
|
||||
summaryAvailable: z.boolean(),
|
||||
ready: z.boolean(),
|
||||
})
|
||||
)
|
||||
.min(2)
|
||||
.max(200),
|
||||
limitations: z.array(z.string().min(1)).min(1),
|
||||
});
|
||||
const invalid = () =>
|
||||
new Error('The experiment comparison could not be verified. Refresh the same selection.');
|
||||
export function parseComparisonQuery(params: URLSearchParams): ExperimentComparisonInput {
|
||||
const allowed = ['leftId', 'rightId', 'referenceTrialKey'];
|
||||
for (const key of params.keys()) {
|
||||
if (!allowed.includes(key) || params.getAll(key).length !== 1) {
|
||||
throw new Error(
|
||||
'Comparison URL requires two different experiment IDs and at most one reference trial key. Unknown or repeated query fields are not supported.'
|
||||
);
|
||||
}
|
||||
}
|
||||
const result = experimentComparisonInputSchema.safeParse(Object.fromEntries(params));
|
||||
if (!result.success) {
|
||||
throw new Error(
|
||||
'Select two different saved experiments to compare. The URL must contain valid leftId and rightId values and, when supplied, a valid referenceTrialKey.'
|
||||
);
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
export function parseExperimentComparison(
|
||||
raw: unknown,
|
||||
input: ExperimentComparisonInput
|
||||
): ExperimentComparisonView {
|
||||
const value = schema.parse(raw),
|
||||
experiments = value.experiments.map(
|
||||
parseWorkbenchExperimentDetail
|
||||
) as ExperimentComparisonView['experiments'];
|
||||
const [left, right] = experiments;
|
||||
const expectedKey = input.referenceTrialKey ?? left.trials[0]?.trialKey;
|
||||
const reference = left.trials.find(trial => trial.trialKey === expectedKey);
|
||||
if (
|
||||
!reference ||
|
||||
left.id !== input.leftId ||
|
||||
right.id !== input.rightId ||
|
||||
value.selection.leftId !== input.leftId ||
|
||||
value.selection.rightId !== input.rightId ||
|
||||
value.selection.referenceTrialKey !== expectedKey ||
|
||||
value.reference.experimentId !== left.id ||
|
||||
value.reference.trialKey !== reference.trialKey ||
|
||||
value.reference.index !== reference.index ||
|
||||
value.reference.runId !== reference.runId ||
|
||||
value.reference.summaryAvailable !== reference.comparable ||
|
||||
value.reference.diagnostic !== reference.diagnostic
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const expectedRows = experiments.flatMap(experiment =>
|
||||
experiment.trials.map(trial => ({ experimentId: experiment.id, trial }))
|
||||
);
|
||||
if (value.rows.length !== expectedRows.length) {
|
||||
throw invalid();
|
||||
}
|
||||
value.rows.forEach((row, index) => {
|
||||
const expected = expectedRows[index],
|
||||
order = row.differences.map(key => experimentComparisonDimensions.indexOf(key));
|
||||
if (
|
||||
!expected ||
|
||||
row.experimentId !== expected.experimentId ||
|
||||
row.trialKey !== expected.trial.trialKey ||
|
||||
order.some((position, i) => i > 0 && position <= (order[i - 1] ?? -1)) ||
|
||||
(row.inputCompatibility === 'match') !== (row.differences.length === 0) ||
|
||||
row.summaryAvailable !== expected.trial.comparable ||
|
||||
row.ready !==
|
||||
(row.inputCompatibility === 'match' && row.summaryAvailable && reference.comparable)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
});
|
||||
return { ...value, experiments };
|
||||
}
|
||||
export {
|
||||
parseExperimentComparison,
|
||||
parseComparisonQuery,
|
||||
type ExperimentComparisonView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
export const experimentComparisonApi = {
|
||||
async get(
|
||||
input: ExperimentComparisonInput,
|
||||
|
|
|
|||
|
|
@ -1,312 +1,31 @@
|
|||
import { z } from 'zod';
|
||||
import { researchActorSchema } from '@stock-bot/stock-config/research';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
MAX_WALK_FORWARD_RUNS,
|
||||
MAX_WALK_FORWARD_WINDOWS,
|
||||
walkForwardInputSchema,
|
||||
walkForwardPolicy,
|
||||
type WalkForwardDetail,
|
||||
walkForwardHashSchema as hash,
|
||||
invalidWalkForwardResponse as invalid,
|
||||
parseWalkForwardDetail,
|
||||
parseWalkForwardPreview,
|
||||
sameWalkForwardInput as same,
|
||||
walkForwardSummarySchema as summary,
|
||||
walkForwardIdSchema as uuid,
|
||||
WalkForwardApiError,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
import {
|
||||
type WalkForwardFinalizationInput,
|
||||
type WalkForwardInput,
|
||||
type WalkForwardSubmission,
|
||||
type WalkForwardSummary,
|
||||
} from '@stock-bot/stock-config/walk-forward';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
import {
|
||||
parseChronologicalValidationPreview,
|
||||
type ChronologicalValidationPreviewView,
|
||||
} from './chronologicalValidationApi';
|
||||
import {
|
||||
parseValidationDetail,
|
||||
validationEvidenceSchema,
|
||||
type ValidationDetailView,
|
||||
} from './chronologicalValidationDurableApi';
|
||||
import { parseExperimentPreview, type ExperimentPreviewView } from './experimentApi';
|
||||
|
||||
export type WalkForwardPreviewView = {
|
||||
version: 'walk-forward-preview/v1';
|
||||
execution: 'preview-only';
|
||||
previewHash: string;
|
||||
input: WalkForwardInput;
|
||||
source: ExperimentPreviewView;
|
||||
policy: typeof walkForwardPolicy;
|
||||
windows: { index: number; preview: ChronologicalValidationPreviewView }[];
|
||||
counts: {
|
||||
windows: number;
|
||||
trainingRuns: number;
|
||||
holdoutRuns: number;
|
||||
totalRuns: number;
|
||||
maxRuns: number;
|
||||
};
|
||||
};
|
||||
export type WalkForwardDetailView = Omit<WalkForwardDetail, 'preview' | 'windows'> & {
|
||||
preview: WalkForwardPreviewView;
|
||||
windows: {
|
||||
index: number;
|
||||
validationId: string;
|
||||
status: 'admitted' | 'missing';
|
||||
validation: ValidationDetailView | null;
|
||||
}[];
|
||||
};
|
||||
export class WalkForwardApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number | null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
get ambiguous() {
|
||||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/),
|
||||
uuid = z.string().uuid(),
|
||||
count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const same = (left: unknown, right: unknown) =>
|
||||
canonicalStrategyJson(left) === canonicalStrategyJson(right);
|
||||
const invalid = () =>
|
||||
new WalkForwardApiError(
|
||||
'The walk-forward response could not be verified. Refresh or retry the same request.',
|
||||
null
|
||||
);
|
||||
const prepared = z.object({
|
||||
version: z.literal('walk-forward-preview/v1'),
|
||||
execution: z.literal('preview-only'),
|
||||
previewHash: hash,
|
||||
input: walkForwardInputSchema,
|
||||
source: z.unknown(),
|
||||
policy: z.unknown(),
|
||||
windows: z
|
||||
.array(z.object({ index: count, preview: z.unknown() }))
|
||||
.min(2)
|
||||
.max(MAX_WALK_FORWARD_WINDOWS),
|
||||
counts: z.object({
|
||||
windows: count,
|
||||
trainingRuns: count,
|
||||
holdoutRuns: count,
|
||||
totalRuns: count,
|
||||
maxRuns: count,
|
||||
}),
|
||||
});
|
||||
export function parseWalkForwardPreview(
|
||||
raw: unknown,
|
||||
expected?: WalkForwardInput
|
||||
): WalkForwardPreviewView {
|
||||
const value = prepared.parse(raw),
|
||||
source = parseExperimentPreview(value.source);
|
||||
const { windows: recipes, ...sourceInput } = value.input;
|
||||
const size = recipes.length,
|
||||
candidates = source.candidates.length;
|
||||
if (
|
||||
(expected && !same(value.input, expected)) ||
|
||||
!same(source.input, sourceInput) ||
|
||||
!same(value.policy, walkForwardPolicy) ||
|
||||
value.windows.length !== size ||
|
||||
!same(value.counts, {
|
||||
windows: size,
|
||||
trainingRuns: size * candidates,
|
||||
holdoutRuns: size * 2,
|
||||
totalRuns: size * (candidates + 2),
|
||||
maxRuns: MAX_WALK_FORWARD_RUNS,
|
||||
}) ||
|
||||
value.counts.totalRuns > MAX_WALK_FORWARD_RUNS
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const windows = value.windows.map((item, index) => {
|
||||
const recipe = recipes[index],
|
||||
previous = recipes[index - 1];
|
||||
if (
|
||||
!recipe ||
|
||||
item.index !== index ||
|
||||
(previous &&
|
||||
(recipe.train.tradeStart < previous.train.tradeStart ||
|
||||
recipe.train.tradeEnd <= previous.train.tradeEnd ||
|
||||
recipe.validation.tradeStart < previous.test.tradeEnd))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const name = `${value.input.name} · window ${index + 1}`;
|
||||
const preview = parseChronologicalValidationPreview(
|
||||
{ preview: item.preview },
|
||||
{ ...sourceInput, name, recipe }
|
||||
);
|
||||
const { previewHash: _windowHash, ...childSource } = preview.source;
|
||||
const { previewHash: _sourceHash, ...originalSource } = source;
|
||||
if (!same(childSource, { ...originalSource, input: { ...sourceInput, name } })) {
|
||||
throw invalid();
|
||||
}
|
||||
return { index, preview };
|
||||
});
|
||||
return { ...value, source, windows, policy: walkForwardPolicy };
|
||||
}
|
||||
const summary = z
|
||||
.object({
|
||||
id: uuid,
|
||||
backtestId: uuid,
|
||||
name: z.string().min(1),
|
||||
previewHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
cancelRequested: z.boolean(),
|
||||
windowCount: count.min(2).max(MAX_WALK_FORWARD_WINDOWS),
|
||||
reportedWindowCount: count,
|
||||
trainingRunCount: count,
|
||||
plannedRunCount: count.max(MAX_WALK_FORWARD_RUNS),
|
||||
stage: z.enum(['windows', 'reported']),
|
||||
})
|
||||
.superRefine((item, context) => {
|
||||
if (
|
||||
item.reportedWindowCount > item.windowCount ||
|
||||
item.trainingRunCount < item.windowCount ||
|
||||
item.plannedRunCount !== item.trainingRunCount + 2 * item.windowCount
|
||||
) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'Inconsistent walk-forward counts',
|
||||
});
|
||||
}
|
||||
});
|
||||
const report = z.object({
|
||||
version: z.literal('walk-forward-report/v1'),
|
||||
id: uuid,
|
||||
walkForwardId: uuid,
|
||||
previewHash: hash,
|
||||
reportHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: researchActorSchema,
|
||||
reset: z.literal('initial-capital-empty-positions'),
|
||||
segments: z
|
||||
.array(
|
||||
z.object({
|
||||
index: count,
|
||||
validationId: uuid,
|
||||
previewHash: hash,
|
||||
selectionHash: hash,
|
||||
reportId: uuid,
|
||||
reportHash: hash,
|
||||
validation: validationEvidenceSchema,
|
||||
test: validationEvidenceSchema,
|
||||
})
|
||||
)
|
||||
.min(2)
|
||||
.max(MAX_WALK_FORWARD_WINDOWS),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const detail = z.object({
|
||||
preview: z.unknown(),
|
||||
windows: z.array(
|
||||
z.object({
|
||||
index: count,
|
||||
validationId: uuid,
|
||||
status: z.enum(['admitted', 'missing']),
|
||||
validation: z.unknown(),
|
||||
})
|
||||
),
|
||||
report: report.nullable(),
|
||||
actions: z.object({
|
||||
finalize: z.object({ available: z.boolean(), reason: z.string().nullable() }),
|
||||
}),
|
||||
});
|
||||
export function parseWalkForwardDetail(raw: unknown): WalkForwardDetailView {
|
||||
const base = summary.parse(raw),
|
||||
value = detail.parse(raw),
|
||||
preview = parseWalkForwardPreview(value.preview);
|
||||
if (
|
||||
base.backtestId !== preview.input.backtestId ||
|
||||
base.name !== preview.input.name ||
|
||||
base.previewHash !== preview.previewHash ||
|
||||
base.windowCount !== preview.counts.windows ||
|
||||
base.trainingRunCount !== preview.counts.trainingRuns ||
|
||||
base.plannedRunCount !== preview.counts.totalRuns ||
|
||||
value.windows.length !== base.windowCount ||
|
||||
new Set(value.windows.map(item => item.validationId)).size !== base.windowCount ||
|
||||
(base.stage === 'reported') !== (value.report !== null)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const windows = value.windows.map((item, index) => {
|
||||
if (item.index !== index || (item.status === 'missing') !== (item.validation === null)) {
|
||||
throw invalid();
|
||||
}
|
||||
const validation = item.validation === null ? null : parseValidationDetail(item.validation);
|
||||
if (
|
||||
validation &&
|
||||
(validation.id !== item.validationId ||
|
||||
validation.backtestId !== base.backtestId ||
|
||||
!same(validation.preview, preview.windows[index]?.preview))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...item, validation };
|
||||
});
|
||||
if (
|
||||
base.reportedWindowCount !== windows.filter(item => item.validation?.report).length ||
|
||||
(value.actions.finalize.available &&
|
||||
(base.cancelRequested ||
|
||||
value.report ||
|
||||
windows.some(
|
||||
item =>
|
||||
!item.validation?.report ||
|
||||
item.validation.cancelRequested ||
|
||||
item.validation.phases.some(
|
||||
phase =>
|
||||
phase.status !== 'admitted' ||
|
||||
!phase.experiment ||
|
||||
phase.experiment.cancelRequested ||
|
||||
phase.experiment.trials.some(
|
||||
trial =>
|
||||
trial.status !== 'completed' || !trial.comparable || trial.cancelRequested
|
||||
)
|
||||
)
|
||||
)))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
if (value.report) {
|
||||
const saved = value.report;
|
||||
if (
|
||||
saved.walkForwardId !== base.id ||
|
||||
saved.previewHash !== base.previewHash ||
|
||||
saved.segments.length !== base.windowCount
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
for (const [index, segment] of saved.segments.entries()) {
|
||||
const member = windows[index],
|
||||
frozen = preview.windows[index]?.preview,
|
||||
child = member?.validation?.report;
|
||||
const candidate = frozen?.source.candidates[segment.validation.sourceCandidateIndex];
|
||||
if (
|
||||
!member ||
|
||||
!frozen ||
|
||||
!candidate ||
|
||||
segment.index !== index ||
|
||||
segment.validationId !== member.validationId ||
|
||||
segment.previewHash !== frozen.previewHash ||
|
||||
segment.validation.phase !== 'validation' ||
|
||||
segment.test.phase !== 'test' ||
|
||||
segment.validation.sourceCandidateIndex !== segment.test.sourceCandidateIndex ||
|
||||
segment.validation.datasetHash !== frozen.partitions[1].dataset.hash ||
|
||||
segment.test.datasetHash !== frozen.partitions[2].dataset.hash ||
|
||||
[segment.validation, segment.test].some(
|
||||
item =>
|
||||
item.trialKey !== candidate.trialKey || !same(item.parameters, candidate.parameters)
|
||||
) ||
|
||||
(member.validation &&
|
||||
(!child ||
|
||||
segment.reportId !== child.id ||
|
||||
segment.reportHash !== child.reportHash ||
|
||||
segment.selectionHash !== child.selectionHash ||
|
||||
!same(segment.validation, child.validation) ||
|
||||
!same(segment.test, child.test)))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
}
|
||||
return { ...base, ...value, preview, windows };
|
||||
}
|
||||
export {
|
||||
WalkForwardApiError,
|
||||
parseWalkForwardDetail,
|
||||
parseWalkForwardPreview,
|
||||
type WalkForwardDetailView,
|
||||
type WalkForwardPreviewView,
|
||||
} from '@stock-bot/stock-config/research-responses';
|
||||
|
||||
const envelope = (body: unknown, key: string) => z.record(z.unknown()).parse(body)[key];
|
||||
async function request<T>(
|
||||
path: string,
|
||||
|
|
|
|||
216
apps/stock/web-app/src/features/paper/PaperDeploymentPage.tsx
Normal file
216
apps/stock/web-app/src/features/paper/PaperDeploymentPage.tsx
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import type {
|
||||
PaperDeployment,
|
||||
PaperDeploymentStatus,
|
||||
} from '@stock-bot/stock-config/paper-deployments';
|
||||
import { actionClass, fieldClass } from '../strategies/components/StrategyParameterForm';
|
||||
import { paperApi } from './paperApi';
|
||||
|
||||
export function PaperDeploymentPage() {
|
||||
const { deploymentId = '' } = useParams<{ deploymentId: string }>();
|
||||
return <PaperDeploymentView key={deploymentId} id={deploymentId} />;
|
||||
}
|
||||
function PaperDeploymentView({ id }: { id: string }) {
|
||||
const [deployment, setDeployment] = useState<PaperDeployment | null>(null),
|
||||
[status, setStatus] = useState<PaperDeploymentStatus | null>(null),
|
||||
[error, setError] = useState(''),
|
||||
[pending, setPending] = useState(false),
|
||||
[loading, setLoading] = useState(true),
|
||||
[recover, setRecover] = useState(false),
|
||||
[reason, setReason] = useState('Operator halt');
|
||||
const alive = useRef(true),
|
||||
sequence = useRef(0),
|
||||
writing = useRef(false);
|
||||
const refresh = async () => {
|
||||
if (writing.current) {
|
||||
return;
|
||||
}
|
||||
const current = ++sequence.current;
|
||||
setError('');
|
||||
try {
|
||||
const next = await paperApi.status(id);
|
||||
if (alive.current && current === sequence.current) {
|
||||
setStatus(next);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current && current === sequence.current) {
|
||||
setStatus(null);
|
||||
setError(cause instanceof Error ? cause.message : 'Paper status unavailable');
|
||||
}
|
||||
}
|
||||
};
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
const abort = new AbortController();
|
||||
void paperApi
|
||||
.get(id, abort.signal)
|
||||
.then(value => {
|
||||
if (alive.current) {
|
||||
setDeployment(value);
|
||||
void refresh();
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (alive.current) {
|
||||
setError(cause instanceof Error ? cause.message : 'Deployment unavailable');
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (alive.current) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
alive.current = false;
|
||||
sequence.current++;
|
||||
abort.abort();
|
||||
};
|
||||
}, [id]);
|
||||
const command = async (operation: 'bind' | 'activate' | 'halt') => {
|
||||
if (writing.current) {
|
||||
return;
|
||||
}
|
||||
writing.current = true;
|
||||
sequence.current++;
|
||||
setPending(true);
|
||||
setError('');
|
||||
try {
|
||||
const value = await paperApi.command(
|
||||
id,
|
||||
operation,
|
||||
operation === 'activate'
|
||||
? { recoverPending: recover }
|
||||
: operation === 'halt'
|
||||
? { reason }
|
||||
: {}
|
||||
);
|
||||
if (alive.current) {
|
||||
setStatus(value);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setStatus(null);
|
||||
setError(
|
||||
(cause instanceof Error ? cause.message : 'Paper command unavailable') +
|
||||
' Refresh readiness before another activation.'
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
writing.current = false;
|
||||
if (alive.current) {
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
if (loading) {
|
||||
return <p role="status">Loading paper deployment…</p>;
|
||||
}
|
||||
return (
|
||||
<main className="space-y-5 p-6">
|
||||
<Link to="/paper">Paper deployments</Link>
|
||||
<h1 className="text-2xl">
|
||||
{deployment?.preview.input.name ?? 'Paper deployment unavailable'}
|
||||
</h1>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{deployment && (
|
||||
<>
|
||||
<p>
|
||||
Immutable version {deployment.preview.strategy.versionId} · reviewed by{' '}
|
||||
{deployment.principal} at {deployment.createdAt}
|
||||
</p>
|
||||
<p>
|
||||
Account {deployment.preview.configuration.matching.risk.ledger.accountId}. Live trading
|
||||
is unavailable.
|
||||
</p>
|
||||
<p>{deployment.preview.input.reason}</p>
|
||||
<ul>
|
||||
{deployment.preview.limitations.map(item => (
|
||||
<li key={item}>{item}</li>
|
||||
))}
|
||||
</ul>
|
||||
<details>
|
||||
<summary>Retained promotion and evidence</summary>
|
||||
<pre className="overflow-auto text-xs">{JSON.stringify(deployment, null, 2)}</pre>
|
||||
</details>
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-xl">Paper host readiness</h2>
|
||||
<button disabled={pending} className={actionClass} onClick={() => void refresh()}>
|
||||
Refresh readiness
|
||||
</button>
|
||||
{status ? (
|
||||
<>
|
||||
<p>
|
||||
{status.readiness.active
|
||||
? 'Active paper execution'
|
||||
: 'Halted or inactive paper execution'}{' '}
|
||||
· {status.readiness.connected ? 'Feed connected' : 'Feed disconnected'}
|
||||
</p>
|
||||
<ul>
|
||||
{status.readiness.reasons.map(item => (
|
||||
<li key={item}>{item}</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>Bound deployment: {status.boundDeploymentId ?? 'None'}</p>
|
||||
<button
|
||||
className={actionClass}
|
||||
disabled={pending || Boolean(status.boundDeploymentId)}
|
||||
onClick={() => void command('bind')}
|
||||
>
|
||||
Bind halted deployment
|
||||
</button>
|
||||
<label className="block">
|
||||
<input
|
||||
aria-label="Recover pending paper work"
|
||||
type="checkbox"
|
||||
checked={recover}
|
||||
disabled={pending}
|
||||
onChange={e => setRecover(e.target.checked)}
|
||||
/>{' '}
|
||||
Explicitly recover retained pending work on activation
|
||||
</label>
|
||||
<button
|
||||
className={actionClass}
|
||||
disabled={
|
||||
pending ||
|
||||
status.boundDeploymentId !== id ||
|
||||
status.readiness.active ||
|
||||
!status.readiness.connected
|
||||
}
|
||||
onClick={() => void command('activate')}
|
||||
>
|
||||
Activate paper
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<p>Readiness has not been confirmed. Activation is unavailable.</p>
|
||||
)}
|
||||
<label className="block">
|
||||
Halt reason
|
||||
<input
|
||||
aria-label="Halt reason"
|
||||
className={fieldClass}
|
||||
value={reason}
|
||||
onChange={e => setReason(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
className={actionClass}
|
||||
disabled={pending || !reason.trim()}
|
||||
onClick={() => void command('halt')}
|
||||
>
|
||||
Halt paper
|
||||
</button>
|
||||
<p>
|
||||
Startup is inactive. A trusted feed producer must connect and provide fresh quotes
|
||||
before an operator can activate. Existing capital and checkpoints are retained.
|
||||
Activation rechecks current approval and build. Revoking catalog approval blocks new
|
||||
activation; use Halt paper to stop an already active account.
|
||||
</p>
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
{pending && <p role="status">Confirming paper command…</p>}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
459
apps/stock/web-app/src/features/paper/PaperDeploymentsPage.tsx
Normal file
459
apps/stock/web-app/src/features/paper/PaperDeploymentsPage.tsx
Normal file
|
|
@ -0,0 +1,459 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import type {
|
||||
PaperDeployment,
|
||||
PaperPromotionInput,
|
||||
PaperPromotionPreview,
|
||||
} from '@stock-bot/stock-config/paper-deployments';
|
||||
import { paperPromotionInputSchema } from '@stock-bot/stock-config/paper-deployments';
|
||||
import { chronologicalValidationDurableApi } from '../experiments/services/chronologicalValidationDurableApi';
|
||||
import { experimentApi } from '../experiments/services/experimentApi';
|
||||
import { walkForwardApi } from '../experiments/services/walkForwardApi';
|
||||
import { actionClass, fieldClass } from '../strategies/components/StrategyParameterForm';
|
||||
import { useUnsavedWarning } from '../strategies/components/useUnsavedWarning';
|
||||
import { paperApi, PaperApiError } from './paperApi';
|
||||
|
||||
const message = (cause: unknown) =>
|
||||
cause instanceof Error ? cause.message : 'Paper request failed';
|
||||
const initialTransport = JSON.stringify(
|
||||
{
|
||||
accountId: '',
|
||||
sessionId: '',
|
||||
quoteSeriesId: '',
|
||||
riskSession: { calendarId: '', calendarRevision: '', sessionId: '', startsAt: 0 },
|
||||
policy: {
|
||||
version: 1,
|
||||
sourceId: '',
|
||||
priceBasis: 'raw',
|
||||
maxFeedAgeMs: 60000,
|
||||
observations: [],
|
||||
cadence: [],
|
||||
calendars: [],
|
||||
riskBoundaries: [],
|
||||
},
|
||||
},
|
||||
null,
|
||||
2
|
||||
);
|
||||
type Source = {
|
||||
source: PaperPromotionInput['outOfSample'];
|
||||
tests: Array<{ runId: string; label: string }>;
|
||||
};
|
||||
export function PaperDeploymentsPage() {
|
||||
const navigate = useNavigate(),
|
||||
alive = useRef(true),
|
||||
busy = useRef(false),
|
||||
generation = useRef(0),
|
||||
frozen = useRef(false),
|
||||
dirty = useRef(false),
|
||||
receipt = useRef<{ preview: PaperPromotionPreview; key: string } | null>(null);
|
||||
const [rows, setRows] = useState<PaperDeployment[]>([]),
|
||||
[loading, setLoading] = useState(true),
|
||||
[error, setError] = useState(''),
|
||||
[pending, setPending] = useState(false),
|
||||
[uncertain, setUncertain] = useState(false);
|
||||
const [name, setName] = useState(''),
|
||||
[kind, setKind] = useState<'chronological' | 'walk-forward'>('chronological'),
|
||||
[sourceId, setSourceId] = useState(''),
|
||||
[costId, setCostId] = useState('');
|
||||
const [source, setSource] = useState<Source | null>(null),
|
||||
[cost, setCost] = useState<{
|
||||
id: string;
|
||||
previewHash: string;
|
||||
trials: Array<{ runId: string; label: string }>;
|
||||
} | null>(null),
|
||||
[testRunId, setTestRunId] = useState(''),
|
||||
[costRunId, setCostRunId] = useState('');
|
||||
const [transport, setTransport] = useState(initialTransport),
|
||||
[reason, setReason] = useState(''),
|
||||
[ack, setAck] = useState(false),
|
||||
[preview, setPreview] = useState<PaperPromotionPreview | null>(null);
|
||||
useUnsavedWarning(dirty.current || pending || uncertain);
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
const abort = new AbortController();
|
||||
void paperApi
|
||||
.list(abort.signal)
|
||||
.then(value => {
|
||||
if (alive.current) {
|
||||
setRows(value.deployments);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (alive.current) {
|
||||
setError(message(cause));
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (alive.current) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
alive.current = false;
|
||||
generation.current++;
|
||||
abort.abort();
|
||||
};
|
||||
}, []);
|
||||
const change = (action: () => void) => {
|
||||
if (busy.current || frozen.current) {
|
||||
return;
|
||||
}
|
||||
dirty.current = true;
|
||||
generation.current++;
|
||||
receipt.current = null;
|
||||
setPreview(null);
|
||||
setError('');
|
||||
action();
|
||||
};
|
||||
const run = async (work: () => Promise<void>, retryReceipt = false) => {
|
||||
if (busy.current || (frozen.current && !retryReceipt)) {
|
||||
return;
|
||||
}
|
||||
busy.current = true;
|
||||
setPending(true);
|
||||
setError('');
|
||||
try {
|
||||
await work();
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setError(message(cause));
|
||||
}
|
||||
} finally {
|
||||
busy.current = false;
|
||||
if (alive.current) {
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const loadEvidence = () =>
|
||||
run(async () => {
|
||||
const captured = generation.current;
|
||||
const sourcePromise =
|
||||
kind === 'chronological'
|
||||
? chronologicalValidationDurableApi.get(sourceId).then(value => {
|
||||
if (!value.report) {
|
||||
throw new Error('Chronological report is not sealed');
|
||||
}
|
||||
return {
|
||||
source: {
|
||||
kind: 'chronological-report/v1' as const,
|
||||
validationId: value.id,
|
||||
reportId: value.report.id,
|
||||
reportHash: value.report.reportHash,
|
||||
previewHash: value.report.previewHash,
|
||||
},
|
||||
tests: [{ runId: value.report.test.runId, label: 'Sealed chronological test' }],
|
||||
};
|
||||
})
|
||||
: walkForwardApi.get(sourceId).then(value => {
|
||||
if (!value.report) {
|
||||
throw new Error('Walk-forward report is not sealed');
|
||||
}
|
||||
return {
|
||||
source: {
|
||||
kind: 'walk-forward-report/v1' as const,
|
||||
walkForwardId: value.id,
|
||||
reportId: value.report.id,
|
||||
reportHash: value.report.reportHash,
|
||||
previewHash: value.report.previewHash,
|
||||
},
|
||||
tests: value.report.segments.map(segment => ({
|
||||
runId: segment.test.runId,
|
||||
label: `Window ${segment.index + 1} test`,
|
||||
})),
|
||||
};
|
||||
});
|
||||
const [nextSource, nextCost] = await Promise.all([sourcePromise, experimentApi.get(costId)]);
|
||||
if (
|
||||
nextCost.preview.version !== 'cost-sensitivity-preview/v1' ||
|
||||
nextCost.trials.some(t => t.status !== 'completed' || !t.runId)
|
||||
) {
|
||||
throw new Error('Select a fully completed cost-sensitivity study');
|
||||
}
|
||||
if (!alive.current || captured !== generation.current) {
|
||||
return;
|
||||
}
|
||||
const trials = nextCost.trials.map((trial, index) => {
|
||||
const scenario =
|
||||
nextCost.preview.version === 'cost-sensitivity-preview/v1'
|
||||
? nextCost.preview.candidates[index]?.costs
|
||||
: null;
|
||||
return {
|
||||
runId: trial.runId ?? '',
|
||||
label: `${index === 0 ? 'Baseline' : `Scenario ${index}`} · fee ${scenario?.feeRate}, slippage ${scenario?.slippageRate}`,
|
||||
};
|
||||
});
|
||||
setSource(nextSource);
|
||||
setCost({ id: nextCost.id, previewHash: nextCost.previewHash, trials });
|
||||
setTestRunId(nextSource.tests[0]?.runId ?? '');
|
||||
setCostRunId(trials[0]?.runId ?? '');
|
||||
});
|
||||
const review = () =>
|
||||
run(async () => {
|
||||
if (!source || !cost) {
|
||||
throw new Error('Load sealed test and completed cost evidence first');
|
||||
}
|
||||
const input = paperPromotionInputSchema.parse({
|
||||
name,
|
||||
outOfSample: source.source,
|
||||
testRunId,
|
||||
costExperimentId: cost.id,
|
||||
costPreviewHash: cost.previewHash,
|
||||
costRunId,
|
||||
transport: JSON.parse(transport),
|
||||
reason,
|
||||
acknowledgeTrustedCode: ack,
|
||||
});
|
||||
const captured = generation.current,
|
||||
next = await paperApi.preview(input);
|
||||
if (alive.current && captured === generation.current) {
|
||||
setPreview(next);
|
||||
receipt.current = { preview: next, key: crypto.randomUUID() };
|
||||
}
|
||||
});
|
||||
const create = () =>
|
||||
run(async () => {
|
||||
const captured = receipt.current;
|
||||
if (!preview || !captured || captured.preview !== preview) {
|
||||
throw new Error('Review a current preview first');
|
||||
}
|
||||
try {
|
||||
const saved = await paperApi.create(
|
||||
captured.preview.input,
|
||||
captured.preview.previewHash,
|
||||
captured.key
|
||||
);
|
||||
if (alive.current) {
|
||||
frozen.current = false;
|
||||
dirty.current = false;
|
||||
setUncertain(false);
|
||||
navigate(`/paper/${saved.id}`);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current && (!(cause instanceof PaperApiError) || cause.uncertain)) {
|
||||
frozen.current = true;
|
||||
setUncertain(true);
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
}, true);
|
||||
const disabled = pending || uncertain;
|
||||
return (
|
||||
<main
|
||||
className="space-y-6 p-6"
|
||||
onClickCapture={event => {
|
||||
const link = (event.target as HTMLElement).closest('a');
|
||||
if (
|
||||
link &&
|
||||
(!link.target || link.target === '_self') &&
|
||||
!link.hasAttribute('download') &&
|
||||
event.button === 0 &&
|
||||
!event.ctrlKey &&
|
||||
!event.metaKey &&
|
||||
!event.shiftKey &&
|
||||
!event.altKey &&
|
||||
(dirty.current || busy.current || frozen.current) &&
|
||||
!window.confirm(
|
||||
'Leave this paper promotion draft or unconfirmed submission? Its exact retry inputs and key will be discarded. You can inspect saved records in another tab.'
|
||||
)
|
||||
) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<h1 className="text-2xl">Paper deployments</h1>
|
||||
<p>
|
||||
Promote reviewed research into a halted paper account. Live trading is unavailable. Creating
|
||||
a deployment does not connect a feed or activate trading.
|
||||
</p>
|
||||
{loading ? (
|
||||
<p role="status">Loading deployments…</p>
|
||||
) : rows.length ? (
|
||||
<ul>
|
||||
{rows.map(row => (
|
||||
<li key={row.id}>
|
||||
<Link to={`/paper/${row.id}`}>{row.preview.input.name}</Link> ·{' '}
|
||||
{row.preview.configuration.matching.risk.ledger.accountId}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>No paper deployments yet.</p>
|
||||
)}
|
||||
{error && <p role="alert">{error}</p>}
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-xl">Review a new promotion</h2>
|
||||
<p>
|
||||
Use a sealed report and completed cost study from{' '}
|
||||
<Link to="/experiments">experiments</Link>. Future sessions and feed metadata must be
|
||||
supplied explicitly; no calendar is inferred.
|
||||
</p>
|
||||
<fieldset disabled={disabled} className="space-y-3">
|
||||
<label className="block">
|
||||
Deployment name
|
||||
<input
|
||||
aria-label="Deployment name"
|
||||
className={fieldClass}
|
||||
value={name}
|
||||
onChange={e => change(() => setName(e.target.value))}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Report type
|
||||
<select
|
||||
aria-label="Report type"
|
||||
className={fieldClass}
|
||||
value={kind}
|
||||
onChange={e =>
|
||||
change(() => {
|
||||
setKind(e.target.value as typeof kind);
|
||||
setSource(null);
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="chronological">Chronological validation</option>
|
||||
<option value="walk-forward">Walk-forward series</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
Report owner ID
|
||||
<input
|
||||
aria-label="Report owner ID"
|
||||
className={fieldClass}
|
||||
value={sourceId}
|
||||
onChange={e =>
|
||||
change(() => {
|
||||
setSourceId(e.target.value);
|
||||
setSource(null);
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Cost experiment ID
|
||||
<input
|
||||
aria-label="Cost experiment ID"
|
||||
className={fieldClass}
|
||||
value={costId}
|
||||
onChange={e =>
|
||||
change(() => {
|
||||
setCostId(e.target.value);
|
||||
setCost(null);
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<button className={actionClass} type="button" onClick={() => void loadEvidence()}>
|
||||
Load evidence
|
||||
</button>
|
||||
{source && (
|
||||
<label className="block">
|
||||
Test run
|
||||
<select
|
||||
aria-label="Test run"
|
||||
className={fieldClass}
|
||||
value={testRunId}
|
||||
onChange={e => change(() => setTestRunId(e.target.value))}
|
||||
>
|
||||
{source.tests.map(item => (
|
||||
<option key={item.runId} value={item.runId}>
|
||||
{item.label} · {item.runId}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{cost && (
|
||||
<label className="block">
|
||||
Paper cost scenario
|
||||
<select
|
||||
aria-label="Paper cost scenario"
|
||||
className={fieldClass}
|
||||
value={costRunId}
|
||||
onChange={e => change(() => setCostRunId(e.target.value))}
|
||||
>
|
||||
{cost.trials.map(item => (
|
||||
<option key={item.runId} value={item.runId}>
|
||||
{item.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<label className="block">
|
||||
Explicit paper transport and future sessions (JSON)
|
||||
<textarea
|
||||
aria-label="Paper transport"
|
||||
className={`${fieldClass} font-mono`}
|
||||
rows={15}
|
||||
value={transport}
|
||||
onChange={e => change(() => setTransport(e.target.value))}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Review rationale
|
||||
<textarea
|
||||
aria-label="Review rationale"
|
||||
className={fieldClass}
|
||||
value={reason}
|
||||
onChange={e => change(() => setReason(e.target.value))}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
<input
|
||||
aria-label="Authorize trusted paper code"
|
||||
type="checkbox"
|
||||
checked={ack}
|
||||
onChange={e => change(() => setAck(e.target.checked))}
|
||||
/>{' '}
|
||||
I reviewed the strategy code, holdout and costs, and authorize these exact bytes as
|
||||
trusted paper-host code, including AI-originated code.
|
||||
</label>
|
||||
<button className={actionClass} type="button" onClick={() => void review()}>
|
||||
Preview promotion
|
||||
</button>
|
||||
</fieldset>
|
||||
{preview && (
|
||||
<section className="space-y-2">
|
||||
<h3>Exact promotion preview</h3>
|
||||
<p>
|
||||
Version {preview.strategy.versionId} · {preview.strategy.origin}
|
||||
</p>
|
||||
<p>
|
||||
Account {preview.configuration.matching.risk.ledger.accountId} · initial capital{' '}
|
||||
{preview.configuration.matching.risk.ledger.initialCapital}
|
||||
</p>
|
||||
<p>
|
||||
Test return: {preview.evidence.test.metrics.totalReturn ?? 'Unavailable'} · fills{' '}
|
||||
{preview.evidence.test.fillCount}
|
||||
</p>
|
||||
<p>
|
||||
Paper-host hash: <code>{preview.host.hostSha256}</code>
|
||||
</p>
|
||||
<ul>
|
||||
{preview.limitations.map(item => (
|
||||
<li key={item}>{item}</li>
|
||||
))}
|
||||
</ul>
|
||||
<details>
|
||||
<summary>Frozen configuration and evidence</summary>
|
||||
<pre className="overflow-auto text-xs">{JSON.stringify(preview, null, 2)}</pre>
|
||||
</details>
|
||||
<button disabled={pending} className={actionClass} onClick={() => void create()}>
|
||||
{uncertain ? 'Retry same promotion receipt' : 'Create halted deployment'}
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
{uncertain && (
|
||||
<p role="status">
|
||||
The previous submission may have succeeded. The draft is frozen; retry uses the same key
|
||||
and cannot create a second deployment.
|
||||
</p>
|
||||
)}
|
||||
{pending && <p role="status">Checking paper promotion…</p>}
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
2
apps/stock/web-app/src/features/paper/index.ts
Normal file
2
apps/stock/web-app/src/features/paper/index.ts
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export { PaperDeploymentsPage } from './PaperDeploymentsPage';
|
||||
export { PaperDeploymentPage } from './PaperDeploymentPage';
|
||||
110
apps/stock/web-app/src/features/paper/paperApi.ts
Normal file
110
apps/stock/web-app/src/features/paper/paperApi.ts
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
paperDeploymentSchema,
|
||||
paperDeploymentStatusSchema,
|
||||
paperPromotionInputSchema,
|
||||
paperPromotionPreviewSchema,
|
||||
type PaperPromotionInput,
|
||||
} from '@stock-bot/stock-config/paper-deployments';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
|
||||
export class PaperApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly status: number | null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
get uncertain() {
|
||||
return this.status === null || this.status >= 500 || this.status === 408;
|
||||
}
|
||||
}
|
||||
async function request<S extends z.ZodTypeAny>(
|
||||
path: string,
|
||||
schema: S,
|
||||
init?: RequestInit
|
||||
): Promise<z.output<S>> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await apiFetch(`${API_BASE_URL}/api/v2/paper-deployments${path}`, init);
|
||||
} catch (error) {
|
||||
if (init?.signal?.aborted) {
|
||||
throw error;
|
||||
}
|
||||
throw new PaperApiError(
|
||||
'The paper response was lost. Check saved status before changing the request.',
|
||||
null
|
||||
);
|
||||
}
|
||||
const body: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
const error = z.object({ error: z.string() }).safeParse(body);
|
||||
throw new PaperApiError(
|
||||
error.success ? error.data.error : `Paper request failed (${response.status})`,
|
||||
response.status
|
||||
);
|
||||
}
|
||||
try {
|
||||
return schema.parse(body);
|
||||
} catch {
|
||||
throw new PaperApiError('Paper response could not be verified; check saved status.', null);
|
||||
}
|
||||
}
|
||||
const json = (body: unknown, key?: string): RequestInit => ({
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...(key ? { 'Idempotency-Key': key } : {}) },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
export const paperApi = {
|
||||
list: (signal?: AbortSignal) =>
|
||||
request('', z.object({ deployments: z.array(paperDeploymentSchema) }).strict(), { signal }),
|
||||
get: async (id: string, signal?: AbortSignal) => {
|
||||
const value = await request(`/${encodeURIComponent(id)}`, paperDeploymentSchema, { signal });
|
||||
if (value.id !== id) {
|
||||
throw new PaperApiError('Paper deployment identity mismatch', null);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
preview: async (input: PaperPromotionInput, signal?: AbortSignal) => {
|
||||
const parsed = paperPromotionInputSchema.parse(input),
|
||||
value = await request('/preview', paperPromotionPreviewSchema, { ...json(parsed), signal });
|
||||
if (canonicalStrategyJson(value.input) !== canonicalStrategyJson(parsed)) {
|
||||
throw new PaperApiError('Paper preview input mismatch', null);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
create: async (input: PaperPromotionInput, previewHash: string, key: string) => {
|
||||
const parsed = paperPromotionInputSchema.parse(input),
|
||||
value = await request('', paperDeploymentSchema, json({ ...parsed, previewHash }, key));
|
||||
if (
|
||||
value.preview.previewHash !== previewHash ||
|
||||
canonicalStrategyJson(value.preview.input) !== canonicalStrategyJson(parsed)
|
||||
) {
|
||||
throw new PaperApiError('Paper promotion receipt mismatch', null);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
status: async (id: string, signal?: AbortSignal) => {
|
||||
const value = await request(
|
||||
`/${encodeURIComponent(id)}/readiness`,
|
||||
paperDeploymentStatusSchema,
|
||||
{ signal }
|
||||
);
|
||||
if (value.deploymentId !== id) {
|
||||
throw new PaperApiError('Paper status identity mismatch', null);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
command: async (id: string, operation: 'bind' | 'activate' | 'halt', body: unknown) => {
|
||||
const value = await request(
|
||||
`/${encodeURIComponent(id)}/${operation}`,
|
||||
paperDeploymentStatusSchema,
|
||||
json(body)
|
||||
);
|
||||
if (value.deploymentId !== id) {
|
||||
throw new PaperApiError('Paper command identity mismatch', null);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
};
|
||||
|
|
@ -28,6 +28,7 @@ export function ResearchAgentsPage() {
|
|||
const [name, setName] = useState('');
|
||||
const [projects, setProjects] = useState(search.get('projectId') ?? '');
|
||||
const [backtests, setBacktests] = useState('');
|
||||
const [candidateBacktests, setCandidateBacktests] = useState('');
|
||||
const [limits, setLimits] = useState<Record<string, string>>(() =>
|
||||
Object.fromEntries(limitFields.map(([key, , value]) => [key, value]))
|
||||
);
|
||||
|
|
@ -43,7 +44,7 @@ export function ResearchAgentsPage() {
|
|||
const writing = useRef(false);
|
||||
const generation = useRef(0);
|
||||
const budgetRequests = useRef(new Map<string, number>());
|
||||
useUnsavedWarning(Boolean(name || backtests || token || uncertain));
|
||||
useUnsavedWarning(Boolean(name || backtests || candidateBacktests || token || uncertain));
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
|
|
@ -87,6 +88,9 @@ export function ResearchAgentsPage() {
|
|||
name,
|
||||
allowedProjectIds: identifiers(projects),
|
||||
allowedBacktestIds: identifiers(backtests),
|
||||
...(candidateBacktests.trim()
|
||||
? { allowOwnCandidateBacktestIds: identifiers(candidateBacktests) }
|
||||
: {}),
|
||||
limits: Object.fromEntries(limitFields.map(([key]) => [key, Number(limits[key])])),
|
||||
});
|
||||
if (!parsed.success) {
|
||||
|
|
@ -109,6 +113,7 @@ export function ResearchAgentsPage() {
|
|||
setToken(result.token);
|
||||
setName('');
|
||||
setBacktests('');
|
||||
setCandidateBacktests('');
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
|
|
@ -266,6 +271,20 @@ export function ResearchAgentsPage() {
|
|||
Separate IDs with commas or whitespace. Empty lists grant no access. Backtests must
|
||||
already have an eligible immutable version, retained dataset and canonical policy.
|
||||
</p>
|
||||
<label className="block">
|
||||
Allow own candidates on backtest IDs
|
||||
<textarea
|
||||
aria-label="Allow own candidates on backtest IDs"
|
||||
className={fieldClass}
|
||||
value={candidateBacktests}
|
||||
onChange={event => setCandidateBacktests(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Optional subset of the allowed backtests. This permits the agent’s own immutable
|
||||
candidates to run in isolation under the same frozen financial policy. Review revocation
|
||||
still blocks new admissions.
|
||||
</p>
|
||||
{limitFields.map(([key, label]) => (
|
||||
<label key={key} className="block">
|
||||
{label}
|
||||
|
|
@ -321,7 +340,10 @@ export function ResearchAgentsPage() {
|
|||
<Link to={`/backtests/${grant.backtestId}`} className="text-primary-500">
|
||||
{grant.backtestId}
|
||||
</Link>{' '}
|
||||
· Policy {grant.policyHash}
|
||||
· Policy {grant.policyHash} ·{' '}
|
||||
{grant.allowOwnCandidates
|
||||
? 'Owned isolated candidates allowed'
|
||||
: 'Template strategy only'}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import type {
|
|||
StrategyVersionSummary,
|
||||
} from '@stock-bot/types';
|
||||
import { BuiltinReview } from './components/BuiltinReview';
|
||||
import { CandidatePublication } from './components/CandidatePublication';
|
||||
import { actionClass, fieldClass, StrategyParameterForm } from './components/StrategyParameterForm';
|
||||
import { versionPath } from './components/StrategySelection';
|
||||
import { confirmDiscard, useUnsavedWarning } from './components/useUnsavedWarning';
|
||||
|
|
@ -33,6 +34,7 @@ function StrategyDetail({ strategyId, versionId }: { strategyId: string; version
|
|||
const [parameters, setParameters] = useState<Parameters>({});
|
||||
const [validParameters, setValidParameters] = useState(false);
|
||||
const [parameterEdits, setParameterEdits] = useState(false);
|
||||
const [publicationDirty, setPublicationDirty] = useState(false);
|
||||
const [cloneOpen, setCloneOpen] = useState(false);
|
||||
const [cloneName, setCloneName] = useState('');
|
||||
const [cloneDescription, setCloneDescription] = useState('');
|
||||
|
|
@ -52,7 +54,10 @@ function StrategyDetail({ strategyId, versionId }: { strategyId: string; version
|
|||
strategy && (name !== strategy.name || description !== strategy.description)
|
||||
);
|
||||
const dirty =
|
||||
metadataDirty || parameterEdits || (cloneOpen && Boolean(cloneName || cloneDescription));
|
||||
metadataDirty ||
|
||||
parameterEdits ||
|
||||
publicationDirty ||
|
||||
(cloneOpen && Boolean(cloneName || cloneDescription));
|
||||
useUnsavedWarning(dirty);
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
|
|
@ -291,11 +296,25 @@ function StrategyDetail({ strategyId, versionId }: { strategyId: string; version
|
|||
{strategy.archived ? 'Restore strategy' : 'Archive strategy'}
|
||||
</button>
|
||||
</form>
|
||||
<CandidatePublication
|
||||
key={`publication:${strategyId}:${versionId ?? ''}`}
|
||||
strategyId={strategyId}
|
||||
parentVersionId={versionId ?? null}
|
||||
disabled={
|
||||
strategy.archived ||
|
||||
cloning ||
|
||||
cloneFrozen ||
|
||||
versionLoading ||
|
||||
Boolean(versionId && !version)
|
||||
}
|
||||
onDirtyChange={setPublicationDirty}
|
||||
onPublished={published => navigate(versionPath(published))}
|
||||
/>
|
||||
<section className="space-y-3">
|
||||
<h2 className="font-semibold">Immutable versions</h2>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Publish version packages using the existing catalog API. Metadata edits do not change
|
||||
retained code.
|
||||
Published packages preserve exact code and dependency hashes. Metadata edits do not
|
||||
change retained code.
|
||||
</p>
|
||||
<label className="block text-sm">
|
||||
Strategy version
|
||||
|
|
@ -305,7 +324,7 @@ function StrategyDetail({ strategyId, versionId }: { strategyId: string; version
|
|||
value={versionId ?? ''}
|
||||
disabled={cloning || cloneFrozen}
|
||||
onChange={event => {
|
||||
if (confirmDiscard(parameterEdits)) {
|
||||
if (confirmDiscard(parameterEdits || publicationDirty)) {
|
||||
navigate(
|
||||
event.target.value
|
||||
? `/strategies/${strategyId}/versions/${event.target.value}`
|
||||
|
|
@ -429,7 +448,8 @@ function StrategyDetail({ strategyId, versionId }: { strategyId: string; version
|
|||
)}
|
||||
<p className="text-sm text-text-secondary">
|
||||
The clone retains exact artifact bytes and parent lineage. It is a new
|
||||
candidate awaiting review; cloning does not enable execution.
|
||||
candidate. Research eligibility requires a declared isolated execution
|
||||
contract and an available sandbox.
|
||||
</p>
|
||||
<label className="block text-sm">
|
||||
Clone name
|
||||
|
|
@ -517,7 +537,7 @@ function VersionIdentity({ version }: { version: StrategyVersionSummary }) {
|
|||
</p>
|
||||
<p role="status">
|
||||
{version.origin === 'candidate'
|
||||
? 'Candidate execution is unavailable until isolated execution is supported.'
|
||||
? 'Candidate research uses the isolated runtime. Eligibility is checked against the retained package, dataset and financial policy.'
|
||||
: 'Canonical execution requires approval, a matching executable build, a supported dataset and an explicit simulation policy.'}
|
||||
</p>
|
||||
<p>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,197 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { StrategyVersionPackage } from '@stock-bot/types';
|
||||
import {
|
||||
CandidatePublicationError,
|
||||
publishCandidate,
|
||||
readCandidatePackage,
|
||||
type PublishedCandidate,
|
||||
} from '../services/candidatePublication';
|
||||
import { actionClass, fieldClass } from './StrategyParameterForm';
|
||||
|
||||
/** Key by family/parent identity. A lost write keeps exactly one package and receipt. */
|
||||
export function CandidatePublication({
|
||||
strategyId,
|
||||
parentVersionId,
|
||||
disabled,
|
||||
onDirtyChange,
|
||||
onPublished,
|
||||
}: {
|
||||
strategyId: string;
|
||||
parentVersionId: string | null;
|
||||
disabled: boolean;
|
||||
onDirtyChange: (dirty: boolean) => void;
|
||||
onPublished: (version: PublishedCandidate) => void;
|
||||
}) {
|
||||
const [pkg, setPackage] = useState<StrategyVersionPackage | null>(null);
|
||||
const [filename, setFilename] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [pending, setPending] = useState(false);
|
||||
const [uncertain, setUncertain] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const active = useRef(false);
|
||||
const generation = useRef(0);
|
||||
const writing = useRef(false);
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
const intent = useRef<{ pkg: StrategyVersionPackage; key: string } | null>(null);
|
||||
const dirtyCallback = useRef(onDirtyChange);
|
||||
dirtyCallback.current = onDirtyChange;
|
||||
useEffect(() => {
|
||||
active.current = true;
|
||||
return () => {
|
||||
active.current = false;
|
||||
generation.current++;
|
||||
dirtyCallback.current(false);
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
onDirtyChange(Boolean(filename || pkg || uncertain));
|
||||
}, [filename, pkg, uncertain, onDirtyChange]);
|
||||
const select = async (file: File | undefined) => {
|
||||
if (writing.current || intent.current) {
|
||||
return;
|
||||
}
|
||||
const current = ++generation.current;
|
||||
setPackage(null);
|
||||
setError('');
|
||||
setFilename(file?.name ?? '');
|
||||
intent.current = null;
|
||||
if (!file) {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
try {
|
||||
const parsed = await readCandidatePackage(await file.text());
|
||||
if (active.current && current === generation.current) {
|
||||
setPackage(parsed);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (active.current && current === generation.current) {
|
||||
setError(cause instanceof Error ? cause.message : 'Package could not be read');
|
||||
}
|
||||
} finally {
|
||||
if (active.current && current === generation.current) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const publish = async () => {
|
||||
if (writing.current || (!intent.current && (disabled || loading || !pkg))) {
|
||||
return;
|
||||
}
|
||||
if (!intent.current && pkg) {
|
||||
intent.current = { pkg, key: crypto.randomUUID() };
|
||||
}
|
||||
const captured = intent.current;
|
||||
if (!captured) {
|
||||
return;
|
||||
}
|
||||
writing.current = true;
|
||||
setPending(true);
|
||||
setError('');
|
||||
try {
|
||||
const saved = await publishCandidate(strategyId, captured.pkg, parentVersionId, captured.key);
|
||||
if (active.current) {
|
||||
intent.current = null;
|
||||
setUncertain(false);
|
||||
setPackage(null);
|
||||
setFilename('');
|
||||
if (fileInput.current) {
|
||||
fileInput.current.value = '';
|
||||
}
|
||||
onDirtyChange(false);
|
||||
onPublished(saved);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (active.current) {
|
||||
setError(cause instanceof Error ? cause.message : 'Publication failed');
|
||||
const lost = !(cause instanceof CandidatePublicationError) || cause.uncertain;
|
||||
setUncertain(lost);
|
||||
if (!lost) {
|
||||
intent.current = null;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
writing.current = false;
|
||||
if (active.current) {
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
return (
|
||||
<section
|
||||
aria-label="Publish candidate version"
|
||||
className="space-y-3 border border-border rounded p-4"
|
||||
>
|
||||
<h3 className="font-semibold">Publish candidate version</h3>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Upload a self-contained strategy package. Research evaluates candidate code in the isolated
|
||||
runtime with Rust financial constraints. Warmup is an author declaration; paper promotion
|
||||
requires a separate operator review.
|
||||
</p>
|
||||
<label className="block text-sm">
|
||||
Candidate package (JSON)
|
||||
<input
|
||||
ref={fileInput}
|
||||
type="file"
|
||||
accept="application/json,.json"
|
||||
aria-label="Candidate package (JSON)"
|
||||
className={fieldClass}
|
||||
disabled={disabled || pending || uncertain}
|
||||
onChange={event => void select(event.target.files?.[0])}
|
||||
/>
|
||||
</label>
|
||||
{loading && <p role="status">Checking retained package...</p>}
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{pkg && (
|
||||
<dl className="text-sm break-all space-y-1">
|
||||
<dt>Program</dt>
|
||||
<dd>
|
||||
{pkg.program.strategyId} / {pkg.program.strategyVersion}
|
||||
</dd>
|
||||
<dt>Artifact SHA256</dt>
|
||||
<dd>{pkg.artifact.sha256}</dd>
|
||||
<dt>Dependency lock SHA256</dt>
|
||||
<dd>{pkg.dependencyLock.sha256}</dd>
|
||||
<dt>Author-declared warmup bars</dt>
|
||||
<dd>{pkg.execution?.warmupBars}</dd>
|
||||
<dt>Parent version</dt>
|
||||
<dd>{parentVersionId ?? 'First version in this family'}</dd>
|
||||
</dl>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={pending || (!intent.current && (disabled || loading || !pkg))}
|
||||
onClick={() => void publish()}
|
||||
>
|
||||
{pending
|
||||
? 'Publishing...'
|
||||
: uncertain
|
||||
? 'Retry same publication'
|
||||
: 'Publish immutable candidate'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={pending || uncertain || disabled || !filename}
|
||||
onClick={() => {
|
||||
if (writing.current || intent.current) {
|
||||
return;
|
||||
}
|
||||
generation.current++;
|
||||
setLoading(false);
|
||||
setPackage(null);
|
||||
setFilename('');
|
||||
setError('');
|
||||
intent.current = null;
|
||||
if (fileInput.current) {
|
||||
fileInput.current.value = '';
|
||||
}
|
||||
}}
|
||||
>
|
||||
Clear package
|
||||
</button>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -222,7 +222,7 @@ export function StrategySelection({
|
|||
</Link>
|
||||
<p className="text-xs text-text-muted">
|
||||
{selected.origin === 'candidate'
|
||||
? 'Candidate execution is unavailable until isolated execution is supported.'
|
||||
? 'Candidate research requires an isolated execution declaration and an available sandbox. Eligibility is checked when preparing the run.'
|
||||
: 'Reviewed built-in versions require a supported dataset, explicit policy and matching executable build before execution.'}
|
||||
</p>
|
||||
{family?.archived && (
|
||||
|
|
|
|||
|
|
@ -0,0 +1,105 @@
|
|||
import { z } from 'zod';
|
||||
import { parseStrategyVersionPackage } from '@stock-bot/stock-config/strategy';
|
||||
import type { StrategyVersionPackage } from '@stock-bot/types';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
|
||||
export class CandidatePublicationError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number | null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
get uncertain() {
|
||||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
export interface PublishedCandidate {
|
||||
id: string;
|
||||
strategyId: string;
|
||||
ordinal: number;
|
||||
}
|
||||
const hash = async (value: string) =>
|
||||
[...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value)))]
|
||||
.map(byte => byte.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
|
||||
/** Parse and hash inert bytes. Generated code is never imported or compiled in the browser. */
|
||||
export async function readCandidatePackage(text: string): Promise<StrategyVersionPackage> {
|
||||
const pkg = parseStrategyVersionPackage(JSON.parse(text));
|
||||
if (pkg.execution?.kind !== 'isolated-candidate/v1') {
|
||||
throw new Error('Package must declare isolated-candidate/v1 execution and its warmup bars');
|
||||
}
|
||||
const [artifact, lock] = await Promise.all([
|
||||
hash(pkg.artifact.content),
|
||||
hash(pkg.dependencyLock.content),
|
||||
]);
|
||||
if (artifact !== pkg.artifact.sha256 || lock !== pkg.dependencyLock.sha256) {
|
||||
throw new Error('Package artifact or dependency-lock hash does not match its retained bytes');
|
||||
}
|
||||
return pkg;
|
||||
}
|
||||
export async function publishCandidate(
|
||||
strategyId: string,
|
||||
pkg: StrategyVersionPackage,
|
||||
parentVersionId: string | null,
|
||||
key: string
|
||||
): Promise<PublishedCandidate> {
|
||||
strategyId = z.string().uuid().parse(strategyId).toLowerCase();
|
||||
parentVersionId = z.string().uuid().nullable().parse(parentVersionId)?.toLowerCase() ?? null;
|
||||
const body = JSON.stringify({ package: pkg, parentVersionId });
|
||||
let response: Response;
|
||||
try {
|
||||
response = await apiFetch(
|
||||
`${API_BASE_URL}/api/v2/strategies/${encodeURIComponent(strategyId)}/versions`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key },
|
||||
body,
|
||||
}
|
||||
);
|
||||
} catch {
|
||||
throw new CandidatePublicationError(
|
||||
'Publication response was lost. Retry the same publication to recover its receipt.',
|
||||
null
|
||||
);
|
||||
}
|
||||
const raw: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
const parsed = z.object({ error: z.string() }).safeParse(raw);
|
||||
throw new CandidatePublicationError(
|
||||
parsed.success ? parsed.data.error : `Publication failed (${response.status})`,
|
||||
response.status
|
||||
);
|
||||
}
|
||||
const parsed = z
|
||||
.object({
|
||||
version: z.object({
|
||||
id: z.string().uuid(),
|
||||
strategyId: z.string().uuid(),
|
||||
ordinal: z.number().int().positive(),
|
||||
origin: z.literal('candidate'),
|
||||
parentVersionId: z.string().uuid().nullable(),
|
||||
package: z.object({
|
||||
artifact: z.object({ sha256: z.string() }),
|
||||
dependencyLock: z.object({ sha256: z.string() }),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.safeParse(raw);
|
||||
if (
|
||||
!parsed.success ||
|
||||
response.status !== 201 ||
|
||||
parsed.data.version.strategyId !== strategyId ||
|
||||
parsed.data.version.parentVersionId !== parentVersionId ||
|
||||
parsed.data.version.package.artifact.sha256 !== pkg.artifact.sha256 ||
|
||||
parsed.data.version.package.dependencyLock.sha256 !== pkg.dependencyLock.sha256
|
||||
) {
|
||||
throw new CandidatePublicationError(
|
||||
'Publication response could not be verified. Retry the same publication.',
|
||||
null
|
||||
);
|
||||
}
|
||||
const { id, ordinal } = parsed.data.version;
|
||||
return { id, strategyId, ordinal };
|
||||
}
|
||||
|
|
@ -35,6 +35,7 @@ export const navigation: NavigationItem[] = [
|
|||
{ name: 'Backtests', href: '/backtests', icon: BeakerIcon },
|
||||
{ name: 'Research', href: '/research', icon: BeakerIcon },
|
||||
{ name: 'Experiments', href: '/experiments', icon: BeakerIcon },
|
||||
{ name: 'Paper deployments', href: '/paper', icon: DocumentTextIcon },
|
||||
{
|
||||
name: 'System',
|
||||
icon: ServerStackIcon,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue