-- Each chronological phase remains an ordinary one-dataset experiment and run lifecycle. ALTER TABLE research_experiments ADD COLUMN IF NOT EXISTS validation_manifest JSONB; ALTER TABLE research_experiments ADD COLUMN IF NOT EXISTS validation_parent_id UUID REFERENCES research_experiments(id) ON DELETE RESTRICT; ALTER TABLE research_experiments ADD COLUMN IF NOT EXISTS validation_phase TEXT; ALTER TABLE research_experiments ADD COLUMN IF NOT EXISTS validation_selection JSONB; ALTER TABLE research_experiments ADD COLUMN IF NOT EXISTS validation_report JSONB; DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='validation_experiment_shape' AND conrelid='research_experiments'::regclass) THEN ALTER TABLE research_experiments ADD CONSTRAINT validation_experiment_shape CHECK (( (validation_phase IS NULL AND validation_parent_id IS NULL AND validation_manifest IS NULL AND validation_selection IS NULL AND validation_report IS NULL) OR (validation_phase='train' AND validation_parent_id IS NULL AND validation_manifest IS NOT NULL) OR (validation_phase IN ('validation','test') AND validation_parent_id IS NOT NULL AND validation_parent_id<>id AND validation_manifest IS NULL AND validation_selection IS NULL AND validation_report IS NULL) ) IS TRUE); END IF; END $$; CREATE UNIQUE INDEX IF NOT EXISTS validation_child_phase ON research_experiments(validation_parent_id,validation_phase) WHERE validation_parent_id IS NOT NULL; CREATE UNIQUE INDEX IF NOT EXISTS validation_selection_receipt ON research_experiments((validation_selection->>'principal'),(validation_selection#>>'{_receipt,key}')) WHERE validation_selection IS NOT NULL; CREATE UNIQUE INDEX IF NOT EXISTS validation_report_receipt ON research_experiments((validation_report->>'principal'),(validation_report#>>'{_receipt,key}')) WHERE validation_report IS NOT NULL; -- Reuse the original source-template proof without invoking a trigger function as a normal function. CREATE OR REPLACE FUNCTION validate_experiment_manifest(candidate_row research_experiments) RETURNS void LANGUAGE plpgsql AS $$ DECLARE parent RECORD; selected RECORD; approval RECORD; retained JSONB; request JSONB; candidate JSONB; candidate_index INTEGER := 0; BEGIN SELECT * INTO parent FROM backtests WHERE id=candidate_row.backtest_id FOR UPDATE; request := candidate_row.preview->'request'; IF (parent.id IS NOT NULL AND parent.archived_at IS NULL AND NOT candidate_row.cancel_requested AND jsonb_typeof(candidate_row.preview)='object' AND candidate_row.preview->>'version'='research-experiment-preview/v1' AND candidate_row.preview->>'previewHash'=candidate_row.preview_hash AND candidate_row.preview#>>'{input,name}'=candidate_row.name AND candidate_row.preview#>>'{input,backtestId}'=candidate_row.backtest_id::text AND jsonb_typeof(candidate_row.preview#>'{input,grid}')='object' AND jsonb_typeof(candidate_row.preview->'candidates')='array' AND jsonb_array_length(candidate_row.preview->'candidates') BETWEEN 1 AND 100 AND request->>'kind'='canonical-research/v1' AND request->>'backtestId'=candidate_row.backtest_id::text AND request->>'runId'='00000000-0000-4000-8000-000000000001' AND request->>'name'=parent.name AND request#>>'{strategy,versionId}'=parent.strategy_version_id::text AND request#>'{strategy,selection,parameters}'=parent.strategy_parameters AND request->>'datasetHash'=parent.config->>'datasetHash' AND request#>>'{policy,matching,risk,ledger,sessionId}'=request->>'runId' AND request#>>'{policy,matching,risk,ledger,accountId}'='research:'||(request->>'runId') AND request#>>'{policy,matching,risk,ledger,baseCurrency}'='USD' AND request#>>'{policy,matching,risk,ledger,reserveOwnerId}'='reserve' AND (request#>>'{policy,matching,risk,ledger,initialCapital}')::numeric=parent.initial_capital AND request#>>'{strategy,selection,ownerBudget}'=parent.config#>>'{canonical,ownerBudget}' AND request#>'{strategy,selection,seed}'=parent.config#>'{canonical,seed}' AND request#>>'{policy,allow_exploratory}'='false' AND jsonb_typeof(request->'build')='object' AND request#>>'{build,version}'='1' AND request#>>'{build,runtime}'='bun' AND request#>>'{build,workerSha256}' ~ '^[a-f0-9]{64}$' AND request#>>'{build,engineWrapperSha256}' ~ '^[a-f0-9]{64}$' AND request#>>'{build,engineBinarySha256}' ~ '^[a-f0-9]{64}$' AND request#>>'{build,dependencyLockSha256}' ~ '^[a-f0-9]{64}$' AND length(request#>>'{build,runtimeVersion}')>0 AND length(request#>>'{build,platform}')>0 AND length(request#>>'{build,arch}')>0 AND request->'modelArtifacts'='[]'::jsonb) IS NOT TRUE THEN RAISE EXCEPTION 'Experiment manifest requires an active canonical template and complete frozen identity' USING ERRCODE='23514'; END IF; IF EXISTS (SELECT 1 FROM jsonb_each(parent.config->'canonical') settings WHERE CASE settings.key WHEN 'version' THEN request#>'{analyticsPolicy,version}' WHEN 'ownerBudget' THEN request#>'{strategy,selection,ownerBudget}' WHEN 'seed' THEN request#>'{strategy,selection,seed}' WHEN 'halfSpreadRate' THEN request#>'{policy,matching,halfSpreadRate}' WHEN 'slippageRate' THEN request#>'{policy,matching,slippageRate}' WHEN 'latencyMs' THEN request#>'{policy,matching,latencyMs}' WHEN 'participationRate' THEN request#>'{policy,participation_rate}' WHEN 'periodsPerYear' THEN request#>'{analyticsPolicy,periodsPerYear}' WHEN 'annualRiskFreeRate' THEN request#>'{analyticsPolicy,annualRiskFreeRate}' ELSE request#>ARRAY['policy','matching','risk',settings.key] END IS DISTINCT FROM settings.value) THEN RAISE EXCEPTION 'Experiment financial and analysis settings must match its saved template' USING ERRCODE='23514'; END IF; SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id WHERE v.id=parent.strategy_version_id FOR UPDATE OF s; SELECT id,decision INTO approval FROM strategy_review_events WHERE version_id=selected.id ORDER BY ordinal DESC LIMIT 1; IF (selected.origin='builtin' AND selected.family_archived IS NULL AND approval.decision='approve' AND request#>>'{strategy,origin}'='builtin' AND request#>>'{strategy,familyId}'=selected.strategy_id::text AND request#>>'{strategy,reviewId}'=approval.id::text AND request#>'{strategy,package}'=selected.envelope AND request#>>'{strategy,selection,ownerId}'='strategy:'||selected.id::text AND request#>'{policy,matching,risk,ledger,ownerIds}'=jsonb_build_array('strategy:'||selected.id::text) AND request#>'{policy,matching,owners}'=jsonb_build_array(jsonb_build_object('ownerId','strategy:'||selected.id::text,'mode','Target')) AND request#>>'{strategy,selection,strategyId}'=selected.envelope#>>'{program,strategyId}' AND request#>>'{strategy,selection,strategyVersion}'=selected.envelope#>>'{program,strategyVersion}') IS NOT TRUE THEN RAISE EXCEPTION 'Experiment requires the exact current approved built-in version' USING ERRCODE='23514'; END IF; SELECT payload INTO retained FROM backtest_datasets WHERE hash=request->>'datasetHash'; IF (retained#>>'{manifest,version}'='2' AND retained#>>'{manifest,eligibility}'='eligible' AND retained->'manifest'=candidate_row.preview->'dataset' AND retained#>>'{manifest,hash}'=request->>'datasetHash' AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1 AND jsonb_array_length(retained#>'{manifest,series}')=1 AND jsonb_array_length(retained#>'{manifest,universe,instrumentIds}')=1 AND request#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}' AND request#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}' AND request#>'{policy,matching,series}'=jsonb_build_array(jsonb_build_object('instrumentId',request#>>'{strategy,selection,instrumentId}','seriesId',request#>>'{strategy,selection,seriesId}','mode','Open')) AND request#>'{policy,cadence}'=jsonb_build_array(jsonb_build_object('owner_id','strategy:'||selected.id::text,'series_ids',jsonb_build_array(request#>>'{strategy,selection,seriesId}')))) IS NOT TRUE THEN RAISE EXCEPTION 'Experiment requires the exact eligible retained single-asset dataset' USING ERRCODE='23514'; END IF; FOR candidate IN SELECT value FROM jsonb_array_elements(candidate_row.preview->'candidates') LOOP IF (jsonb_typeof(candidate)='object' AND candidate->>'index'=candidate_index::text AND candidate->>'trialKey' ~ '^[a-f0-9]{64}$' AND jsonb_typeof(candidate->'parameters')='object' AND candidate->'parameters' <> '{}'::jsonb AND NOT EXISTS (SELECT 1 FROM jsonb_object_keys(candidate->'parameters') p(key) WHERE p.key IN ('__proto__','constructor','prototype') OR NOT selected.envelope#>'{parameterSchema,properties}' ? p.key) AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements_text(selected.envelope#>'{parameterSchema,required}') required(key) WHERE NOT candidate->'parameters' ? required.key) AND NOT EXISTS (SELECT 1 FROM jsonb_each(candidate->'parameters') p WHERE jsonb_typeof(p.value) NOT IN ('string','number','boolean'))) IS NOT TRUE THEN RAISE EXCEPTION 'Experiment candidates require contiguous indexes, keys and complete scalar parameters' USING ERRCODE='23514'; END IF; candidate_index := candidate_index+1; END LOOP; IF (SELECT count(DISTINCT value->>'trialKey') FROM jsonb_array_elements(candidate_row.preview->'candidates'))<>candidate_index OR (SELECT count(DISTINCT value->'parameters') FROM jsonb_array_elements(candidate_row.preview->'candidates'))<>candidate_index THEN RAISE EXCEPTION 'Experiment candidates must be unique' USING ERRCODE='23514'; END IF; RETURN; END $$; CREATE OR REPLACE FUNCTION require_experiment_manifest() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN PERFORM validate_experiment_manifest(NEW); RETURN NEW; END $$; DROP TRIGGER IF EXISTS experiment_manifest_admission ON research_experiments; CREATE TRIGGER experiment_manifest_admission BEFORE INSERT ON research_experiments FOR EACH ROW WHEN (NEW.validation_phase IS NULL) EXECUTE FUNCTION require_experiment_manifest(); CREATE OR REPLACE FUNCTION assert_validation_phase_preview(value JSONB, manifest JSONB, phase TEXT, winner JSONB DEFAULT NULL, review_id TEXT DEFAULT NULL) RETURNS void LANGUAGE plpgsql AS $$ DECLARE partition JSONB; request JSONB; candidates JSONB; expected JSONB; BEGIN partition := manifest->'partitions'->CASE phase WHEN 'train' THEN 0 WHEN 'validation' THEN 1 WHEN 'test' THEN 2 ELSE -1 END; request := partition->'request'; IF phase='train' THEN candidates := manifest#>'{source,candidates}'; ELSE IF winner IS NULL OR review_id IS NULL THEN RAISE EXCEPTION 'Holdout requires frozen winner and approval' USING ERRCODE='23514'; END IF; request := jsonb_set(request,'{strategy,selection,parameters}',winner->'parameters'); request := jsonb_set(request,'{strategy,reviewId}',to_jsonb(review_id)); candidates := jsonb_build_array(jsonb_set(winner,'{index}','0'::jsonb)); END IF; expected := jsonb_build_object('version','research-experiment-preview/v1','input',jsonb_build_object( 'backtestId',manifest#>'{input,backtestId}','name',(manifest#>>'{input,name}')||' · '||phase, 'grid',CASE WHEN phase='train' THEN manifest#>'{input,grid}' ELSE '{}'::jsonb END), 'request',request,'dataset',partition->'dataset','candidates',candidates); IF ((value-'previewHash')=expected AND value->>'previewHash' ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN RAISE EXCEPTION 'Validation phase must preserve its exact frozen request, data and candidate' USING ERRCODE='23514'; END IF; END $$; CREATE OR REPLACE FUNCTION assert_validation_preparation(manifest JSONB) RETURNS void LANGUAGE plpgsql AS $$ DECLARE source JSONB; retained JSONB; slice JSONB; partition JSONB; bounds JSONB; bar JSONB; calendar JSONB; phase TEXT; idx INTEGER := 0; candidate JSONB; required_history INTEGER := 0; n INTEGER; warmup BIGINT; start_at BIGINT; end_at BIGINT; prior_end BIGINT := NULL; total INTEGER; available_warmup INTEGER; admitted INTEGER; evaluation INTEGER; terminal INTEGER; delayed INTEGER; previous_event BIGINT; previous_sequence BIGINT; event_at BIGINT; sequence BIGINT; arrival BIGINT; expected_bars JSONB; expected_manifest JSONB; expected_request JSONB; initial_session JSONB; boundaries JSONB; counts JSONB; BEGIN source := manifest->'source'; IF (manifest->>'version'='chronological-validation-preview/v1' AND manifest->>'execution'='preview-only' AND manifest->>'previewHash' ~ '^[a-f0-9]{64}$' AND ((manifest->'input')-'recipe')=source->'input' AND manifest#>'{input,recipe,version}'='1'::jsonb AND manifest#>'{input,recipe,labelHorizonMs}'='0'::jsonb AND jsonb_typeof(manifest->'partitions')='array' AND jsonb_array_length(manifest->'partitions')=3 AND manifest->'policy'='{"selection":{"phase":"train","metric":"totalReturn","direction":"maximize","tieBreak":"candidate-index","requireAllCandidates":true},"validationRole":"diagnostic-only","testRole":"holdout-only","reset":"initial-capital-empty-positions","model":"deterministic-unfitted","readiness":"input-checks-only"}'::jsonb) IS NOT TRUE THEN RAISE EXCEPTION 'Validation requires the fixed complete chronological preparation policy' USING ERRCODE='23514'; END IF; SELECT payload INTO retained FROM backtest_datasets WHERE hash=source#>>'{request,datasetHash}'; IF (retained->'manifest'=source->'dataset' AND retained#>>'{manifest,eligibility}'='eligible') IS NOT TRUE THEN RAISE EXCEPTION 'Validation source must equal its retained eligible manifest' USING ERRCODE='23514'; END IF; FOR candidate IN SELECT value FROM jsonb_array_elements(source->'candidates') LOOP IF source#>>'{request,strategy,selection,strategyId}'='sma_crossover' THEN n := (candidate#>>'{parameters,slowPeriod}')::integer+1; ELSIF source#>>'{request,strategy,selection,strategyId}'='mean_reversion' THEN n := GREATEST((candidate#>>'{parameters,lookbackPeriod}')::integer,(candidate#>>'{parameters,trendPeriod}')::integer, (candidate#>>'{parameters,momentumPeriod}')::integer+1,(candidate#>>'{parameters,volatilityPeriod}')::integer+1); ELSE RAISE EXCEPTION 'Unsupported validation strategy' USING ERRCODE='23514'; END IF; required_history := GREATEST(required_history,n); END LOOP; SELECT value INTO calendar FROM jsonb_array_elements(retained#>'{manifest,calendars}') WHERE value->>'id'=retained#>>'{manifest,series,0,calendarId}'; FOREACH phase IN ARRAY ARRAY['train','validation','test'] LOOP partition := manifest->'partitions'->idx; bounds := manifest#>ARRAY['input','recipe',phase]; warmup := (bounds->>'warmupStart')::bigint; start_at := (bounds->>'tradeStart')::bigint; end_at := (bounds->>'tradeEnd')::bigint; IF (partition->>'phase'=phase AND warmup=(retained#>>'{manifest,bounds,warmupStart}')::bigint AND start_at>=(retained#>>'{manifest,bounds,tradeStart}')::bigint AND end_at<=(retained#>>'{manifest,bounds,tradeEnd}')::bigint AND (prior_end IS NULL OR prior_end<=start_at) AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(retained->'bars') b, unnest(ARRAY[warmup,start_at,end_at]) boundary WHERE (b->>'intervalStart')::bigint>'intervalEnd')::bigint)) IS NOT TRUE THEN RAISE EXCEPTION 'Validation windows must be exact chronological in-source boundaries' USING ERRCODE='23514'; END IF; SELECT COALESCE(jsonb_agg(value ORDER BY ordinality),'[]'::jsonb) INTO expected_bars FROM jsonb_array_elements(retained->'bars') WITH ORDINALITY WHERE (value->>'intervalStart')::bigint>=warmup AND (value->>'intervalEnd')::bigint<=end_at; total := jsonb_array_length(expected_bars); expected_manifest := ((retained->'manifest')-'hash'-'bounds'-'barCount') || jsonb_build_object('hash',partition#>'{dataset,hash}','bounds',bounds,'barCount',total); SELECT payload INTO slice FROM backtest_datasets WHERE hash=partition#>>'{dataset,hash}'; IF (total>0 AND slice->'bars'=expected_bars AND slice->'manifest'=expected_manifest AND partition->'dataset'=expected_manifest AND partition#>>'{dataset,hash}' ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN RAISE EXCEPTION 'Validation slice must preserve exact source bars, availability and metadata' USING ERRCODE='23514'; END IF; available_warmup:=0; admitted:=0; evaluation:=0; terminal:=0; delayed:=0; previous_event:=NULL; previous_sequence:=NULL; FOR bar IN SELECT value FROM jsonb_array_elements(expected_bars) LOOP arrival:=(bar->>'availableAt')::bigint; event_at:=(bar->>'eventTime')::bigint; sequence:=(bar->>'sourceSequence')::bigint; IF arrivalprevious_event OR (event_at=previous_event AND sequence>previous_sequence) THEN admitted:=admitted+1; previous_event:=event_at; previous_sequence:=sequence; END IF; ELSIF arrival'counts'=counts AND (partition->>'requiredWarmup')::integer=required_history AND admitted>=required_history AND evaluation>0 AND jsonb_typeof(partition->'warnings')='array') IS NOT TRUE THEN RAISE EXCEPTION 'Validation history readiness and availability counts must be exact' USING ERRCODE='23514'; END IF; SELECT value INTO initial_session FROM jsonb_array_elements(calendar->'sessions') WHERE (value->>'open')::bigint<=warmup ORDER BY (value->>'open')::bigint DESC LIMIT 1; SELECT COALESCE(jsonb_agg(jsonb_build_object('calendarId',calendar->'id','calendarRevision',calendar->'revision','sessionId',value->'date','startsAt',value->'open') ORDER BY ordinality),'[]'::jsonb) INTO boundaries FROM jsonb_array_elements(calendar->'sessions') WITH ORDINALITY WHERE (value->>'open')::bigint>warmup AND (value->>'open')::bigint<=end_at; expected_request:=jsonb_set(source->'request','{datasetHash}',partition#>'{dataset,hash}'); expected_request:=jsonb_set(expected_request,'{policy,matching,risk,ledger,riskSession}',jsonb_build_object('calendarId',calendar->'id','calendarRevision',calendar->'revision','sessionId',initial_session->'date','startsAt',initial_session->'open')); expected_request:=jsonb_set(expected_request,'{policy,risk_boundaries}',boundaries); IF (initial_session IS NOT NULL AND partition->'request'=expected_request) IS NOT TRUE THEN RAISE EXCEPTION 'Validation phases may change only their dataset and exact retained account clock' USING ERRCODE='23514'; END IF; idx:=idx+1; prior_end:=end_at; END LOOP; END $$; CREATE OR REPLACE FUNCTION require_validation_experiment() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE source_row research_experiments; root research_experiments; selected RECORD; approval RECORD; phase_id TEXT; BEGIN IF NEW.validation_selection IS NOT NULL OR NEW.validation_report IS NOT NULL OR NEW.cancel_requested THEN RAISE EXCEPTION 'New validation phases cannot invent selection, report or cancellation' USING ERRCODE='23514'; END IF; IF NEW.validation_phase='train' THEN source_row:=NEW; source_row.preview:=NEW.validation_manifest->'source'; source_row.preview_hash:=source_row.preview->>'previewHash'; source_row.name:=source_row.preview#>>'{input,name}'; PERFORM validate_experiment_manifest(source_row); PERFORM assert_validation_preparation(NEW.validation_manifest); PERFORM assert_validation_phase_preview(NEW.preview,NEW.validation_manifest,'train'); ELSE -- The service already holds the parent; direct insert follows the same order. PERFORM 1 FROM backtests WHERE id=NEW.backtest_id AND archived_at IS NULL FOR UPDATE; IF NOT FOUND THEN RAISE EXCEPTION 'Holdout requires an active parent' USING ERRCODE='23514'; END IF; SELECT * INTO root FROM research_experiments WHERE id=NEW.validation_parent_id FOR UPDATE; phase_id:=root.validation_selection#>>ARRAY['holdoutExperimentIds',NEW.validation_phase]; IF (root.validation_phase='train' AND NOT root.cancel_requested AND root.validation_selection IS NOT NULL AND root.backtest_id=NEW.backtest_id AND phase_id=NEW.id::text AND NEW.name=(root.validation_manifest#>>'{input,name}')||' · '||NEW.validation_phase AND NEW.submission_principal=root.validation_selection->>'principal' AND NEW.submission_key='validation-child:'||NEW.id::text) IS NOT TRUE THEN RAISE EXCEPTION 'Holdout must belong to its uncancelled frozen training selection' USING ERRCODE='23514'; END IF; SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id WHERE v.id::text=root.validation_manifest#>>'{source,request,strategy,versionId}' FOR UPDATE OF s; SELECT id,decision INTO approval FROM strategy_review_events WHERE version_id=selected.id ORDER BY ordinal DESC LIMIT 1; IF (selected.origin='builtin' AND selected.family_archived IS NULL AND approval.decision='approve' AND root.validation_selection->>'reviewId'=approval.id::text AND root.validation_manifest#>'{source,request,strategy,package}'=selected.envelope) IS NOT TRUE THEN RAISE EXCEPTION 'Holdout requires current approval of the original frozen version' USING ERRCODE='23514'; END IF; PERFORM assert_validation_phase_preview(NEW.preview,root.validation_manifest,NEW.validation_phase,root.validation_selection->'winner',root.validation_selection->>'reviewId'); END IF; IF (NEW.preview->>'previewHash'=NEW.preview_hash AND NEW.preview#>>'{input,name}'=NEW.name AND NEW.preview#>>'{input,backtestId}'=NEW.backtest_id::text) IS NOT TRUE THEN RAISE EXCEPTION 'Validation phase row identity must match its preview' USING ERRCODE='23514'; END IF; RETURN NEW; END $$; DROP TRIGGER IF EXISTS validation_experiment_admission ON research_experiments; CREATE TRIGGER validation_experiment_admission BEFORE INSERT ON research_experiments FOR EACH ROW WHEN (NEW.validation_phase IS NOT NULL) EXECUTE FUNCTION require_validation_experiment(); -- Copies/provenance checks only. Existing Rust results and verified canonical reporting own economics. CREATE OR REPLACE FUNCTION assert_validation_evidence(item JSONB, phase_experiment_id UUID, phase TEXT, source_index INTEGER) RETURNS numeric LANGUAGE plpgsql AS $$ DECLARE experiment research_experiments; run RECORD; result JSONB; expected_request JSONB; expected JSONB; candidate JSONB; analysis_policy JSONB; metric RECORD; BEGIN SELECT * INTO experiment FROM research_experiments WHERE id=phase_experiment_id; SELECT r.*,br.canonical_result INTO run FROM runs r LEFT JOIN backtest_results br ON br.run_id=r.id WHERE r.id::text=item->>'runId' AND r.experiment_id=phase_experiment_id; result:=run.canonical_result; candidate:=experiment.preview->'candidates'->run.trial_index; expected_request:=jsonb_set(experiment.preview->'request','{runId}',to_jsonb(run.id::text)); expected_request:=jsonb_set(expected_request,'{policy,matching,risk,ledger,sessionId}',to_jsonb(run.id::text)); expected_request:=jsonb_set(expected_request,'{policy,matching,risk,ledger,accountId}',to_jsonb('research:'||run.id::text)); expected_request:=jsonb_set(expected_request,'{strategy,selection,parameters}',candidate->'parameters'); analysis_policy:=(expected_request->'analyticsPolicy') || jsonb_build_object( 'calendarId',expected_request#>'{policy,matching,risk,ledger,riskSession,calendarId}', 'calendarRevision',expected_request#>'{policy,matching,risk,ledger,riskSession,calendarRevision}', 'sampling','account-boundary-after-observations-v1','marks','last-available-no-per-session-freshness-certification', 'returnUnit','fraction','variance','sample-n-minus-one','riskFreeConversion','annual-rate-divided-by-periods-per-year', 'downside','full-series-rms-relative-to-risk-free','partialPeriods','visible-excluded-from-periodic-statistics', 'drawdown','session-end-and-terminal-sampled','exposureBasis','elapsed-calendar-time', 'cagrBasis','elapsed-calendar-days-365','zeroTerminalCagr','negative-one-for-positive-elapsed-time'); IF (experiment.id IS NOT NULL AND NOT experiment.cancel_requested AND experiment.validation_phase=phase AND run.id IS NOT NULL AND run.status='completed' AND NOT run.cancel_requested AND run.backtest_id=experiment.backtest_id AND candidate->>'index'=run.trial_index::text AND candidate->>'trialKey'=run.trial_key AND run.request_snapshot=expected_request AND run.dataset_hash=expected_request->>'datasetHash' AND result->>'kind'='canonical-result/v1' AND result->>'status'='completed' AND result->>'financialEngine'='rust' AND result->>'strategyExecution'='typescript-retained-builtin/v1' AND result->>'runId'=run.id::text AND result->>'backtestId'=run.backtest_id::text AND result->'request'=expected_request AND result#>'{financial,identity}'=jsonb_build_object('version',1,'sessionId',run.id::text,'datasetHash',run.dataset_hash) AND result#>'{financial,policy}'=expected_request->'policy' AND result#>'{analytics,version}'='1'::jsonb AND result#>'{analytics,policy}'=analysis_policy AND jsonb_typeof(result#>'{analytics,metrics}')='object' AND jsonb_typeof(result#>'{analytics,unavailable}')='object' AND jsonb_typeof(result#>'{financial,limitations}')='array' AND jsonb_typeof(result#>'{financial,modelLimitations}')='array') IS NOT TRUE THEN RAISE EXCEPTION 'Validation evidence requires the exact complete uncancelled canonical phase result and policy' USING ERRCODE='23514'; END IF; FOR metric IN SELECT * FROM jsonb_each(result#>'{analytics,metrics}') LOOP IF jsonb_typeof(metric.value) NOT IN ('null','number') OR (metric.value='null'::jsonb) IS DISTINCT FROM (result#>'{analytics,unavailable}' ? metric.key) THEN RAISE EXCEPTION 'Validation metric availability must remain truthful' USING ERRCODE='23514'; END IF; END LOOP; expected:=jsonb_build_object('phase',phase,'experimentId',phase_experiment_id::text,'runId',run.id::text, 'sourceCandidateIndex',source_index,'trialKey',candidate->'trialKey','parameters',candidate->'parameters', 'datasetHash',run.dataset_hash,'requestHash',item->'requestHash','economicHash',item->'economicHash', 'metrics',result#>'{analytics,metrics}','unavailable',result#>'{analytics,unavailable}', 'completePeriodCount',result#>'{analytics,completePeriodCount}','periodicSampleCount',result#>'{analytics,periodicSampleCount}', 'fillCount',result#>'{analytics,fillCount}','limitations',(result#>'{financial,limitations}')||(result#>'{financial,modelLimitations}')); IF (item=expected AND item->>'requestHash' ~ '^[a-f0-9]{64}$' AND item->>'economicHash' ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN RAISE EXCEPTION 'Validation evidence must copy the precise retained result facts' USING ERRCODE='23514'; END IF; IF phase='train' AND jsonb_typeof(result#>'{analytics,metrics,totalReturn}') IS DISTINCT FROM 'number' THEN RAISE EXCEPTION 'Every training return must be a finite available number' USING ERRCODE='23514'; END IF; RETURN (result#>>'{analytics,metrics,totalReturn}')::numeric; END $$; CREATE OR REPLACE FUNCTION protect_validation_evidence() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE document JSONB; candidate JSONB; item JSONB; idx INTEGER; winner_index INTEGER; best numeric; score numeric; selected RECORD; approval RECORD; root research_experiments; phase TEXT; child_id UUID; BEGIN IF NEW.validation_manifest IS DISTINCT FROM OLD.validation_manifest OR NEW.validation_parent_id IS DISTINCT FROM OLD.validation_parent_id OR NEW.validation_phase IS DISTINCT FROM OLD.validation_phase THEN RAISE EXCEPTION 'Validation preparation and phase lineage are immutable' USING ERRCODE='23514'; END IF; IF OLD.validation_selection IS NOT NULL AND NEW.validation_selection IS DISTINCT FROM OLD.validation_selection THEN RAISE EXCEPTION 'Validation selection is write once' USING ERRCODE='23514'; END IF; IF OLD.validation_report IS NOT NULL AND NEW.validation_report IS DISTINCT FROM OLD.validation_report THEN RAISE EXCEPTION 'Validation report is write once' USING ERRCODE='23514'; END IF; IF OLD.validation_selection IS NULL AND NEW.validation_selection IS NOT NULL THEN document:=NEW.validation_selection; IF (NEW.validation_phase='train' AND NOT NEW.cancel_requested AND OLD.validation_report IS NULL AND document->>'version'='chronological-validation-selection/v1' AND document->>'validationId'=NEW.id::text AND document->>'previewHash'=NEW.validation_manifest->>'previewHash' AND document->>'selectionHash' ~ '^[a-f0-9]{64}$' AND document->>'id' ~ '^[a-f0-9-]{36}$' AND (document->>'createdAt')::timestamptz IS NOT NULL AND document->>'principal' IN ('operator','service') AND document#>>'{_receipt,key}' ~ '^[!-~]{1,200}$' AND document#>>'{_receipt,hash}' ~ '^[a-f0-9]{64}$' AND jsonb_typeof(document->'training')='array' AND jsonb_array_length(document->'training')=jsonb_array_length(NEW.preview->'candidates') AND (SELECT count(*) FROM runs WHERE experiment_id=NEW.id)=jsonb_array_length(NEW.preview->'candidates') AND NOT EXISTS (SELECT 1 FROM research_experiments WHERE validation_parent_id=NEW.id) AND document#>>'{holdoutExperimentIds,validation}' ~ '^[a-f0-9-]{36}$' AND document#>>'{holdoutExperimentIds,test}' ~ '^[a-f0-9-]{36}$' AND document#>>'{holdoutExperimentIds,validation}'<>document#>>'{holdoutExperimentIds,test}') IS NOT TRUE THEN RAISE EXCEPTION 'Selection requires a complete uncancelled training experiment and immutable receipt' USING ERRCODE='23514'; END IF; idx:=0; best:=NULL; winner_index:=NULL; FOR item IN SELECT value FROM jsonb_array_elements(document->'training') LOOP score:=assert_validation_evidence(item,NEW.id,'train',idx); candidate:=NEW.preview->'candidates'->idx; IF item->>'trialKey' IS DISTINCT FROM candidate->>'trialKey' THEN RAISE EXCEPTION 'Training evidence must follow original candidate order' USING ERRCODE='23514'; END IF; IF best IS NULL OR score>best THEN best:=score; winner_index:=idx; END IF; idx:=idx+1; END LOOP; IF document->'winner' IS DISTINCT FROM NEW.preview->'candidates'->winner_index THEN RAISE EXCEPTION 'Winner must maximize training return with original-index tie break' USING ERRCODE='23514'; END IF; SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id WHERE v.id::text=NEW.validation_manifest#>>'{source,request,strategy,versionId}' FOR UPDATE OF s; SELECT id,decision INTO approval FROM strategy_review_events WHERE version_id=selected.id ORDER BY ordinal DESC LIMIT 1; IF (selected.origin='builtin' AND selected.family_archived IS NULL AND approval.decision='approve' AND document->>'reviewId'=approval.id::text AND NEW.validation_manifest#>'{source,request,strategy,package}'=selected.envelope) IS NOT TRUE THEN RAISE EXCEPTION 'New holdouts require current approval of their original version' USING ERRCODE='23514'; END IF; END IF; IF OLD.validation_report IS NULL AND NEW.validation_report IS NOT NULL THEN document:=NEW.validation_report; IF (NEW.validation_phase='train' AND NOT NEW.cancel_requested AND OLD.validation_selection IS NOT NULL AND document->>'version'='chronological-validation-report/v1' AND document->>'validationId'=NEW.id::text AND document->>'previewHash'=NEW.validation_manifest->>'previewHash' AND document->>'selectionHash'=OLD.validation_selection->>'selectionHash' AND document->>'reportHash' ~ '^[a-f0-9]{64}$' AND document->>'id' ~ '^[a-f0-9-]{36}$' AND (document->>'createdAt')::timestamptz IS NOT NULL AND document->>'principal' IN ('operator','service') AND document#>>'{_receipt,key}' ~ '^[!-~]{1,200}$' AND document#>>'{_receipt,hash}' ~ '^[a-f0-9]{64}$' AND document->'training'=OLD.validation_selection->'training' AND document->>'reset'='initial-capital-empty-positions' AND jsonb_typeof(document->'limitations')='array') IS NOT TRUE THEN RAISE EXCEPTION 'Report requires exact frozen selection and independent reset evidence' USING ERRCODE='23514'; END IF; idx:=0; FOR item IN SELECT value FROM jsonb_array_elements(document->'training') LOOP PERFORM assert_validation_evidence(item,NEW.id,'train',idx); idx:=idx+1; END LOOP; FOREACH phase IN ARRAY ARRAY['validation','test'] LOOP child_id:=(OLD.validation_selection#>>ARRAY['holdoutExperimentIds',phase])::uuid; IF NOT EXISTS (SELECT 1 FROM research_experiments WHERE id=child_id AND validation_parent_id=NEW.id AND validation_phase=phase AND NOT cancel_requested) OR (SELECT count(*) FROM runs WHERE experiment_id=child_id)<>1 THEN RAISE EXCEPTION 'Report requires each exact complete holdout child' USING ERRCODE='23514'; END IF; PERFORM assert_validation_evidence(document->phase,child_id,phase,(OLD.validation_selection#>>'{winner,index}')::integer); END LOOP; END IF; RETURN NEW; END $$; DROP TRIGGER IF EXISTS validation_evidence_identity ON research_experiments; CREATE TRIGGER validation_evidence_identity BEFORE UPDATE ON research_experiments FOR EACH ROW EXECUTE FUNCTION protect_validation_evidence(); CREATE OR REPLACE FUNCTION require_complete_validation_admission() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE current research_experiments; child research_experiments; candidate JSONB; phase TEXT; BEGIN SELECT * INTO current FROM research_experiments WHERE id=NEW.id; IF current.validation_phase IS NULL THEN RETURN NULL; END IF; IF (SELECT count(*) FROM runs WHERE experiment_id=current.id)<>jsonb_array_length(current.preview->'candidates') OR EXISTS (SELECT 1 FROM runs r LEFT JOIN backtest_dispatch d ON d.run_id=r.id WHERE r.experiment_id=current.id AND d.run_id IS NULL) THEN RAISE EXCEPTION 'Validation admission requires its complete exact run and durable outbox set' USING ERRCODE='23514'; END IF; IF current.validation_phase='train' AND current.validation_selection IS NOT NULL THEN IF (SELECT count(*) FROM research_experiments WHERE validation_parent_id=current.id)<>2 THEN RAISE EXCEPTION 'Selection must atomically admit both holdout experiments' USING ERRCODE='23514'; END IF; FOREACH phase IN ARRAY ARRAY['validation','test'] LOOP SELECT * INTO child FROM research_experiments WHERE id::text=current.validation_selection#>>ARRAY['holdoutExperimentIds',phase] AND validation_parent_id=current.id AND validation_phase=phase; IF child.id IS NULL OR (SELECT count(*) FROM runs WHERE experiment_id=child.id)<>1 OR NOT EXISTS (SELECT 1 FROM runs r JOIN backtest_dispatch d ON d.run_id=r.id WHERE r.experiment_id=child.id) THEN RAISE EXCEPTION 'Selection must atomically retain each singleton holdout and durable outbox' USING ERRCODE='23514'; END IF; END LOOP; END IF; RETURN NULL; END $$; DROP TRIGGER IF EXISTS validation_admission_complete ON research_experiments; CREATE CONSTRAINT TRIGGER validation_admission_complete AFTER INSERT OR UPDATE OF validation_selection ON research_experiments DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION require_complete_validation_admission(); CREATE OR REPLACE FUNCTION cascade_validation_cancellation() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE child RECORD; BEGIN -- UPDATE already owns this row. Never lock upward to the parent from this trigger. IF NEW.validation_phase='train' AND NEW.cancel_requested AND NOT OLD.cancel_requested THEN FOR child IN SELECT id FROM research_experiments WHERE validation_parent_id=NEW.id ORDER BY CASE validation_phase WHEN 'validation' THEN 0 ELSE 1 END LOOP UPDATE research_experiments SET cancel_requested=TRUE WHERE id=child.id; END LOOP; UPDATE runs SET cancel_requested=TRUE,status=CASE WHEN status='pending' THEN 'cancelled'::run_status ELSE status END, completed_at=CASE WHEN status='pending' THEN NOW() ELSE completed_at END,updated_at=NOW() WHERE (experiment_id=NEW.id OR experiment_id IN (SELECT id FROM research_experiments WHERE validation_parent_id=NEW.id)) AND status IN ('pending','running','paused'); END IF; RETURN NULL; END $$; DROP TRIGGER IF EXISTS validation_cancellation_cascade ON research_experiments; CREATE TRIGGER validation_cancellation_cascade AFTER UPDATE OF cancel_requested ON research_experiments FOR EACH ROW EXECUTE FUNCTION cascade_validation_cancellation();