535 lines
43 KiB
PL/PgSQL
535 lines
43 KiB
PL/PgSQL
-- Explicit research principals. Existing financial snapshots, actors and receipts remain unchanged.
|
|
CREATE TABLE IF NOT EXISTS research_agents (
|
|
id TEXT PRIMARY KEY CHECK(id ~ '^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'),
|
|
name TEXT NOT NULL CHECK(length(btrim(name))>0),
|
|
token_hash TEXT NOT NULL UNIQUE CHECK(token_hash ~ '^[a-f0-9]{64}$'),
|
|
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
|
revision INTEGER NOT NULL DEFAULT 1 CHECK(revision>0),
|
|
policy JSONB NOT NULL,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
);
|
|
CREATE TABLE IF NOT EXISTS research_agent_audit (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
agent_id TEXT NOT NULL REFERENCES research_agents(id) ON DELETE RESTRICT,
|
|
operation TEXT NOT NULL, entity_id TEXT NOT NULL,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
);
|
|
ALTER TABLE runs ADD COLUMN IF NOT EXISTS research_agent_id TEXT REFERENCES research_agents(id) ON DELETE RESTRICT;
|
|
ALTER TABLE runs ADD COLUMN IF NOT EXISTS research_limits JSONB;
|
|
ALTER TABLE runs ADD COLUMN IF NOT EXISTS research_deadline_at TIMESTAMPTZ;
|
|
CREATE INDEX IF NOT EXISTS research_agent_active_runs ON runs(research_agent_id,status) WHERE research_agent_id IS NOT NULL;
|
|
CREATE OR REPLACE FUNCTION is_research_actor(value TEXT) RETURNS BOOLEAN LANGUAGE SQL STABLE AS $$
|
|
SELECT value IN ('operator','service') OR EXISTS(SELECT 1 FROM research_agents WHERE id=value)
|
|
$$;
|
|
CREATE OR REPLACE FUNCTION research_grant_policy(request JSONB) RETURNS JSONB LANGUAGE SQL IMMUTABLE AS $$
|
|
SELECT jsonb_build_object('datasetHash',request->'datasetHash','versionId',request#>'{strategy,versionId}',
|
|
'ownerBudget',request#>'{strategy,selection,ownerBudget}','seed',request#>'{strategy,selection,seed}',
|
|
'policy',jsonb_set(jsonb_set(request->'policy','{matching,risk,ledger,sessionId}','"agent-grant-run"'),'{matching,risk,ledger,accountId}','"agent-grant-account"'),
|
|
'analyticsPolicy',request->'analyticsPolicy','build',request->'build','modelArtifacts',request->'modelArtifacts')
|
|
$$;
|
|
CREATE OR REPLACE FUNCTION validate_research_agent_policy() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
DECLARE key TEXT; value JSONB; item JSONB;
|
|
BEGIN
|
|
IF TG_OP='UPDATE' AND (NEW.id IS DISTINCT FROM OLD.id OR NEW.token_hash IS DISTINCT FROM OLD.token_hash OR NEW.created_at IS DISTINCT FROM OLD.created_at OR NEW.revision<>OLD.revision+1) THEN
|
|
RAISE EXCEPTION 'Research principal identity is immutable and policy updates require the next revision' USING ERRCODE='23514';
|
|
END IF;
|
|
IF (jsonb_typeof(NEW.policy)='object' AND NEW.policy->>'version'='1' AND jsonb_typeof(NEW.policy->'allowedProjectIds')='array' AND jsonb_typeof(NEW.policy->'grants')='array' AND jsonb_typeof(NEW.policy->'limits')='object'
|
|
AND NEW.policy-ARRAY['version','allowedProjectIds','grants','limits']='{}'::jsonb
|
|
AND (NEW.policy->'limits')-ARRAY['maxActiveTrials','maxTrialsPerExperiment','maxBarEvaluationsPerExperiment','maxAttemptWallMs','maxAttempts']='{}'::jsonb) IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Invalid research principal policy' USING ERRCODE='23514';
|
|
END IF;
|
|
FOREACH key IN ARRAY ARRAY['maxActiveTrials','maxTrialsPerExperiment','maxBarEvaluationsPerExperiment','maxAttemptWallMs','maxAttempts'] LOOP
|
|
value:=NEW.policy->'limits'->key;
|
|
IF jsonb_typeof(value) IS DISTINCT FROM 'number' THEN RAISE EXCEPTION 'Invalid research resource limit' USING ERRCODE='23514'; END IF;
|
|
IF (value::text)::numeric<1 OR (value::text)::numeric>9007199254740991 OR trunc((value::text)::numeric)<>(value::text)::numeric THEN RAISE EXCEPTION 'Invalid research resource limit' USING ERRCODE='23514'; END IF;
|
|
END LOOP;
|
|
IF (NEW.policy#>>'{limits,maxAttempts}')::numeric>3 OR (NEW.policy#>>'{limits,maxAttemptWallMs}')::numeric>2147483647 THEN RAISE EXCEPTION 'Invalid research attempt budget' USING ERRCODE='23514'; END IF;
|
|
FOR item IN SELECT jsonb_array_elements(NEW.policy->'grants') LOOP
|
|
IF (jsonb_typeof(item)='object' AND item-ARRAY['backtestId','policyHash','policy']='{}'::jsonb AND item->>'backtestId' ~ '^[0-9a-f-]{36}$' AND item->>'policyHash' ~ '^[a-f0-9]{64}$' AND jsonb_typeof(item->'policy')='object') IS NOT TRUE THEN RAISE EXCEPTION 'Invalid research template grant' USING ERRCODE='23514'; END IF;
|
|
END LOOP;
|
|
RETURN NEW;
|
|
END $$;
|
|
DROP TRIGGER IF EXISTS research_agents_policy ON research_agents;
|
|
CREATE TRIGGER research_agents_policy BEFORE INSERT OR UPDATE ON research_agents FOR EACH ROW EXECUTE FUNCTION validate_research_agent_policy();
|
|
DROP TRIGGER IF EXISTS research_agents_retained ON research_agents;
|
|
CREATE TRIGGER research_agents_retained BEFORE DELETE OR TRUNCATE ON research_agents FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation();
|
|
DROP TRIGGER IF EXISTS research_agent_audit_immutable ON research_agent_audit;
|
|
CREATE TRIGGER research_agent_audit_immutable BEFORE UPDATE OR DELETE OR TRUNCATE ON research_agent_audit FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation();
|
|
CREATE OR REPLACE FUNCTION audit_research_agent_policy() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
|
|
INSERT INTO research_agent_audit(agent_id,operation,entity_id) VALUES(NEW.id,'operator-policy-'||lower(TG_OP),NEW.id||':'||NEW.revision::text); RETURN NEW;
|
|
END $$;
|
|
DROP TRIGGER IF EXISTS research_agents_audit ON research_agents;
|
|
CREATE TRIGGER research_agents_audit AFTER INSERT OR UPDATE ON research_agents FOR EACH ROW EXECUTE FUNCTION audit_research_agent_policy();
|
|
|
|
-- Only explicitly named historical role checks are widened. Unknown definitions fail the migration.
|
|
DO $$ DECLARE spec TEXT[]; table_name TEXT; column_name TEXT; constraint_name TEXT; definition TEXT; BEGIN
|
|
FOREACH spec SLICE 1 IN ARRAY ARRAY[
|
|
['strategies','owner_principal'],['strategies','updated_by'],['strategy_versions','created_by'],
|
|
['research_projects','owner_principal'],['research_projects','updated_by'],
|
|
['research_hypotheses','owner_principal'],['research_hypotheses','updated_by'],['research_hypothesis_revisions','submitted_by'],
|
|
['analysis_artifacts','owner_principal'],['analysis_artifacts','updated_by'],['analysis_artifact_revisions','submitted_by'],['research_project_strategies','added_by'],
|
|
['research_experiments','submission_principal'],['experiment_trial_retries','principal'],['research_walk_forwards','submission_principal']
|
|
] LOOP
|
|
table_name:=spec[1]; column_name:=spec[2]; constraint_name:=table_name||'_'||column_name||'_check';
|
|
IF to_regclass(table_name) IS NULL THEN CONTINUE; END IF;
|
|
SELECT pg_get_constraintdef(oid) INTO definition FROM pg_constraint WHERE conrelid=to_regclass(table_name) AND conname=constraint_name;
|
|
IF definition IS NULL OR (position('operator' IN definition)=0 AND position('is_research_actor' IN definition)=0) OR (position('service' IN definition)=0 AND position('is_research_actor' IN definition)=0) THEN RAISE EXCEPTION 'Unexpected role constraint %',constraint_name; END IF;
|
|
IF position('is_research_actor' IN definition)=0 THEN
|
|
EXECUTE format('ALTER TABLE %I DROP CONSTRAINT %I',table_name,constraint_name);
|
|
EXECUTE format('ALTER TABLE %I ADD CONSTRAINT %I CHECK(is_research_actor(%I) IS TRUE)',table_name,constraint_name,column_name);
|
|
END IF;
|
|
END LOOP;
|
|
END $$;
|
|
|
|
CREATE OR REPLACE FUNCTION research_agent_authority(experiment research_experiments) RETURNS JSONB LANGUAGE plpgsql STABLE AS $$
|
|
DECLARE root research_experiments;
|
|
BEGIN
|
|
IF experiment.validation_phase='train' THEN RETURN experiment.validation_manifest#>'{source,request}'; END IF;
|
|
IF experiment.validation_parent_id IS NOT NULL THEN SELECT * INTO root FROM research_experiments WHERE id=experiment.validation_parent_id; RETURN root.validation_manifest#>'{source,request}'; END IF;
|
|
IF experiment.preview->>'version'='cost-sensitivity-preview/v1' THEN RETURN experiment.preview#>'{source,request}'; END IF;
|
|
RETURN experiment.preview->'request';
|
|
END $$;
|
|
CREATE OR REPLACE FUNCTION assert_research_agent_grant(agent research_agents, backtest_id UUID, request JSONB) RETURNS void LANGUAGE plpgsql AS $$ BEGIN
|
|
IF agent.enabled IS DISTINCT FROM TRUE OR NOT EXISTS(SELECT 1 FROM jsonb_array_elements(agent.policy->'grants') g WHERE g->>'backtestId'=backtest_id::text AND g->'policy'=research_grant_policy(request)) THEN
|
|
RAISE EXCEPTION 'research_access:Operator approval of this exact template, dataset and financial policy is required';
|
|
END IF;
|
|
END $$;
|
|
CREATE OR REPLACE FUNCTION research_validation_work(preview JSONB) RETURNS NUMERIC LANGUAGE SQL IMMUTABLE AS $$
|
|
SELECT COALESCE((preview#>>'{partitions,0,dataset,barCount}')::numeric,0)*jsonb_array_length(preview#>'{source,candidates}') + COALESCE((preview#>>'{partitions,1,dataset,barCount}')::numeric,0)+COALESCE((preview#>>'{partitions,2,dataset,barCount}')::numeric,0)
|
|
$$;
|
|
CREATE OR REPLACE FUNCTION guard_agent_experiment() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
DECLARE agent research_agents; planned NUMERIC; work NUMERIC; root_owner TEXT;
|
|
BEGIN
|
|
IF NEW.validation_parent_id IS NOT NULL THEN
|
|
SELECT submission_principal INTO root_owner FROM research_experiments WHERE id=NEW.validation_parent_id;
|
|
IF root_owner LIKE 'agent:%' AND NEW.submission_principal IS DISTINCT FROM root_owner THEN RAISE EXCEPTION 'research_access:Holdouts must retain their owning research principal'; END IF;
|
|
END IF;
|
|
IF NEW.submission_principal NOT LIKE 'agent:%' THEN RETURN NEW; END IF;
|
|
SELECT * INTO agent FROM research_agents WHERE id=NEW.submission_principal FOR UPDATE;
|
|
PERFORM assert_research_agent_grant(agent,NEW.backtest_id,research_agent_authority(NEW));
|
|
IF NEW.validation_phase='train' THEN planned:=jsonb_array_length(NEW.validation_manifest#>'{source,candidates}')+2; work:=research_validation_work(NEW.validation_manifest);
|
|
ELSE planned:=jsonb_array_length(NEW.preview->'candidates'); work:=planned*(NEW.preview#>>'{dataset,barCount}')::numeric; END IF;
|
|
IF (planned <= (agent.policy#>>'{limits,maxTrialsPerExperiment}')::numeric AND work <= (agent.policy#>>'{limits,maxBarEvaluationsPerExperiment}')::numeric) IS NOT TRUE THEN RAISE EXCEPTION 'research_budget:Experiment exceeds its operator trial or observation budget'; END IF;
|
|
INSERT INTO research_agent_audit(agent_id,operation,entity_id) VALUES(agent.id,'experiment-admitted',NEW.id::text);
|
|
RETURN NEW;
|
|
END $$;
|
|
DROP TRIGGER IF EXISTS aa_agent_experiment ON research_experiments;
|
|
CREATE TRIGGER aa_agent_experiment BEFORE INSERT ON research_experiments FOR EACH ROW EXECUTE FUNCTION guard_agent_experiment();
|
|
CREATE OR REPLACE FUNCTION guard_agent_walk_forward() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
DECLARE agent research_agents; work NUMERIC;
|
|
BEGIN
|
|
IF NEW.submission_principal NOT LIKE 'agent:%' THEN RETURN NEW; END IF;
|
|
SELECT * INTO agent FROM research_agents WHERE id=NEW.submission_principal FOR UPDATE;
|
|
PERFORM assert_research_agent_grant(agent,NEW.backtest_id,NEW.preview#>'{source,request}');
|
|
SELECT sum(research_validation_work(segment->'preview')) INTO work FROM jsonb_array_elements(NEW.preview->'windows') segment;
|
|
IF ((NEW.preview#>>'{counts,totalRuns}')::numeric <= (agent.policy#>>'{limits,maxTrialsPerExperiment}')::numeric AND work <= (agent.policy#>>'{limits,maxBarEvaluationsPerExperiment}')::numeric) IS NOT TRUE THEN RAISE EXCEPTION 'research_budget:Walk-forward exceeds its operator trial or observation budget'; END IF;
|
|
INSERT INTO research_agent_audit(agent_id,operation,entity_id) VALUES(agent.id,'walk-forward-admitted',NEW.id::text);
|
|
RETURN NEW;
|
|
END $$;
|
|
DROP TRIGGER IF EXISTS aa_agent_walk_forward ON research_walk_forwards;
|
|
CREATE TRIGGER aa_agent_walk_forward BEFORE INSERT ON research_walk_forwards FOR EACH ROW EXECUTE FUNCTION guard_agent_walk_forward();
|
|
|
|
CREATE OR REPLACE FUNCTION guard_agent_run_budget() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
DECLARE principal TEXT; agent research_agents; experiment research_experiments; active_count BIGINT;
|
|
BEGIN
|
|
IF TG_OP='INSERT' THEN
|
|
SELECT * INTO experiment FROM research_experiments WHERE id=NEW.experiment_id;
|
|
principal:=CASE WHEN experiment.submission_principal LIKE 'agent:%' THEN experiment.submission_principal ELSE NULL END;
|
|
IF principal IS NULL THEN
|
|
IF NEW.research_agent_id IS NOT NULL OR NEW.research_limits IS NOT NULL OR NEW.research_deadline_at IS NOT NULL THEN RAISE EXCEPTION 'research_access:Only admitted research experiments may carry agent budgets'; END IF;
|
|
RETURN NEW;
|
|
END IF;
|
|
SELECT * INTO agent FROM research_agents WHERE id=principal FOR UPDATE;
|
|
PERFORM assert_research_agent_grant(agent,NEW.backtest_id,research_agent_authority(experiment));
|
|
IF NEW.research_agent_id IS NOT NULL AND NEW.research_agent_id<>principal THEN RAISE EXCEPTION 'research_access:Agent run attribution mismatch'; END IF;
|
|
IF NEW.research_limits IS NOT NULL OR NEW.research_deadline_at IS NOT NULL THEN RAISE EXCEPTION 'research_access:Agent execution budget is server-owned'; END IF;
|
|
NEW.research_agent_id:=principal; NEW.research_limits:=agent.policy->'limits';
|
|
ELSE
|
|
IF NEW.research_agent_id IS DISTINCT FROM OLD.research_agent_id OR NEW.research_limits IS DISTINCT FROM OLD.research_limits THEN RAISE EXCEPTION 'research_access:Agent run attribution and resource envelope are immutable'; END IF;
|
|
IF OLD.research_agent_id IS NULL THEN
|
|
IF NEW.research_deadline_at IS NOT NULL THEN RAISE EXCEPTION 'research_access:Unexpected agent deadline'; END IF;
|
|
RETURN NEW;
|
|
END IF;
|
|
principal:=OLD.research_agent_id;
|
|
IF NEW.research_deadline_at IS DISTINCT FROM OLD.research_deadline_at THEN RAISE EXCEPTION 'research_access:Agent deadline is server-owned'; END IF;
|
|
IF NEW.attempt_number<OLD.attempt_number THEN RAISE EXCEPTION 'research_access:Agent attempt budget cannot be reset'; END IF;
|
|
IF NEW.status='running' AND NEW.attempt_id IS DISTINCT FROM OLD.attempt_id THEN
|
|
IF OLD.status<>'pending' OR NEW.attempt_number<>OLD.attempt_number+1 OR NEW.attempt_number>(OLD.research_limits->>'maxAttempts')::integer THEN RAISE EXCEPTION 'research_budget:Research attempt budget exhausted'; END IF;
|
|
NEW.research_deadline_at:=clock_timestamp()+(OLD.research_limits->>'maxAttemptWallMs')::bigint*interval '1 millisecond';
|
|
ELSIF NEW.attempt_number IS DISTINCT FROM OLD.attempt_number THEN RAISE EXCEPTION 'research_access:Agent attempts advance only at claim'; END IF;
|
|
IF NEW.status IN ('running','paused') AND (NEW.attempt_id IS NULL OR NEW.research_deadline_at IS NULL OR NEW.lease_expires_at IS NULL) THEN RAISE EXCEPTION 'research_access:Active research work requires a complete bounded claim'; END IF;
|
|
IF NEW.status='completed' AND (NEW.research_deadline_at IS NULL OR clock_timestamp()>=NEW.research_deadline_at) THEN RAISE EXCEPTION 'research_budget:Research attempt wall time exceeded'; END IF;
|
|
END IF;
|
|
IF TG_OP='INSERT' OR (NEW.status='pending' AND OLD.status IN ('failed','completed','cancelled')) THEN
|
|
SELECT * INTO agent FROM research_agents WHERE id=principal FOR UPDATE;
|
|
IF NOT agent.enabled THEN RAISE EXCEPTION 'research_access:Research principal is disabled'; END IF;
|
|
IF TG_OP='UPDATE' THEN
|
|
SELECT * INTO experiment FROM research_experiments WHERE id=NEW.experiment_id;
|
|
PERFORM assert_research_agent_grant(agent,NEW.backtest_id,research_agent_authority(experiment));
|
|
END IF;
|
|
IF NEW.attempt_number >= (NEW.research_limits->>'maxAttempts')::integer THEN RAISE EXCEPTION 'research_budget:Research attempt budget exhausted'; END IF;
|
|
SELECT count(*) INTO active_count FROM runs WHERE research_agent_id=principal AND status IN ('pending','running','paused') AND id<>NEW.id;
|
|
IF active_count >= (agent.policy#>>'{limits,maxActiveTrials}')::bigint THEN RAISE EXCEPTION 'research_budget:Active trial capacity exhausted; wait for completion or cancellation'; END IF;
|
|
INSERT INTO research_agent_audit(agent_id,operation,entity_id) VALUES(principal,CASE WHEN TG_OP='INSERT' THEN 'trial-admitted' ELSE 'trial-retried' END,NEW.id::text);
|
|
END IF;
|
|
RETURN NEW;
|
|
END $$;
|
|
DROP TRIGGER IF EXISTS aa_agent_run_budget ON runs;
|
|
CREATE TRIGGER aa_agent_run_budget BEFORE INSERT OR UPDATE ON runs FOR EACH ROW EXECUTE FUNCTION guard_agent_run_budget();
|
|
|
|
-- Recheck at transaction completion as persistence can outlast the worker's timer.
|
|
CREATE OR REPLACE FUNCTION require_agent_result_deadline() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
DECLARE owner runs;
|
|
BEGIN
|
|
SELECT * INTO owner FROM runs WHERE id=NEW.run_id;
|
|
IF owner.research_agent_id IS NOT NULL AND (owner.research_deadline_at IS NULL OR clock_timestamp()>=owner.research_deadline_at) THEN
|
|
RAISE EXCEPTION 'research_budget:Research attempt wall time exceeded before result commit';
|
|
END IF;
|
|
RETURN NEW;
|
|
END $$;
|
|
DROP TRIGGER IF EXISTS research_result_deadline ON backtest_results;
|
|
CREATE CONSTRAINT TRIGGER research_result_deadline AFTER INSERT ON backtest_results DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION require_agent_result_deadline();
|
|
|
|
-- Additional actor ownership fence; API admissions already hold the agent as their first lock.
|
|
-- These downward mutation triggers never acquire an agent lock after a resource row lock.
|
|
CREATE OR REPLACE FUNCTION assert_research_agent_owner(principal TEXT, owner TEXT) RETURNS void LANGUAGE plpgsql AS $$ BEGIN
|
|
IF principal LIKE 'agent:%' AND (principal IS DISTINCT FROM owner OR NOT EXISTS(SELECT 1 FROM research_agents WHERE id=principal AND enabled)) THEN
|
|
RAISE EXCEPTION 'research_access:Research action requires its enabled owning principal';
|
|
END IF;
|
|
END $$;
|
|
CREATE OR REPLACE FUNCTION guard_research_action_owner() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
DECLARE owner TEXT;
|
|
BEGIN
|
|
IF TG_TABLE_NAME='experiment_trial_retries' THEN
|
|
SELECT submission_principal INTO owner FROM research_experiments WHERE id=NEW.experiment_id;
|
|
PERFORM assert_research_agent_owner(NEW.principal,owner);
|
|
ELSIF TG_TABLE_NAME='research_experiments' THEN
|
|
IF OLD.validation_selection IS NULL AND NEW.validation_selection IS NOT NULL AND NEW.submission_principal LIKE 'agent:%' AND NEW.validation_selection->>'principal' IS DISTINCT FROM NEW.submission_principal THEN RAISE EXCEPTION 'research_access:New holdouts must be selected by the owning research principal'; END IF;
|
|
IF OLD.validation_selection IS NULL AND NEW.validation_selection IS NOT NULL THEN PERFORM assert_research_agent_owner(NEW.validation_selection->>'principal',NEW.submission_principal); END IF;
|
|
IF OLD.validation_report IS NULL AND NEW.validation_report IS NOT NULL THEN PERFORM assert_research_agent_owner(NEW.validation_report->>'principal',NEW.submission_principal); END IF;
|
|
ELSIF OLD.report IS NULL AND NEW.report IS NOT NULL THEN PERFORM assert_research_agent_owner(NEW.report->>'principal',NEW.submission_principal);
|
|
END IF;
|
|
RETURN NEW;
|
|
END $$;
|
|
DROP TRIGGER IF EXISTS aa_research_action_owner ON experiment_trial_retries;
|
|
CREATE TRIGGER aa_research_action_owner BEFORE INSERT ON experiment_trial_retries FOR EACH ROW EXECUTE FUNCTION guard_research_action_owner();
|
|
DROP TRIGGER IF EXISTS aa_research_action_owner ON research_experiments;
|
|
CREATE TRIGGER aa_research_action_owner BEFORE UPDATE ON research_experiments FOR EACH ROW EXECUTE FUNCTION guard_research_action_owner();
|
|
DROP TRIGGER IF EXISTS aa_research_action_owner ON research_walk_forwards;
|
|
CREATE TRIGGER aa_research_action_owner BEFORE UPDATE ON research_walk_forwards FOR EACH ROW EXECUTE FUNCTION guard_research_action_owner();
|
|
|
|
-- Agent narratives are scoped to granted projects and owned candidates; human labels cannot be forged.
|
|
CREATE OR REPLACE FUNCTION guard_research_agent_metadata() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
DECLARE value JSONB:=to_jsonb(NEW); principal TEXT; agent research_agents; project_id TEXT; owner TEXT;
|
|
BEGIN
|
|
principal:=CASE WHEN TG_TABLE_NAME='strategy_versions' THEN value->>'created_by'
|
|
WHEN TG_TABLE_NAME IN ('research_hypothesis_revisions','analysis_artifact_revisions') THEN value->>'submitted_by'
|
|
WHEN TG_TABLE_NAME='research_project_strategies' THEN value->>'added_by'
|
|
WHEN TG_OP='INSERT' THEN value->>'owner_principal' ELSE value->>'updated_by' END;
|
|
IF principal NOT LIKE 'agent:%' THEN RETURN NEW; END IF;
|
|
SELECT * INTO agent FROM research_agents WHERE id=principal FOR UPDATE;
|
|
IF NOT FOUND OR NOT agent.enabled THEN RAISE EXCEPTION 'research_access:Research principal is disabled'; END IF;
|
|
IF TG_TABLE_NAME='research_projects' THEN RAISE EXCEPTION 'research_access:Only an operator provisions research projects'; END IF;
|
|
IF value ? 'content_origin' AND value->>'content_origin' IS DISTINCT FROM 'ai' THEN RAISE EXCEPTION 'research_access:Research principals must declare AI authorship'; END IF;
|
|
IF TG_TABLE_NAME='strategies' THEN
|
|
IF TG_OP='UPDATE' AND OLD.owner_principal<>principal THEN RAISE EXCEPTION 'research_access:Candidate family is not owned by this principal'; END IF;
|
|
ELSIF TG_TABLE_NAME='strategy_versions' THEN
|
|
SELECT owner_principal INTO owner FROM strategies WHERE id=(value->>'strategy_id')::uuid;
|
|
IF owner IS DISTINCT FROM principal OR value->>'origin'<>'candidate' THEN RAISE EXCEPTION 'research_access:Research principals may only publish owned candidate versions'; END IF;
|
|
ELSE
|
|
project_id:=value->>'project_id';
|
|
IF TG_TABLE_NAME='research_hypothesis_revisions' THEN SELECT h.project_id::text,h.owner_principal INTO project_id,owner FROM research_hypotheses h WHERE h.id=(value->>'hypothesis_id')::uuid;
|
|
ELSIF TG_TABLE_NAME='analysis_artifact_revisions' THEN SELECT a.project_id::text,a.owner_principal INTO project_id,owner FROM analysis_artifacts a WHERE a.id=(value->>'artifact_id')::uuid;
|
|
ELSIF TG_TABLE_NAME='research_project_strategies' THEN SELECT owner_principal INTO owner FROM strategies WHERE id=(value->>'strategy_id')::uuid;
|
|
ELSIF TG_OP='UPDATE' THEN owner:=to_jsonb(OLD)->>'owner_principal';
|
|
ELSE owner:=principal; END IF;
|
|
IF owner IS DISTINCT FROM principal OR NOT (agent.policy->'allowedProjectIds' ? project_id) THEN RAISE EXCEPTION 'research_access:Research project or narrative ownership is not permitted'; END IF;
|
|
END IF;
|
|
INSERT INTO research_agent_audit(agent_id,operation,entity_id) VALUES(principal,TG_TABLE_NAME||'-'||lower(TG_OP),COALESCE(value->>'id',value->>'project_id'));
|
|
RETURN NEW;
|
|
END $$;
|
|
DO $$ DECLARE name TEXT; BEGIN
|
|
FOREACH name IN ARRAY ARRAY['strategies','strategy_versions','research_projects','research_hypotheses','research_hypothesis_revisions','analysis_artifacts','analysis_artifact_revisions','research_project_strategies'] LOOP
|
|
IF to_regclass(name) IS NOT NULL THEN
|
|
EXECUTE format('DROP TRIGGER IF EXISTS aa_research_agent_metadata ON %I',name);
|
|
EXECUTE format('CREATE TRIGGER aa_research_agent_metadata BEFORE INSERT OR UPDATE ON %I FOR EACH ROW EXECUTE FUNCTION guard_research_agent_metadata()',name);
|
|
END IF;
|
|
END LOOP;
|
|
END $$;
|
|
|
|
-- Preserved 24-chronological-validation.sql body; only accepted principal identity predicate is extended.
|
|
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 is_research_actor(document->>'principal') 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 is_research_actor(document->>'principal') 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 $$;
|
|
|
|
-- Preserved 25-walk-forward.sql body; only accepted principal identity predicate is extended.
|
|
CREATE OR REPLACE FUNCTION protect_walk_forward_evidence() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
DECLARE document JSONB; member research_experiments; expected JSONB; item JSONB; segment JSONB; idx INTEGER:=0; training_index INTEGER;
|
|
BEGIN
|
|
IF NEW.id IS DISTINCT FROM OLD.id OR NEW.backtest_id IS DISTINCT FROM OLD.backtest_id OR NEW.name IS DISTINCT FROM OLD.name
|
|
OR NEW.preview IS DISTINCT FROM OLD.preview OR NEW.preview_hash IS DISTINCT FROM OLD.preview_hash OR NEW.member_ids IS DISTINCT FROM OLD.member_ids
|
|
OR NEW.submission_principal IS DISTINCT FROM OLD.submission_principal OR NEW.submission_key IS DISTINCT FROM OLD.submission_key
|
|
OR NEW.submission_hash IS DISTINCT FROM OLD.submission_hash OR NEW.created_at IS DISTINCT FROM OLD.created_at OR (OLD.cancel_requested AND NOT NEW.cancel_requested)
|
|
OR (OLD.report IS NOT NULL AND NEW.report IS DISTINCT FROM OLD.report) THEN
|
|
RAISE EXCEPTION 'Walk-forward inputs, receipt and report are immutable; cancellation is permanent' USING ERRCODE='23514';
|
|
END IF;
|
|
IF OLD.report IS NULL AND NEW.report IS NOT NULL THEN
|
|
document:=NEW.report;
|
|
IF (NOT NEW.cancel_requested AND document->>'version'='walk-forward-report/v1' AND document->>'walkForwardId'=NEW.id::text
|
|
AND document->>'previewHash'=NEW.preview_hash AND document->>'reportHash' ~ '^[a-f0-9]{64}$'
|
|
AND document->>'id' ~ '^[a-f0-9-]{36}$' AND (document->>'createdAt')::timestamptz IS NOT NULL
|
|
AND is_research_actor(document->>'principal') AND document#>>'{_receipt,key}' ~ '^[!-~]{1,200}$'
|
|
AND document#>>'{_receipt,hash}' ~ '^[a-f0-9]{64}$' AND document->>'reset'='initial-capital-empty-positions'
|
|
AND jsonb_typeof(document->'segments')='array' AND jsonb_array_length(document->'segments')=cardinality(NEW.member_ids)
|
|
AND jsonb_typeof(document->'limitations')='array') IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Walk-forward report requires all independent reset segments and a sealed receipt' USING ERRCODE='23514';
|
|
END IF;
|
|
FOR segment IN SELECT value FROM jsonb_array_elements(document->'segments') LOOP
|
|
SELECT * INTO member FROM research_experiments WHERE id=NEW.member_ids[idx+1] AND walk_forward_id=NEW.id AND walk_forward_index=idx;
|
|
IF (member.id IS NOT NULL AND NOT member.cancel_requested AND member.validation_report IS NOT NULL
|
|
AND member.validation_manifest=NEW.preview#>ARRAY['windows',idx::text,'preview']
|
|
AND member.validation_report->>'previewHash'=member.validation_manifest->>'previewHash'
|
|
AND member.validation_report->>'selectionHash'=member.validation_selection->>'selectionHash'
|
|
AND member.validation_report->'training'=member.validation_selection->'training') IS NOT TRUE THEN
|
|
RAISE EXCEPTION 'Every walk-forward member must have uncancelled sealed evidence matching its exact preparation' USING ERRCODE='23514';
|
|
END IF;
|
|
training_index:=0;
|
|
FOR item IN SELECT value FROM jsonb_array_elements(member.validation_report->'training') LOOP
|
|
PERFORM assert_validation_evidence(item,member.id,'train',training_index); training_index:=training_index+1;
|
|
END LOOP;
|
|
IF training_index<>jsonb_array_length(member.preview->'candidates') THEN RAISE EXCEPTION 'All training evidence is required' USING ERRCODE='23514'; END IF;
|
|
PERFORM assert_validation_evidence(member.validation_report->'validation',(member.validation_selection#>>'{holdoutExperimentIds,validation}')::uuid,'validation',(member.validation_selection#>>'{winner,index}')::integer);
|
|
PERFORM assert_validation_evidence(member.validation_report->'test',(member.validation_selection#>>'{holdoutExperimentIds,test}')::uuid,'test',(member.validation_selection#>>'{winner,index}')::integer);
|
|
expected:=jsonb_build_object('index',idx,'validationId',member.id::text,'previewHash',member.validation_manifest->'previewHash',
|
|
'selectionHash',member.validation_report->'selectionHash','reportId',member.validation_report->'id','reportHash',member.validation_report->'reportHash',
|
|
'validation',member.validation_report->'validation','test',member.validation_report->'test');
|
|
IF segment IS DISTINCT FROM expected THEN RAISE EXCEPTION 'Walk-forward segments must copy exact ordered sealed member reports' USING ERRCODE='23514'; END IF;
|
|
idx:=idx+1;
|
|
END LOOP;
|
|
END IF;
|
|
RETURN NEW;
|
|
END $$;
|
|
|
|
-- Preserved 26-cost-sensitivity.sql body; only accepted principal identity predicate is extended.
|
|
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 is_research_actor(NEW.submission_principal)
|
|
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 $$;
|