-- Explicit immutable human authorization; operational state remains in canonical account custody. CREATE TABLE IF NOT EXISTS paper_deployments ( id UUID PRIMARY KEY, account_id TEXT NOT NULL UNIQUE, strategy_version_id UUID NOT NULL REFERENCES strategy_versions(id), promotion_hash TEXT NOT NULL CHECK (promotion_hash ~ '^[a-f0-9]{64}$'), idempotency_key TEXT NOT NULL UNIQUE CHECK (idempotency_key ~ '^[!-~]{1,200}$'), request_hash TEXT NOT NULL CHECK (request_hash ~ '^[a-f0-9]{64}$'), document JSONB NOT NULL CHECK (jsonb_typeof(document)='object'), created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() ); -- Enumerated normalization only: costs and replay/account clocks may differ, no risk or parameter erasure. CREATE OR REPLACE FUNCTION paper_research_profile(request JSONB) RETURNS JSONB LANGUAGE sql IMMUTABLE AS $$ SELECT jsonb_build_object( 'strategy',(request->'strategy')-'reviewId', 'policy',(request->'policy') #- '{matching,risk,ledger,sessionId}' #- '{matching,risk,ledger,accountId}' #- '{matching,risk,ledger,riskSession}' #- '{matching,risk,feeRate}' #- '{matching,slippageRate}' #- '{risk_boundaries}', 'build',request->'build','analyticsPolicy',request->'analyticsPolicy','modelArtifacts',request->'modelArtifacts') $$; CREATE OR REPLACE FUNCTION require_paper_deployment() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE p JSONB:=NEW.document->'preview'; i JSONB:=p->'input'; s JSONB:=i->'outOfSample'; version strategy_versions; family strategies; review strategy_review_events; cost research_experiments; report JSONB; source_hash TEXT; cost_run runs; test_run runs; result backtest_results; item JSONB; expected JSONB; actual_run runs; trial INTEGER:=0; BEGIN IF (NEW.document=jsonb_build_object('version','paper-deployment/v1','id',NEW.id::text,'principal','operator', 'createdAt',NEW.document->'createdAt','promotionHash',NEW.promotion_hash,'preview',p) AND jsonb_typeof(NEW.document->'createdAt')='string' AND p->>'version'='paper-promotion-preview/v1' AND p->>'previewHash' ~ '^[a-f0-9]{64}$' AND p->'strategy'->>'versionId'=NEW.strategy_version_id::text AND p#>>'{configuration,matching,risk,ledger,accountId}'=NEW.account_id AND p#>>'{configuration,version}'='2' AND i->'acknowledgeTrustedCode'='true'::jsonb AND length(i->>'reason')>0 AND jsonb_typeof(p->'limitations')='array' AND jsonb_typeof(p->'host')='object' AND p->'host'->>'version'='paper-host/v1' AND p->'host'->>'hostSha256' ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN RAISE EXCEPTION 'Paper promotion requires an explicit immutable operator document' USING ERRCODE='23514'; END IF; SELECT * INTO version FROM strategy_versions WHERE id=NEW.strategy_version_id; SELECT * INTO family FROM strategies WHERE id=version.strategy_id FOR UPDATE; SELECT * INTO review FROM strategy_review_events WHERE version_id=version.id ORDER BY ordinal DESC LIMIT 1; IF (family.id IS NOT NULL AND family.archived_at IS NULL AND review.decision='approve' AND p#>>'{strategy,familyId}'=family.id::text AND p#>>'{strategy,reviewId}'=review.id::text AND p#>>'{strategy,origin}'=version.origin AND p#>>'{strategy,artifactSha256}'=version.envelope#>>'{artifact,sha256}' AND p#>>'{strategy,dependencyLockSha256}'=version.envelope#>>'{dependencyLock,sha256}') IS NOT TRUE THEN RAISE EXCEPTION 'Paper promotion requires the exact currently approved version' USING ERRCODE='23514'; END IF; SELECT * INTO cost FROM research_experiments WHERE id::text=i->>'costExperimentId'; IF (cost.id IS NOT NULL AND cost.validation_phase IS NULL AND cost.preview->>'version'='cost-sensitivity-preview/v1' AND cost.preview_hash=i->>'costPreviewHash' AND cost.preview->>'previewHash'=cost.preview_hash) IS NOT TRUE THEN RAISE EXCEPTION 'Paper promotion requires a cost-sensitivity experiment' USING ERRCODE='23514'; END IF; IF s->>'kind'='chronological-report/v1' THEN SELECT validation_report,validation_manifest#>>'{source,request,datasetHash}' INTO report,source_hash FROM research_experiments WHERE id::text=s->>'validationId' AND validation_phase='train'; IF (report#>>'{test,runId}'=i->>'testRunId') IS NOT TRUE THEN RAISE EXCEPTION 'Paper evidence must select sealed test data' USING ERRCODE='23514'; END IF; ELSIF s->>'kind'='walk-forward-report/v1' THEN SELECT w.report,w.preview#>>'{source,request,datasetHash}' INTO report,source_hash FROM research_walk_forwards w WHERE id::text=s->>'walkForwardId'; IF NOT EXISTS(SELECT 1 FROM jsonb_array_elements(report->'segments') x WHERE x#>>'{test,runId}'=i->>'testRunId') THEN RAISE EXCEPTION 'Paper evidence must select a sealed walk-forward test' USING ERRCODE='23514'; END IF; ELSE RAISE EXCEPTION 'Paper promotion requires an out-of-sample report' USING ERRCODE='23514'; END IF; IF (report->>'id'=s->>'reportId' AND report->>'reportHash'=s->>'reportHash' AND report->>'previewHash'=s->>'previewHash' AND source_hash=cost.preview#>>'{source,request,datasetHash}') IS NOT TRUE THEN RAISE EXCEPTION 'Paper source report or source dataset mismatch' USING ERRCODE='23514'; END IF; SELECT * INTO test_run FROM runs WHERE id::text=i->>'testRunId'; SELECT * INTO cost_run FROM runs WHERE id::text=i->>'costRunId' AND experiment_id=cost.id; IF (test_run.status='completed' AND cost_run.status='completed' AND test_run.request_snapshot#>>'{strategy,versionId}'=version.id::text AND test_run.request_snapshot#>'{strategy,package}'=version.envelope AND paper_research_profile(test_run.request_snapshot)=paper_research_profile(cost_run.request_snapshot)) IS NOT TRUE THEN RAISE EXCEPTION 'Paper evidence strategies and financial policies must match' USING ERRCODE='23514'; END IF; IF EXISTS(SELECT 1 FROM unnest(ARRAY['engineWrapperSha256','engineBinarySha256','dependencyLockSha256','runtime','runtimeVersion','platform','arch']) field WHERE (p->'host'->field=test_run.request_snapshot->'build'->field) IS NOT TRUE) THEN RAISE EXCEPTION 'Paper and research require the same native dependency and runtime build' USING ERRCODE='23514'; END IF; expected:=jsonb_build_object('version',2,'matching',cost_run.request_snapshot#>'{policy,matching}', 'strategies',jsonb_build_array(cost_run.request_snapshot#>'{strategy,selection}'),'policy',i#>'{transport,policy}'); expected:=jsonb_set(expected,'{matching,risk,ledger,accountId}',i#>'{transport,accountId}'); expected:=jsonb_set(expected,'{matching,risk,ledger,sessionId}',i#>'{transport,sessionId}'); expected:=jsonb_set(expected,'{matching,risk,ledger,riskSession}',i#>'{transport,riskSession}'); expected:=jsonb_set(expected,'{matching,series}',jsonb_build_array(jsonb_build_object('instrumentId',cost_run.request_snapshot#>'{strategy,selection,instrumentId}', 'seriesId',i#>'{transport,quoteSeriesId}','mode','Quote'))); IF (p->'configuration'=expected) IS NOT TRUE THEN RAISE EXCEPTION 'Paper configuration may only rebind explicit account and quote/session transport' USING ERRCODE='23514'; END IF; IF (jsonb_typeof(p#>'{evidence,costs}')='array' AND jsonb_array_length(p#>'{evidence,costs}')=jsonb_array_length(cost.preview->'candidates') AND (SELECT count(*) FROM runs WHERE experiment_id=cost.id)=jsonb_array_length(cost.preview->'candidates') AND p#>>'{evidence,test,runId}'=test_run.id::text) IS NOT TRUE THEN RAISE EXCEPTION 'Paper evidence must include every cost trial and selected test' USING ERRCODE='23514'; END IF; FOR item IN SELECT value FROM jsonb_array_elements(p#>'{evidence,costs}') LOOP SELECT * INTO actual_run FROM runs WHERE experiment_id=cost.id AND trial_index=trial; IF (actual_run.status='completed' AND actual_run.id::text=item->>'runId' AND actual_run.request_snapshot=experiment_trial_request(cost.preview,trial,actual_run.id) AND paper_research_profile(test_run.request_snapshot)=paper_research_profile(actual_run.request_snapshot)) IS NOT TRUE THEN RAISE EXCEPTION 'Paper cost evidence membership is incomplete or incompatible' USING ERRCODE='23514'; END IF; trial:=trial+1; END LOOP; FOR item IN SELECT value FROM jsonb_array_elements(jsonb_build_array(p#>'{evidence,test}')||(p#>'{evidence,costs}')) LOOP SELECT * INTO actual_run FROM runs WHERE id::text=item->>'runId'; SELECT * INTO result FROM backtest_results WHERE run_id=actual_run.id; IF (result.canonical_result->>'kind'='canonical-result/v1' AND result.canonical_result->'request'=actual_run.request_snapshot AND result.canonical_result#>'{analytics,metrics}'=item->'metrics' AND result.canonical_result#>'{analytics,fillCount}'=item->'fillCount' AND actual_run.dataset_hash=item->>'datasetHash' AND item->>'economicHash' ~ '^[a-f0-9]{64}$' AND item->>'resultHash' ~ '^[a-f0-9]{64}$') IS NOT TRUE THEN RAISE EXCEPTION 'Paper promotion requires retained canonical result evidence' USING ERRCODE='23514'; END IF; END LOOP; IF EXISTS(SELECT 1 FROM simulation_accounts WHERE id=NEW.account_id) THEN RAISE EXCEPTION 'Choose a new paper account; existing custody cannot be overwritten by promotion' USING ERRCODE='23514'; END IF; RETURN NEW; END $$; DROP TRIGGER IF EXISTS paper_deployment_admission ON paper_deployments; CREATE TRIGGER paper_deployment_admission BEFORE INSERT ON paper_deployments FOR EACH ROW EXECUTE FUNCTION require_paper_deployment(); CREATE OR REPLACE FUNCTION protect_paper_deployment() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'Paper deployments are immutable; use a new account and promotion' USING ERRCODE='23514'; END $$; DROP TRIGGER IF EXISTS paper_deployment_immutable ON paper_deployments; CREATE TRIGGER paper_deployment_immutable BEFORE UPDATE OR DELETE ON paper_deployments FOR EACH ROW EXECUTE FUNCTION protect_paper_deployment();