311 lines
23 KiB
PL/PgSQL
311 lines
23 KiB
PL/PgSQL
-- Explicit cost diagnostics reuse one immutable experiment and the canonical Rust runner.
|
|
-- SQL24's callable v1 validator remains unchanged for chronological/walk-forward admission.
|
|
CREATE OR REPLACE FUNCTION assert_cost_scenario(costs JSONB) RETURNS void LANGUAGE plpgsql IMMUTABLE AS $$ BEGIN
|
|
IF (jsonb_typeof(costs)='object' AND costs-ARRAY['feeRate','slippageRate']='{}'::jsonb
|
|
AND jsonb_typeof(costs->'feeRate')='string' AND costs->>'feeRate' ~ '^(0|1)\.[0-9]{8}$'
|
|
AND (costs->>'feeRate')::numeric BETWEEN 0 AND 1
|
|
AND jsonb_typeof(costs->'slippageRate')='string' AND costs->>'slippageRate' ~ '^0\.[0-9]{8}$') IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Costs must be normalized eight-place fee/slippage fractions within canonical bounds' USING ERRCODE='23514';
|
|
END IF;
|
|
END $$;
|
|
|
|
CREATE OR REPLACE FUNCTION validate_cost_manifest(candidate_row research_experiments) RETURNS void LANGUAGE plpgsql AS $$
|
|
DECLARE source_row research_experiments; manifest JSONB:=candidate_row.preview; source JSONB:=manifest->'source'; candidate JSONB; costs JSONB; idx INTEGER:=0; size INTEGER;
|
|
BEGIN
|
|
IF (manifest->>'version'='cost-sensitivity-preview/v1' AND manifest->>'previewHash'=candidate_row.preview_hash
|
|
AND manifest-ARRAY['version','previewHash','input','source','request','dataset','candidates']='{}'::jsonb
|
|
AND manifest#>>'{input,name}'=candidate_row.name AND manifest#>>'{input,backtestId}'=candidate_row.backtest_id::text
|
|
AND (manifest->'input')-ARRAY['name','backtestId','scenarios']='{}'::jsonb
|
|
AND manifest->'request'=source->'request' AND manifest->'dataset'=source->'dataset'
|
|
AND source->'input'=jsonb_build_object('name',candidate_row.name,'backtestId',candidate_row.backtest_id::text,'grid','{}'::jsonb)
|
|
AND source->>'version'='research-experiment-preview/v1' AND source->>'previewHash' ~ '^[a-f0-9]{64}$'
|
|
AND jsonb_typeof(source->'candidates')='array' AND jsonb_array_length(source->'candidates')=1
|
|
AND source#>'{candidates,0,parameters}'=source#>'{request,strategy,selection,parameters}'
|
|
AND (source#>'{candidates,0}')-ARRAY['index','trialKey','parameters']='{}'::jsonb
|
|
AND jsonb_typeof(manifest#>'{input,scenarios}')='array' AND jsonb_array_length(manifest#>'{input,scenarios}') BETWEEN 1 AND 99
|
|
AND jsonb_typeof(manifest->'candidates')='array') IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Cost experiment requires an exact fixed-parameter empty-grid source and explicit ordered scenarios' USING ERRCODE='23514';
|
|
END IF;
|
|
source_row:=candidate_row; source_row.preview:=source; source_row.preview_hash:=source->>'previewHash';
|
|
PERFORM validate_experiment_manifest(source_row);
|
|
size:=jsonb_array_length(manifest->'candidates');
|
|
IF size<>jsonb_array_length(manifest#>'{input,scenarios}')+1 THEN
|
|
RAISE EXCEPTION 'Every cost scenario and the automatic baseline require one candidate' USING ERRCODE='23514';
|
|
END IF;
|
|
FOR candidate IN SELECT value FROM jsonb_array_elements(manifest->'candidates') LOOP
|
|
costs:=CASE WHEN idx=0 THEN jsonb_build_object('feeRate',source#>'{request,policy,matching,risk,feeRate}','slippageRate',source#>'{request,policy,matching,slippageRate}') ELSE manifest#>ARRAY['input','scenarios',(idx-1)::text] END;
|
|
PERFORM assert_cost_scenario(costs);
|
|
IF (candidate-ARRAY['index','trialKey','parameters','costs']='{}'::jsonb AND candidate->>'index'=idx::text
|
|
AND candidate->>'trialKey' ~ '^[a-f0-9]{64}$' AND candidate->'parameters'=source#>'{request,strategy,selection,parameters}'
|
|
AND candidate->'costs'=costs) IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Cost candidates must preserve fixed parameters, exact ordered costs and contiguous identities' USING ERRCODE='23514';
|
|
END IF;
|
|
idx:=idx+1;
|
|
END LOOP;
|
|
IF (SELECT count(DISTINCT value->'costs') FROM jsonb_array_elements(manifest->'candidates'))<>size
|
|
OR (SELECT count(DISTINCT value->>'trialKey') FROM jsonb_array_elements(manifest->'candidates'))<>size THEN
|
|
RAISE EXCEPTION 'Normalized cost pairs and trial identities must be distinct, including baseline' USING ERRCODE='23514';
|
|
END IF;
|
|
END $$;
|
|
|
|
CREATE OR REPLACE FUNCTION require_experiment_manifest() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
|
|
IF NEW.preview->>'version'='cost-sensitivity-preview/v1' THEN
|
|
PERFORM validate_cost_manifest(NEW);
|
|
ELSE
|
|
IF (NEW.preview-ARRAY['version','previewHash','input','request','dataset','candidates']='{}'::jsonb
|
|
AND (NEW.preview->'input')-ARRAY['backtestId','name','grid']='{}'::jsonb
|
|
AND NOT EXISTS(SELECT 1 FROM jsonb_array_elements(NEW.preview->'candidates') c WHERE c-ARRAY['index','trialKey','parameters']<>'{}'::jsonb)) IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Parameter experiments cannot contain cost-scenario fields' USING ERRCODE='23514';
|
|
END IF;
|
|
PERFORM validate_experiment_manifest(NEW);
|
|
END IF;
|
|
RETURN NEW;
|
|
END $$;
|
|
|
|
-- Shared immutable expected request for initial admission AND manual retry. No financial arithmetic.
|
|
CREATE OR REPLACE FUNCTION experiment_trial_request(manifest JSONB, candidate_index INTEGER, run_id UUID) RETURNS JSONB LANGUAGE plpgsql IMMUTABLE AS $$
|
|
DECLARE candidate JSONB:=manifest->'candidates'->candidate_index; expected JSONB;
|
|
BEGIN
|
|
IF (candidate_index>=0 AND candidate->>'index'=candidate_index::text AND candidate->>'trialKey' ~ '^[a-f0-9]{64}$'
|
|
AND jsonb_typeof(candidate->'parameters')='object' AND run_id IS NOT NULL) IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Trial requires its exact frozen candidate' USING ERRCODE='23514';
|
|
END IF;
|
|
expected:=jsonb_set(manifest->'request','{runId}',to_jsonb(run_id::text));
|
|
expected:=jsonb_set(expected,'{policy,matching,risk,ledger,sessionId}',to_jsonb(run_id::text));
|
|
expected:=jsonb_set(expected,'{policy,matching,risk,ledger,accountId}',to_jsonb('research:'||run_id::text));
|
|
expected:=jsonb_set(expected,'{strategy,selection,parameters}',candidate->'parameters');
|
|
IF manifest->>'version'='cost-sensitivity-preview/v1' THEN
|
|
IF (manifest->'request'=manifest#>'{source,request}' AND candidate->'parameters'=manifest#>'{source,request,strategy,selection,parameters}') IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Cost trial must preserve its exact common source and parameters' USING ERRCODE='23514';
|
|
END IF;
|
|
PERFORM assert_cost_scenario(candidate->'costs');
|
|
expected:=jsonb_set(expected,'{policy,matching,risk,feeRate}',candidate#>'{costs,feeRate}');
|
|
expected:=jsonb_set(expected,'{policy,matching,slippageRate}',candidate#>'{costs,slippageRate}');
|
|
ELSIF manifest->>'version'='research-experiment-preview/v1' THEN
|
|
IF candidate ? 'costs' THEN RAISE EXCEPTION 'Parameter trials cannot override costs' USING ERRCODE='23514'; END IF;
|
|
ELSE RAISE EXCEPTION 'Unknown experiment preview kind' USING ERRCODE='23514';
|
|
END IF;
|
|
RETURN expected;
|
|
END $$;
|
|
|
|
-- Original SQL22 guards, with only trial request reconstruction delegated.
|
|
CREATE OR REPLACE FUNCTION require_active_backtest_for_new_run() RETURNS trigger
|
|
LANGUAGE plpgsql AS $$
|
|
DECLARE parent RECORD; selected RECORD; approval RECORD; retained JSONB; snapshot JSONB; original RECORD; expected JSONB; experiment RECORD; candidate JSONB;
|
|
BEGIN
|
|
SELECT * INTO parent FROM backtests WHERE id=NEW.backtest_id FOR UPDATE;
|
|
IF NOT FOUND THEN RETURN NEW; END IF;
|
|
IF parent.archived_at IS NOT NULL THEN
|
|
RAISE EXCEPTION 'Backtest is archived; restore it before submitting a new run' USING ERRCODE='23514';
|
|
END IF;
|
|
snapshot := NEW.request_snapshot;
|
|
IF NEW.experiment_id IS NOT NULL THEN
|
|
SELECT * INTO experiment FROM research_experiments WHERE id=NEW.experiment_id FOR UPDATE;
|
|
candidate := experiment.preview->'candidates'->NEW.trial_index;
|
|
IF (experiment.id IS NOT NULL AND experiment.backtest_id=NEW.backtest_id AND NOT experiment.cancel_requested
|
|
AND NEW.trial_index>=0 AND candidate->>'index'=NEW.trial_index::text
|
|
AND candidate->>'trialKey'=NEW.trial_key
|
|
AND NEW.original_run_id IS NULL AND NEW.submission_principal IS NULL
|
|
AND NEW.submission_key IS NULL AND NEW.submission_hash IS NULL
|
|
AND NEW.status='pending' AND NEW.speed_multiplier IS NULL
|
|
AND NEW.dataset_hash=experiment.preview#>>'{request,datasetHash}') IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Experiment trial requires its uncancelled manifest, exact candidate and no individual receipt or lineage' 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=experiment.preview#>>'{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 experiment.preview#>>'{request,strategy,reviewId}'=approval.id::text
|
|
AND experiment.preview#>>'{request,strategy,familyId}'=selected.strategy_id::text
|
|
AND experiment.preview#>'{request,strategy,package}'=selected.envelope) IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Experiment requires its current approved original retained built-in version' USING ERRCODE='23514';
|
|
END IF;
|
|
expected := experiment_trial_request(experiment.preview,NEW.trial_index,NEW.id);
|
|
IF snapshot IS DISTINCT FROM expected THEN
|
|
RAISE EXCEPTION 'Experiment trial must preserve its exact frozen request and candidate parameters' USING ERRCODE='23514';
|
|
END IF;
|
|
SELECT payload INTO retained FROM backtest_datasets WHERE hash=NEW.dataset_hash;
|
|
IF (retained#>>'{manifest,version}'='2' AND retained#>>'{manifest,eligibility}'='eligible'
|
|
AND retained->'manifest'=experiment.preview->'dataset'
|
|
AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1
|
|
AND jsonb_array_length(retained#>'{manifest,series}')=1
|
|
AND snapshot#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}'
|
|
AND snapshot#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}') IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Experiment requires the same eligible retained single-asset dataset' USING ERRCODE='23514';
|
|
END IF;
|
|
RETURN NEW;
|
|
END IF;
|
|
IF NEW.original_run_id IS NOT NULL THEN
|
|
SELECT r.*,br.canonical_result INTO original FROM runs r
|
|
LEFT JOIN backtest_results br ON br.run_id=r.id WHERE r.id=NEW.original_run_id;
|
|
IF (original.id IS NOT NULL AND original.id<>NEW.id
|
|
AND original.backtest_id=NEW.backtest_id AND original.status='completed'
|
|
AND original.request_snapshot->>'kind'='canonical-research/v1'
|
|
AND original.request_snapshot->>'runId'=original.id::text
|
|
AND original.request_snapshot->>'backtestId'=NEW.backtest_id::text
|
|
AND original.request_snapshot->>'datasetHash'=original.dataset_hash
|
|
AND original.canonical_result->>'kind'='canonical-result/v1'
|
|
AND original.canonical_result->>'status'='completed'
|
|
AND original.canonical_result->>'runId'=original.id::text
|
|
AND original.canonical_result->>'backtestId'=NEW.backtest_id::text
|
|
AND original.canonical_result->'request'=original.request_snapshot
|
|
AND original.canonical_result->>'financialEngine'='rust'
|
|
AND original.canonical_result->>'strategyExecution'='typescript-retained-builtin/v1'
|
|
AND NEW.dataset_hash=original.dataset_hash
|
|
AND NEW.status='pending' AND NEW.speed_multiplier IS NULL
|
|
AND NEW.submission_principal IN ('operator','service')
|
|
AND NEW.submission_key ~ '^[!-~]{1,200}$'
|
|
AND NEW.submission_hash ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Reproduction requires a completed canonical source in the same backtest and a submission receipt' 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=original.request_snapshot#>>'{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 original.request_snapshot#>>'{strategy,origin}'='builtin'
|
|
AND original.request_snapshot#>>'{strategy,familyId}'=selected.strategy_id::text
|
|
AND original.request_snapshot#>'{strategy,package}'=selected.envelope) IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Reproduction requires the currently approved original retained built-in version' USING ERRCODE='23514';
|
|
END IF;
|
|
expected := jsonb_set(original.request_snapshot, '{runId}', to_jsonb(NEW.id::text));
|
|
expected := jsonb_set(expected, '{policy,matching,risk,ledger,sessionId}', to_jsonb(NEW.id::text));
|
|
expected := jsonb_set(expected, '{policy,matching,risk,ledger,accountId}', to_jsonb('research:'||NEW.id::text));
|
|
expected := jsonb_set(expected, '{strategy,reviewId}', to_jsonb(approval.id::text));
|
|
IF snapshot IS DISTINCT FROM expected THEN
|
|
RAISE EXCEPTION 'Reproduction must preserve the original frozen request except run identities and current approval' USING ERRCODE='23514';
|
|
END IF;
|
|
SELECT payload INTO retained FROM backtest_datasets WHERE hash=NEW.dataset_hash;
|
|
IF (retained#>>'{manifest,version}'='2'
|
|
AND retained#>>'{manifest,eligibility}'='eligible'
|
|
AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1
|
|
AND jsonb_array_length(retained#>'{manifest,series}')=1
|
|
AND jsonb_array_length(snapshot#>'{policy,matching,series}')=1
|
|
AND jsonb_array_length(snapshot#>'{policy,matching,owners}')=1
|
|
AND jsonb_array_length(snapshot#>'{policy,matching,risk,ledger,ownerIds}')=1
|
|
AND snapshot#>>'{policy,allow_exploratory}'='false'
|
|
AND snapshot#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}'
|
|
AND snapshot#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}') IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Reproduction requires the original eligible retained single-asset dataset' USING ERRCODE='23514';
|
|
END IF;
|
|
RETURN NEW;
|
|
END IF;
|
|
IF parent.strategy_version_id IS NULL AND parent.strategy <> 'catalog' THEN
|
|
IF snapshot->>'kind'='canonical-research/v1' THEN
|
|
RAISE EXCEPTION 'Canonical research requires a catalog template' USING ERRCODE='23514';
|
|
END IF;
|
|
RETURN NEW;
|
|
END IF;
|
|
IF (snapshot->>'kind'='canonical-research/v1'
|
|
AND snapshot->>'runId'=NEW.id::text
|
|
AND snapshot->>'backtestId'=NEW.backtest_id::text
|
|
AND snapshot#>>'{strategy,versionId}'=parent.strategy_version_id::text
|
|
AND snapshot->>'datasetHash'=NEW.dataset_hash
|
|
AND NEW.status='pending' AND NEW.speed_multiplier IS NULL) IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Catalog strategy execution requires an admitted canonical request' USING ERRCODE='23514';
|
|
END IF;
|
|
-- This is the same family lock used by operator review and archive. Later
|
|
-- review changes affect new admissions, never rewrite accepted snapshots.
|
|
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=parent.strategy_version_id ORDER BY ordinal DESC LIMIT 1;
|
|
IF (selected.origin='builtin' AND selected.family_archived IS NULL
|
|
AND approval.decision='approve'
|
|
AND snapshot#>>'{strategy,origin}'='builtin'
|
|
AND snapshot#>>'{strategy,familyId}'=selected.strategy_id::text
|
|
AND snapshot#>>'{strategy,reviewId}'=approval.id::text
|
|
AND snapshot#>'{strategy,package}'=selected.envelope
|
|
AND snapshot#>'{strategy,selection,parameters}'=parent.strategy_parameters
|
|
AND snapshot#>>'{strategy,selection,ownerId}'='strategy:'||selected.id::text) IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Canonical research requires the exact approved retained built-in version' USING ERRCODE='23514';
|
|
END IF;
|
|
SELECT payload INTO retained FROM backtest_datasets WHERE hash=NEW.dataset_hash;
|
|
IF (retained#>>'{manifest,version}'='2'
|
|
AND retained#>>'{manifest,eligibility}'='eligible'
|
|
AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1
|
|
AND jsonb_array_length(retained#>'{manifest,series}')=1
|
|
AND jsonb_array_length(snapshot#>'{policy,matching,series}')=1
|
|
AND jsonb_array_length(snapshot#>'{policy,matching,owners}')=1
|
|
AND jsonb_array_length(snapshot#>'{policy,matching,risk,ledger,ownerIds}')=1
|
|
AND snapshot#>>'{policy,allow_exploratory}'='false'
|
|
AND snapshot#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}'
|
|
AND snapshot#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}'
|
|
AND snapshot#>>'{policy,matching,series,0,instrumentId}'=snapshot#>>'{strategy,selection,instrumentId}'
|
|
AND snapshot#>>'{policy,matching,series,0,seriesId}'=snapshot#>>'{strategy,selection,seriesId}') IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Canonical research requires one eligible retained v2 execution asset' USING ERRCODE='23514';
|
|
END IF;
|
|
RETURN NEW;
|
|
END $$;
|
|
|
|
|
|
-- Original SQL23 failure/history/approval guards, with the same request recipe.
|
|
CREATE OR REPLACE FUNCTION require_experiment_retry_failure() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
DECLARE parent RECORD; experiment RECORD; original RECORD; selected RECORD; approval RECORD; expected JSONB; candidate JSONB; retained JSONB;
|
|
BEGIN
|
|
-- Match the API lock order; worker-owned updates only need the run lock.
|
|
SELECT * INTO parent FROM backtests WHERE id=(SELECT backtest_id FROM research_experiments WHERE id=NEW.experiment_id) FOR UPDATE;
|
|
SELECT * INTO experiment FROM research_experiments WHERE id=NEW.experiment_id FOR UPDATE;
|
|
SELECT * INTO original FROM runs WHERE id=NEW.run_id AND experiment_id=NEW.experiment_id FOR UPDATE;
|
|
IF (parent.id IS NOT NULL AND parent.archived_at IS NULL AND experiment.id IS NOT NULL AND NOT experiment.cancel_requested
|
|
AND original.id IS NOT NULL AND original.backtest_id=parent.id AND original.status='failed' AND NOT original.cancel_requested
|
|
AND NEW.recorded_at=NOW() AND original.trial_key=NEW.trial_key AND original.manual_retry_count<2147483647 AND original.attempt_number<2147483647
|
|
AND NEW.retry_number=original.manual_retry_count+1 AND NEW.previous_attempt_number=original.attempt_number
|
|
AND NEW.previous_attempt_id IS NOT DISTINCT FROM original.attempt_id
|
|
AND NEW.error IS NOT DISTINCT FROM original.error AND NEW.progress IS NOT DISTINCT FROM original.progress
|
|
AND NEW.current_simulation_date IS NOT DISTINCT FROM original.current_simulation_date
|
|
AND NEW.started_at IS NOT DISTINCT FROM original.started_at AND NEW.completed_at IS NOT DISTINCT FROM original.completed_at
|
|
AND NEW.paused_at IS NOT DISTINCT FROM original.paused_at AND NEW.failure_updated_at=original.updated_at
|
|
AND NOT EXISTS (SELECT 1 FROM backtest_results WHERE run_id=original.id)) IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Retry requires the exact current failed experiment trial without cancellation or retained result' USING ERRCODE='23514';
|
|
END IF;
|
|
candidate := experiment.preview->'candidates'->original.trial_index;
|
|
expected := experiment_trial_request(experiment.preview,original.trial_index,original.id);
|
|
IF (candidate->>'index'=original.trial_index::text AND candidate->>'trialKey'=original.trial_key
|
|
AND expected=original.request_snapshot AND expected->>'kind'='canonical-research/v1'
|
|
AND expected->>'backtestId'=original.backtest_id::text AND expected->>'datasetHash'=original.dataset_hash
|
|
AND original.original_run_id IS NULL AND original.speed_multiplier IS NULL) IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Retry must preserve its exact immutable experiment request and candidate' 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=expected#>>'{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 NEW.review_id=approval.id AND expected#>>'{strategy,origin}'='builtin'
|
|
AND expected#>>'{strategy,familyId}'=selected.strategy_id::text
|
|
AND expected#>'{strategy,package}'=selected.envelope) IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Retry requires current approval of the original retained built-in version' USING ERRCODE='23514';
|
|
END IF;
|
|
SELECT payload INTO retained FROM backtest_datasets WHERE hash=original.dataset_hash;
|
|
IF (retained#>>'{manifest,version}'='2' AND retained#>>'{manifest,eligibility}'='eligible'
|
|
AND retained->'manifest'=experiment.preview->'dataset'
|
|
AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1
|
|
AND jsonb_array_length(retained#>'{manifest,series}')=1
|
|
AND expected#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}'
|
|
AND expected#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}') IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Retry requires its retained eligible original dataset' USING ERRCODE='23514';
|
|
END IF;
|
|
RETURN NEW;
|
|
END $$;
|
|
|
|
-- Cost admission cannot retain a receipt with missing children or dispatch work.
|
|
CREATE OR REPLACE FUNCTION require_complete_cost_admission() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
DECLARE experiment research_experiments; expected_count INTEGER;
|
|
BEGIN
|
|
IF TG_TABLE_NAME='research_experiments' THEN experiment:=NEW;
|
|
ELSE SELECT * INTO experiment FROM research_experiments WHERE id=NEW.experiment_id; END IF;
|
|
IF experiment.preview->>'version' IS DISTINCT FROM 'cost-sensitivity-preview/v1' THEN RETURN NULL; END IF;
|
|
expected_count:=jsonb_array_length(experiment.preview->'candidates');
|
|
IF (SELECT count(*) FROM runs WHERE experiment_id=experiment.id)<>expected_count
|
|
OR EXISTS(SELECT 1 FROM runs r LEFT JOIN backtest_dispatch d ON d.run_id=r.id WHERE r.experiment_id=experiment.id
|
|
AND (d.run_id IS NULL OR r.request_snapshot IS DISTINCT FROM experiment_trial_request(experiment.preview,r.trial_index,r.id))) THEN
|
|
RAISE EXCEPTION 'Cost experiment must atomically admit every exact trial and durable dispatch' USING ERRCODE='23514';
|
|
END IF;
|
|
RETURN NULL;
|
|
END $$;
|
|
DROP TRIGGER IF EXISTS cost_experiment_complete ON research_experiments;
|
|
CREATE CONSTRAINT TRIGGER cost_experiment_complete AFTER INSERT ON research_experiments DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION require_complete_cost_admission();
|
|
DROP TRIGGER IF EXISTS cost_trial_complete ON runs;
|
|
CREATE CONSTRAINT TRIGGER cost_trial_complete AFTER INSERT ON runs DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION require_complete_cost_admission();
|