diff --git a/db/canonical-baseline/R__database_runtime_grants.sql b/db/canonical-baseline/R__database_runtime_grants.sql index 04554e8..dde5bad 100644 --- a/db/canonical-baseline/R__database_runtime_grants.sql +++ b/db/canonical-baseline/R__database_runtime_grants.sql @@ -374,7 +374,9 @@ GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."notifications" TO id GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."operator_accounts" TO idea2strategy_backend; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."operator_bootstrap_receipts" TO idea2strategy_backend; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."operator_case_command_receipts" TO idea2strategy_backend; +GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."operator_login_credentials" TO idea2strategy_backend; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."operator_role_assignments" TO idea2strategy_backend; +GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."operator_sessions" TO idea2strategy_backend; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."outbox_consumer_receipts" TO idea2strategy_backend; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."outbox_delivery_attempts" TO idea2strategy_backend; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."outbox_messages" TO idea2strategy_backend; @@ -389,6 +391,8 @@ GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."roles" TO idea2strat GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "performance"."bot_current_projections" TO idea2strategy_backend; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "performance"."bot_snapshots" TO idea2strategy_backend; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "performance"."series_manifests" TO idea2strategy_backend; +GRANT SELECT ON TABLE "storage"."backtest_attempt_cleanup_capabilities" TO idea2strategy_backend; +GRANT SELECT ON TABLE "storage"."backtest_object_ownerships" TO idea2strategy_backend; GRANT SELECT ON TABLE "storage"."objects" TO idea2strategy_backend; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "strategy"."compiled_flow_plans" TO idea2strategy_backend; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "strategy"."element_catalog_versions" TO idea2strategy_backend; @@ -478,8 +482,8 @@ GRANT SELECT ON TABLE "competition"."backtest_period_datasets" TO idea2strategy_ GRANT SELECT ON TABLE "competition"."backtest_period_feature_materializations" TO idea2strategy_batch; GRANT SELECT, INSERT, UPDATE ON TABLE "competition"."backtest_period_runs" TO idea2strategy_batch; GRANT SELECT, INSERT ON TABLE "competition"."leaderboard_entries" TO idea2strategy_batch; -GRANT SELECT, INSERT ON TABLE "competition"."leaderboard_snapshots" TO idea2strategy_batch; -GRANT SELECT, INSERT ON TABLE "competition"."live_evaluation_segments" TO idea2strategy_batch; +GRANT SELECT, INSERT, UPDATE ON TABLE "competition"."leaderboard_snapshots" TO idea2strategy_batch; +GRANT SELECT, INSERT, UPDATE ON TABLE "competition"."live_evaluation_segments" TO idea2strategy_batch; GRANT SELECT ON TABLE "competition"."live_room_rules" TO idea2strategy_batch; GRANT SELECT, INSERT ON TABLE "competition"."participation_events" TO idea2strategy_batch; GRANT SELECT, UPDATE ON TABLE "competition"."participations" TO idea2strategy_batch; @@ -565,7 +569,9 @@ GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."notifications" TO id GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."operator_accounts" TO idea2strategy_batch; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."operator_bootstrap_receipts" TO idea2strategy_batch; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."operator_case_command_receipts" TO idea2strategy_batch; +GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."operator_login_credentials" TO idea2strategy_batch; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."operator_role_assignments" TO idea2strategy_batch; +GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."operator_sessions" TO idea2strategy_batch; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."outbox_consumer_receipts" TO idea2strategy_batch; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."outbox_delivery_attempts" TO idea2strategy_batch; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."outbox_messages" TO idea2strategy_batch; @@ -580,6 +586,8 @@ GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."roles" TO idea2strat GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "performance"."bot_current_projections" TO idea2strategy_batch; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "performance"."bot_snapshots" TO idea2strategy_batch; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "performance"."series_manifests" TO idea2strategy_batch; +GRANT SELECT ON TABLE "storage"."backtest_attempt_cleanup_capabilities" TO idea2strategy_batch; +GRANT SELECT ON TABLE "storage"."backtest_object_ownerships" TO idea2strategy_batch; GRANT SELECT ON TABLE "storage"."objects" TO idea2strategy_batch; GRANT SELECT ON TABLE "strategy"."compiled_flow_plans" TO idea2strategy_batch; GRANT SELECT ON TABLE "strategy"."element_catalog_versions" TO idea2strategy_batch; @@ -686,7 +694,9 @@ GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."notifications" TO id GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."operator_accounts" TO idea2strategy_trading; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."operator_bootstrap_receipts" TO idea2strategy_trading; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."operator_case_command_receipts" TO idea2strategy_trading; +GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."operator_login_credentials" TO idea2strategy_trading; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."operator_role_assignments" TO idea2strategy_trading; +GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."operator_sessions" TO idea2strategy_trading; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."outbox_consumer_receipts" TO idea2strategy_trading; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."outbox_delivery_attempts" TO idea2strategy_trading; GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE "operations"."outbox_messages" TO idea2strategy_trading; @@ -757,7 +767,7 @@ GRANT SELECT, INSERT, UPDATE ON TABLE "backtest"."input_feature_materializations GRANT SELECT, INSERT, UPDATE ON TABLE "backtest"."legacy_execution_policy_mappings" TO idea2strategy_backtest; GRANT SELECT, INSERT, UPDATE ON TABLE "backtest"."monthly_judgment_summaries" TO idea2strategy_backtest; GRANT SELECT, INSERT, UPDATE ON TABLE "backtest"."performance_summaries" TO idea2strategy_backtest; -GRANT SELECT, INSERT, UPDATE ON TABLE "backtest"."run_attempts" TO idea2strategy_backtest; +GRANT SELECT ON TABLE "backtest"."run_attempts" TO idea2strategy_backtest; GRANT SELECT, INSERT, UPDATE ON TABLE "backtest"."run_input_pins" TO idea2strategy_backtest; GRANT SELECT, INSERT, UPDATE ON TABLE "backtest"."runs" TO idea2strategy_backtest; GRANT SELECT ON TABLE "bot"."bots" TO idea2strategy_backtest; @@ -780,7 +790,7 @@ GRANT SELECT ON TABLE "market_data"."stream_watermarks" TO idea2strategy_backtes GRANT SELECT ON TABLE "market_data"."trading_sessions" TO idea2strategy_backtest; GRANT SELECT, INSERT, UPDATE ON TABLE "operations"."outbox_consumer_receipts" TO idea2strategy_backtest; GRANT SELECT ON TABLE "operations"."outbox_messages" TO idea2strategy_backtest; -GRANT SELECT, INSERT, UPDATE ON TABLE "storage"."objects" TO idea2strategy_backtest; +GRANT SELECT ON TABLE "storage"."objects" TO idea2strategy_backtest; GRANT SELECT ON TABLE "strategy"."compiled_flow_plans" TO idea2strategy_backtest; GRANT SELECT ON TABLE "strategy"."element_catalog_versions" TO idea2strategy_backtest; GRANT SELECT ON TABLE "strategy"."element_definitions" TO idea2strategy_backtest; @@ -820,3 +830,59 @@ GRANT SELECT, INSERT ON TABLE "storage"."objects" TO idea2strategy_pipeline; GRANT USAGE ON SCHEMA "market_data" TO idea2strategy_pipeline; GRANT USAGE ON SCHEMA "operations" TO idea2strategy_pipeline; GRANT USAGE ON SCHEMA "storage" TO idea2strategy_pipeline; +REVOKE ALL ON FUNCTION "storage"."prepare_backtest_object_cleanup"(jsonb) FROM PUBLIC; +REVOKE ALL ON FUNCTION "storage"."prepare_backtest_object_cleanup"(jsonb) FROM idea2strategy_backend; +REVOKE ALL ON FUNCTION "storage"."prepare_backtest_object_cleanup"(jsonb) FROM idea2strategy_batch; +REVOKE ALL ON FUNCTION "storage"."prepare_backtest_object_cleanup"(jsonb) FROM idea2strategy_trading; +REVOKE ALL ON FUNCTION "storage"."prepare_backtest_object_cleanup"(jsonb) FROM idea2strategy_backtest; +REVOKE ALL ON FUNCTION "storage"."prepare_backtest_object_cleanup"(jsonb) FROM idea2strategy_pipeline; +GRANT EXECUTE ON FUNCTION "storage"."prepare_backtest_object_cleanup"(jsonb) TO idea2strategy_backtest; +REVOKE ALL ON FUNCTION "storage"."reissue_backtest_object_cleanup"(jsonb, text) FROM PUBLIC; +REVOKE ALL ON FUNCTION "storage"."reissue_backtest_object_cleanup"(jsonb, text) FROM idea2strategy_backend; +REVOKE ALL ON FUNCTION "storage"."reissue_backtest_object_cleanup"(jsonb, text) FROM idea2strategy_batch; +REVOKE ALL ON FUNCTION "storage"."reissue_backtest_object_cleanup"(jsonb, text) FROM idea2strategy_trading; +REVOKE ALL ON FUNCTION "storage"."reissue_backtest_object_cleanup"(jsonb, text) FROM idea2strategy_backtest; +REVOKE ALL ON FUNCTION "storage"."reissue_backtest_object_cleanup"(jsonb, text) FROM idea2strategy_pipeline; +GRANT EXECUTE ON FUNCTION "storage"."reissue_backtest_object_cleanup"(jsonb, text) TO idea2strategy_backtest; +REVOKE ALL ON FUNCTION "backtest"."claim_run_attempt"(uuid, text, text, bigint) FROM PUBLIC; +REVOKE ALL ON FUNCTION "backtest"."claim_run_attempt"(uuid, text, text, bigint) FROM idea2strategy_backend; +REVOKE ALL ON FUNCTION "backtest"."claim_run_attempt"(uuid, text, text, bigint) FROM idea2strategy_batch; +REVOKE ALL ON FUNCTION "backtest"."claim_run_attempt"(uuid, text, text, bigint) FROM idea2strategy_trading; +REVOKE ALL ON FUNCTION "backtest"."claim_run_attempt"(uuid, text, text, bigint) FROM idea2strategy_backtest; +REVOKE ALL ON FUNCTION "backtest"."claim_run_attempt"(uuid, text, text, bigint) FROM idea2strategy_pipeline; +GRANT EXECUTE ON FUNCTION "backtest"."claim_run_attempt"(uuid, text, text, bigint) TO idea2strategy_backtest; +REVOKE ALL ON FUNCTION "backtest"."heartbeat_run_attempt"(uuid, uuid, bigint) FROM PUBLIC; +REVOKE ALL ON FUNCTION "backtest"."heartbeat_run_attempt"(uuid, uuid, bigint) FROM idea2strategy_backend; +REVOKE ALL ON FUNCTION "backtest"."heartbeat_run_attempt"(uuid, uuid, bigint) FROM idea2strategy_batch; +REVOKE ALL ON FUNCTION "backtest"."heartbeat_run_attempt"(uuid, uuid, bigint) FROM idea2strategy_trading; +REVOKE ALL ON FUNCTION "backtest"."heartbeat_run_attempt"(uuid, uuid, bigint) FROM idea2strategy_backtest; +REVOKE ALL ON FUNCTION "backtest"."heartbeat_run_attempt"(uuid, uuid, bigint) FROM idea2strategy_pipeline; +GRANT EXECUTE ON FUNCTION "backtest"."heartbeat_run_attempt"(uuid, uuid, bigint) TO idea2strategy_backtest; +REVOKE ALL ON FUNCTION "backtest"."close_run_attempt"(uuid, uuid, text, text, text, boolean) FROM PUBLIC; +REVOKE ALL ON FUNCTION "backtest"."close_run_attempt"(uuid, uuid, text, text, text, boolean) FROM idea2strategy_backend; +REVOKE ALL ON FUNCTION "backtest"."close_run_attempt"(uuid, uuid, text, text, text, boolean) FROM idea2strategy_batch; +REVOKE ALL ON FUNCTION "backtest"."close_run_attempt"(uuid, uuid, text, text, text, boolean) FROM idea2strategy_trading; +REVOKE ALL ON FUNCTION "backtest"."close_run_attempt"(uuid, uuid, text, text, text, boolean) FROM idea2strategy_backtest; +REVOKE ALL ON FUNCTION "backtest"."close_run_attempt"(uuid, uuid, text, text, text, boolean) FROM idea2strategy_pipeline; +GRANT EXECUTE ON FUNCTION "backtest"."close_run_attempt"(uuid, uuid, text, text, text, boolean) TO idea2strategy_backtest; +REVOKE ALL ON FUNCTION "backtest"."recover_expired_run_attempt"(uuid, text, text) FROM PUBLIC; +REVOKE ALL ON FUNCTION "backtest"."recover_expired_run_attempt"(uuid, text, text) FROM idea2strategy_backend; +REVOKE ALL ON FUNCTION "backtest"."recover_expired_run_attempt"(uuid, text, text) FROM idea2strategy_batch; +REVOKE ALL ON FUNCTION "backtest"."recover_expired_run_attempt"(uuid, text, text) FROM idea2strategy_trading; +REVOKE ALL ON FUNCTION "backtest"."recover_expired_run_attempt"(uuid, text, text) FROM idea2strategy_backtest; +REVOKE ALL ON FUNCTION "backtest"."recover_expired_run_attempt"(uuid, text, text) FROM idea2strategy_pipeline; +GRANT EXECUTE ON FUNCTION "backtest"."recover_expired_run_attempt"(uuid, text, text) TO idea2strategy_backtest; +REVOKE ALL ON FUNCTION "storage"."register_backtest_object"(jsonb) FROM PUBLIC; +REVOKE ALL ON FUNCTION "storage"."register_backtest_object"(jsonb) FROM idea2strategy_backend; +REVOKE ALL ON FUNCTION "storage"."register_backtest_object"(jsonb) FROM idea2strategy_batch; +REVOKE ALL ON FUNCTION "storage"."register_backtest_object"(jsonb) FROM idea2strategy_trading; +REVOKE ALL ON FUNCTION "storage"."register_backtest_object"(jsonb) FROM idea2strategy_backtest; +REVOKE ALL ON FUNCTION "storage"."register_backtest_object"(jsonb) FROM idea2strategy_pipeline; +GRANT EXECUTE ON FUNCTION "storage"."register_backtest_object"(jsonb) TO idea2strategy_backtest; +REVOKE ALL ON FUNCTION "storage"."transition_backtest_object"(uuid, text, timestamp with time zone) FROM PUBLIC; +REVOKE ALL ON FUNCTION "storage"."transition_backtest_object"(uuid, text, timestamp with time zone) FROM idea2strategy_backend; +REVOKE ALL ON FUNCTION "storage"."transition_backtest_object"(uuid, text, timestamp with time zone) FROM idea2strategy_batch; +REVOKE ALL ON FUNCTION "storage"."transition_backtest_object"(uuid, text, timestamp with time zone) FROM idea2strategy_trading; +REVOKE ALL ON FUNCTION "storage"."transition_backtest_object"(uuid, text, timestamp with time zone) FROM idea2strategy_backtest; +REVOKE ALL ON FUNCTION "storage"."transition_backtest_object"(uuid, text, timestamp with time zone) FROM idea2strategy_pipeline; +GRANT EXECUTE ON FUNCTION "storage"."transition_backtest_object"(uuid, text, timestamp with time zone) TO idea2strategy_backtest; diff --git a/db/canonical-baseline/V1__initial_schema.sql b/db/canonical-baseline/V1__initial_schema.sql index a6c0275..bb4bd33 100644 --- a/db/canonical-baseline/V1__initial_schema.sql +++ b/db/canonical-baseline/V1__initial_schema.sql @@ -1754,11 +1754,13 @@ BEGIN IF NOT EXISTS ( SELECT 1 FROM operations.operator_accounts account + JOIN operations.operator_login_credentials credential + ON credential.operator_account_id = account.id JOIN operations.operator_role_assignments assignment ON assignment.id = NEW.operator_role_assignment_id AND assignment.operator_account_id = account.id WHERE account.id = NEW.operator_account_id - AND account.external_identity_key_version = NEW.external_identity_key_version + AND credential.credential_version = NEW.credential_version ) THEN RAISE EXCEPTION 'operator bootstrap receipt references incoherent identity evidence'; END IF; @@ -1777,6 +1779,8 @@ BEGIN IF NOT EXISTS ( SELECT 1 FROM operations.operator_accounts account + JOIN operations.operator_login_credentials credential + ON credential.operator_account_id = account.id JOIN operations.operator_role_assignments assignment ON assignment.id = NEW.operator_role_assignment_id AND assignment.operator_account_id = account.id @@ -1785,9 +1789,10 @@ BEGIN JOIN operations.audit_events audit ON audit.id = NEW.audit_event_id WHERE account.id = NEW.operator_account_id - AND account.external_identity_key_version = NEW.external_identity_key_version + AND credential.credential_version = NEW.credential_version AND account.created_at = NEW.applied_at - AND account.mfa_enrolled_at = NEW.applied_at + AND credential.created_at = NEW.applied_at + AND credential.totp_enrolled_at = NEW.applied_at AND assignment.catalog_version = NEW.catalog_version AND assignment.granted_by_operator_id = NEW.operator_account_id AND assignment.granted_at = NEW.applied_at @@ -1813,7 +1818,7 @@ BEGIN AND audit.response_document ->> 'operatorAccountId' = NEW.operator_account_id::text AND audit.response_document ->> 'operatorRoleAssignmentId' = NEW.operator_role_assignment_id::text AND audit.response_document ->> 'catalogVersion' = NEW.catalog_version - AND (audit.response_document ->> 'externalIdentityKeyVersion')::smallint = NEW.external_identity_key_version + AND (audit.response_document ->> 'credentialVersion')::bigint = NEW.credential_version AND audit.response_document ->> 'status' = 'ACTIVE' AND audit.evidence_document ->> 'deploymentActorId' = audit.actor_id::text AND audit.evidence_document ->> 'technicalGrantorOperatorId' = NEW.operator_account_id::text @@ -1838,26 +1843,6 @@ END $$; COMMENT ON FUNCTION operations.require_complete_operator_bootstrap_evidence() IS 'Binds the immutable receipt to its catalog, self-granted technical assignment, deployment actor, dedicated database role, correlation, and DB-time audit evidence.'; --- --- Name: require_versioned_operator_identity(); Type: FUNCTION; Schema: operations; Owner: - --- - -CREATE FUNCTION operations.require_versioned_operator_identity() RETURNS trigger - LANGUAGE plpgsql - AS $$ -BEGIN - IF TG_OP = 'INSERT' AND NEW.external_identity_key_version IS NULL THEN - RAISE EXCEPTION 'new operator identity mappings require a key version'; - END IF; - IF TG_OP = 'UPDATE' - AND OLD.external_identity_key_version IS NOT NULL - AND NEW.external_identity_key_version IS NULL THEN - RAISE EXCEPTION 'operator identity mappings cannot become unversioned'; - END IF; - RETURN NEW; -END $$; - - -- -- Name: verify_case_head_and_chain(); Type: FUNCTION; Schema: operations; Owner: - -- @@ -5907,14 +5892,11 @@ COMMENT ON COLUMN operations.notifications.source_event_hash IS 'Immutable sourc CREATE TABLE operations.operator_accounts ( id uuid DEFAULT gen_random_uuid() NOT NULL, - external_identity_key_hmac character varying(128) NOT NULL, status character varying(30) NOT NULL, - mfa_enrolled_at timestamp with time zone NOT NULL, - last_mfa_verified_at timestamp with time zone, created_at timestamp with time zone NOT NULL, disabled_at timestamp with time zone, - external_identity_key_version smallint, - CONSTRAINT operator_identity_key_version_positive CHECK (((external_identity_key_version IS NULL) OR (external_identity_key_version > 0))) + CONSTRAINT operator_account_status_valid CHECK (((status)::text = ANY ((ARRAY['ACTIVE'::character varying, 'DISABLED'::character varying])::text[]))), + CONSTRAINT operator_account_status_coherent CHECK (((((status)::text = 'ACTIVE'::text) AND (disabled_at IS NULL)) OR (((status)::text = 'DISABLED'::text) AND (disabled_at IS NOT NULL)))) ); @@ -5926,10 +5908,72 @@ COMMENT ON TABLE operations.operator_accounts IS '운영자 계정 저장. Recor -- --- Name: COLUMN operator_accounts.external_identity_key_version; Type: COMMENT; Schema: operations; Owner: - +-- Name: operator_login_credentials; Type: TABLE; Schema: operations; Owner: - -- -COMMENT ON COLUMN operations.operator_accounts.external_identity_key_version IS 'Version of the deployment HMAC key used for the length-delimited issuer/subject mapping. NULL legacy mappings fail closed until verified backfill.'; +CREATE TABLE operations.operator_login_credentials ( + operator_account_id uuid PRIMARY KEY, + login_name character varying(120) NOT NULL UNIQUE, + password_hash character varying(512) NOT NULL, + password_algorithm character varying(30) DEFAULT 'ARGON2ID'::character varying NOT NULL, + password_parameters jsonb NOT NULL, + password_version smallint NOT NULL, + credential_version bigint DEFAULT 1 NOT NULL, + totp_ciphertext bytea NOT NULL, + totp_nonce bytea NOT NULL, + totp_key_version smallint NOT NULL, + totp_enrolled_at timestamp with time zone NOT NULL, + last_accepted_totp_step bigint, + failed_attempt_count integer DEFAULT 0 NOT NULL, + locked_until timestamp with time zone, + password_changed_at timestamp with time zone NOT NULL, + compromised_at timestamp with time zone, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT operator_credential_versions_positive CHECK (((password_version > 0) AND (credential_version > 0) AND (totp_key_version > 0))), + CONSTRAINT operator_failed_attempt_count_nonnegative CHECK ((failed_attempt_count >= 0)), + CONSTRAINT operator_login_name_normalized CHECK ((((login_name)::text = lower((login_name)::text)) AND ((login_name)::text ~ '^[a-z0-9][a-z0-9._-]{2,119}$'::text))), + CONSTRAINT operator_password_algorithm_valid CHECK (((password_algorithm)::text = 'ARGON2ID'::text)), + CONSTRAINT operator_totp_nonce_valid CHECK ((octet_length(totp_nonce) = 12)) +); + +COMMENT ON TABLE operations.operator_login_credentials IS 'Dedicated operator password and encrypted TOTP credential. Raw passwords and TOTP seeds are never stored.'; + + +-- +-- Name: operator_sessions; Type: TABLE; Schema: operations; Owner: - +-- + +CREATE TABLE operations.operator_sessions ( + id uuid DEFAULT gen_random_uuid() PRIMARY KEY, + operator_account_id uuid NOT NULL, + credential_version bigint NOT NULL, + session_token_hmac character varying(64) NOT NULL UNIQUE, + session_hmac_key_version smallint NOT NULL, + csrf_token_hmac character varying(64) NOT NULL, + csrf_hmac_key_version smallint NOT NULL, + csrf_generation bigint DEFAULT 1 NOT NULL, + source_key_hmac character varying(64) NOT NULL, + source_hmac_key_version smallint NOT NULL, + created_at timestamp with time zone NOT NULL, + last_used_at timestamp with time zone NOT NULL, + idle_expires_at timestamp with time zone NOT NULL, + absolute_expires_at timestamp with time zone NOT NULL, + mfa_verified_at timestamp with time zone NOT NULL, + revoked_at timestamp with time zone, + revocation_reason_code character varying(80), + CONSTRAINT operator_session_expiry_coherent CHECK (((created_at <= last_used_at) AND (last_used_at < idle_expires_at) AND (idle_expires_at <= absolute_expires_at))), + CONSTRAINT operator_session_hmacs_valid CHECK ((((session_token_hmac)::text ~ '^[0-9a-f]{64}$'::text) AND ((csrf_token_hmac)::text ~ '^[0-9a-f]{64}$'::text) AND ((source_key_hmac)::text ~ '^[0-9a-f]{64}$'::text))), + CONSTRAINT operator_session_revocation_coherent CHECK ((((revoked_at IS NULL) AND (revocation_reason_code IS NULL)) OR ((revoked_at IS NOT NULL) AND (revocation_reason_code IS NOT NULL)))), + CONSTRAINT operator_session_versions_positive CHECK (((credential_version > 0) AND (session_hmac_key_version > 0) AND (csrf_hmac_key_version > 0) AND (source_hmac_key_version > 0) AND (csrf_generation > 0))) +); + +COMMENT ON TABLE operations.operator_sessions IS 'Opaque server-side operator session. Only versioned HMAC digests are stored.'; + +CREATE INDEX operator_login_credentials_locked_until_idx ON operations.operator_login_credentials USING btree (locked_until); +CREATE INDEX operator_sessions_operator_created_idx ON operations.operator_sessions USING btree (operator_account_id, created_at); +CREATE INDEX operator_sessions_idle_expiry_idx ON operations.operator_sessions USING btree (idle_expires_at); +CREATE INDEX operator_sessions_absolute_expiry_idx ON operations.operator_sessions USING btree (absolute_expires_at); -- @@ -5942,11 +5986,11 @@ CREATE TABLE operations.operator_bootstrap_receipts ( catalog_version character varying(80) NOT NULL, operator_account_id uuid NOT NULL, operator_role_assignment_id uuid NOT NULL, - external_identity_key_version smallint NOT NULL, + credential_version bigint NOT NULL, correlation_id uuid NOT NULL, audit_event_id uuid NOT NULL, applied_at timestamp with time zone NOT NULL, - CONSTRAINT operator_bootstrap_key_version_positive CHECK ((external_identity_key_version > 0)) + CONSTRAINT operator_bootstrap_credential_version_positive CHECK ((credential_version > 0)) ); @@ -8846,7 +8890,7 @@ COPY operations.notifications (id, account_id, bot_id, notification_type, mandat -- Data for Name: operator_accounts; Type: TABLE DATA; Schema: operations; Owner: - -- -COPY operations.operator_accounts (id, external_identity_key_hmac, status, mfa_enrolled_at, last_mfa_verified_at, created_at, disabled_at, external_identity_key_version) FROM stdin; +COPY operations.operator_accounts (id, status, created_at, disabled_at) FROM stdin; \. @@ -8854,7 +8898,7 @@ COPY operations.operator_accounts (id, external_identity_key_hmac, status, mfa_e -- Data for Name: operator_bootstrap_receipts; Type: TABLE DATA; Schema: operations; Owner: - -- -COPY operations.operator_bootstrap_receipts (bootstrap_key, manifest_hash, catalog_version, operator_account_id, operator_role_assignment_id, external_identity_key_version, correlation_id, audit_event_id, applied_at) FROM stdin; +COPY operations.operator_bootstrap_receipts (bootstrap_key, manifest_hash, catalog_version, operator_account_id, operator_role_assignment_id, credential_version, correlation_id, audit_event_id, applied_at) FROM stdin; \. @@ -10789,14 +10833,6 @@ ALTER TABLE ONLY operations.notifications ADD CONSTRAINT notifications_pkey PRIMARY KEY (id); --- --- Name: operator_accounts operator_accounts_external_identity_key_hmac_key; Type: CONSTRAINT; Schema: operations; Owner: - --- - -ALTER TABLE ONLY operations.operator_accounts - ADD CONSTRAINT operator_accounts_external_identity_key_hmac_key UNIQUE (external_identity_key_hmac); - - -- -- Name: operator_accounts operator_accounts_pkey; Type: CONSTRAINT; Schema: operations; Owner: - -- @@ -14028,13 +14064,6 @@ CREATE TRIGGER require_coherent_operator_bootstrap_receipt_before_insert BEFORE CREATE TRIGGER require_complete_operator_bootstrap_evidence_before_insert BEFORE INSERT ON operations.operator_bootstrap_receipts FOR EACH ROW EXECUTE FUNCTION operations.require_complete_operator_bootstrap_evidence(); --- --- Name: operator_accounts require_versioned_operator_identity_before_write; Type: TRIGGER; Schema: operations; Owner: - --- - -CREATE TRIGGER require_versioned_operator_identity_before_write BEFORE INSERT OR UPDATE ON operations.operator_accounts FOR EACH ROW EXECUTE FUNCTION operations.require_versioned_operator_identity(); - - -- -- Name: case_events verify_case_event_chain; Type: TRIGGER; Schema: operations; Owner: - -- @@ -15861,6 +15890,22 @@ ALTER TABLE ONLY operations.operator_bootstrap_receipts ADD CONSTRAINT operator_bootstrap_account_fk FOREIGN KEY (operator_account_id) REFERENCES operations.operator_accounts(id); +-- +-- Name: operator_login_credentials operator_login_credentials_account_fk; Type: FK CONSTRAINT; Schema: operations; Owner: - +-- + +ALTER TABLE ONLY operations.operator_login_credentials + ADD CONSTRAINT operator_login_credentials_account_fk FOREIGN KEY (operator_account_id) REFERENCES operations.operator_accounts(id); + + +-- +-- Name: operator_sessions operator_sessions_account_fk; Type: FK CONSTRAINT; Schema: operations; Owner: - +-- + +ALTER TABLE ONLY operations.operator_sessions + ADD CONSTRAINT operator_sessions_account_fk FOREIGN KEY (operator_account_id) REFERENCES operations.operator_accounts(id); + + -- -- Name: operator_bootstrap_receipts operator_bootstrap_assignment_fk; Type: FK CONSTRAINT; Schema: operations; Owner: - -- diff --git a/db/canonical-baseline/V20260825000000__backend_basic_strategy_execution_completion.sql b/db/canonical-baseline/V20260825000000__backend_basic_strategy_execution_completion.sql new file mode 100644 index 0000000..b8a007f --- /dev/null +++ b/db/canonical-baseline/V20260825000000__backend_basic_strategy_execution_completion.sql @@ -0,0 +1,95 @@ +-- Publish the complete Basic execution catalog without mutating the consolidated V1 definitions. +-- Existing releases stay pinned to the retired basic-elements:2026-08-08 catalog; new drafts select +-- the single active catalog published below. + +UPDATE strategy.element_catalog_versions +SET retired_at = '2026-08-25 00:00:00+00' +WHERE catalog_version = 'basic-elements:2026-08-08' + AND retired_at IS NULL; + +INSERT INTO strategy.element_catalog_versions ( + id, language_version, schema_version, catalog_version, data_requirement_version, + definition_hash, published_at, retired_at +) VALUES ( + '0f5a0000-0000-4000-8000-000000000001', + 'basic/v1', + 'basic-semantic/v1', + 'basic-elements:2026-08-25', + 'alpaca-sip/v1', + 'sha256:' || encode(public.digest('basic-elements:2026-08-25', 'sha256'), 'hex'), + '2026-08-25 00:00:00+00', + NULL +); + +WITH copied AS ( + SELECT + element_code, + element_kind, + CASE element_code + WHEN 'BASIC_RSI_CROSS' THEN jsonb_set(parameter_schema, '{properties,threshold}', + '{"type":"string","minLength":1,"x-numericMinimum":"0","x-numericMaximum":"100"}'::jsonb) + WHEN 'BASIC_HOLDING_PERIOD' THEN jsonb_set(parameter_schema, '{properties,amount}', + '{"type":"string","minLength":1,"x-integer":true,"x-numericMinimum":"0"}'::jsonb) + WHEN 'BASIC_POSITION_RETURN' THEN jsonb_set(parameter_schema, '{properties,thresholdPercent}', + '{"type":"string","minLength":1,"x-numericMinimum":"0","x-numericMaximum":"100"}'::jsonb) + WHEN 'BASIC_PEAK_RETURN' THEN jsonb_set(parameter_schema, '{properties,thresholdPercent}', + '{"type":"string","minLength":1,"x-numericMinimum":"0","x-numericMaximum":"100"}'::jsonb) + WHEN 'BASIC_DRAWDOWN_FROM_PEAK' THEN jsonb_set(parameter_schema, '{properties,thresholdPercent}', + '{"type":"string","minLength":1,"x-numericMinimum":"0","x-numericMaximum":"100"}'::jsonb) + WHEN 'BASIC_SCHEDULE' THEN jsonb_set(parameter_schema, '{properties,interval}', + '{"type":"string","minLength":1,"x-integer":true,"x-numericExclusiveMinimum":"0"}'::jsonb) + WHEN 'BASIC_EQUAL_ALLOCATION_ORDER' THEN + jsonb_set( + jsonb_set( + jsonb_set( + jsonb_set( + jsonb_set(parameter_schema, '{required}', + (parameter_schema -> 'required') || '"maxPositionPercent"'::jsonb), + '{properties,orderPercent}', + '{"type":"string","minLength":1,"x-numericExclusiveMinimum":"0","x-numericMaximum":"100"}'::jsonb), + '{properties,maxPositionPercent}', + '{"type":"string","minLength":1,"x-numericExclusiveMinimum":"0","x-numericMaximum":"100"}'::jsonb, + true), + '{properties,waitInterval}', + '{"type":"string","minLength":1,"x-integer":true,"x-numericExclusiveMinimum":"0"}'::jsonb), + '{properties,maxExecutions}', + '{"type":"string","minLength":1,"x-integer":true,"x-numericExclusiveMinimum":"0"}'::jsonb) + ELSE parameter_schema + END AS parameter_schema, + input_port_schema, + output_port_schema, + CASE WHEN element_code = 'BASIC_EQUAL_ALLOCATION_ORDER' THEN + jsonb_set(execution_contract, '{runtime,arguments,maxPositionPercent}', + '"$maxPositionPercent"'::jsonb, true) + ELSE execution_contract END AS execution_contract + FROM strategy.element_definitions + WHERE element_catalog_version_id = '0f4a0000-0000-4000-8000-000000000001' +), versioned AS ( + SELECT + md5('basic-elements:2026-08-25:' || element_code)::uuid AS id, + element_code, + element_kind, + parameter_schema, + input_port_schema, + output_port_schema, + execution_contract, + 'sha256:' || encode(public.digest( + element_code || ':' || parameter_schema::text || ':' || execution_contract::text, + 'sha256'), 'hex') AS definition_hash + FROM copied +) +INSERT INTO strategy.element_definitions ( + id, element_catalog_version_id, element_code, element_kind, parameter_schema, + input_port_schema, output_port_schema, execution_contract, definition_hash +) +SELECT + id, + '0f5a0000-0000-4000-8000-000000000001', + element_code, + element_kind, + parameter_schema, + input_port_schema, + output_port_schema, + execution_contract, + definition_hash +FROM versioned; diff --git a/db/canonical-baseline/V20260825000001__pipeline_basic_strategy_feature_catalog.sql b/db/canonical-baseline/V20260825000001__pipeline_basic_strategy_feature_catalog.sql new file mode 100644 index 0000000..9760861 --- /dev/null +++ b/db/canonical-baseline/V20260825000001__pipeline_basic_strategy_feature_catalog.sql @@ -0,0 +1,21 @@ +-- Copy the immutable feature definitions for the new Basic catalog under pipeline ownership. +INSERT INTO market_data.feature_definitions ( + id, element_catalog_version_id, feature_code, calculator_version, resolution, + normalized_parameters, output_value_type, required_history_points, definition_hash, created_at +) +SELECT + md5('basic-elements:2026-08-25:feature:' || feature_code || ':' || resolution)::uuid, + '0f5a0000-0000-4000-8000-000000000001', + feature_code, + calculator_version, + resolution, + normalized_parameters, + output_value_type, + required_history_points, + 'sha256:' || encode(public.digest( + 'basic-elements:2026-08-25:feature:' || feature_code || ':' || resolution || ':' + || normalized_parameters::text, + 'sha256'), 'hex'), + '2026-08-25 00:00:01+00' +FROM market_data.feature_definitions +WHERE element_catalog_version_id = '0f4a0000-0000-4000-8000-000000000001'; diff --git a/db/canonical-baseline/V20260826010000__backend_bind_room_invitations_to_accounts.sql b/db/canonical-baseline/V20260826010000__backend_bind_room_invitations_to_accounts.sql new file mode 100644 index 0000000..e74a1fd --- /dev/null +++ b/db/canonical-baseline/V20260826010000__backend_bind_room_invitations_to_accounts.sql @@ -0,0 +1,27 @@ +alter table competition.room_invitations + add column claimed_by_account_id uuid, + add column claimed_at timestamptz, + add column admitted_participation_id uuid; + +alter table competition.room_invitations + add constraint room_invitations_claim_pair_ck + check ((claimed_by_account_id is null) = (claimed_at is null)), + add constraint room_invitations_admission_requires_claim_ck + check (admitted_participation_id is null or claimed_by_account_id is not null), + add constraint room_invitations_claimed_by_account_id_fkey + foreign key (claimed_by_account_id) references identity.accounts(id) deferrable, + add constraint room_invitations_admitted_participation_id_fkey + foreign key (admitted_participation_id) references competition.participations(id) deferrable; + +create unique index room_invitations_admitted_participation_id_uq + on competition.room_invitations(admitted_participation_id) + where admitted_participation_id is not null; + +create index room_invitations_account_admission_idx + on competition.room_invitations(room_id, claimed_by_account_id, admitted_participation_id, expires_at) + where claimed_by_account_id is not null; + +comment on column competition.room_invitations.claimed_by_account_id is + 'Account that authenticated while consuming the one-time secret. A room UUID alone never grants admission.'; +comment on column competition.room_invitations.admitted_participation_id is + 'Participation that atomically spent this account-bound admission grant.'; diff --git a/db/canonical-baseline/V20260827090000__backtest_add_owner_soft_delete.sql b/db/canonical-baseline/V20260827090000__backtest_add_owner_soft_delete.sql new file mode 100644 index 0000000..eef1993 --- /dev/null +++ b/db/canonical-baseline/V20260827090000__backtest_add_owner_soft_delete.sql @@ -0,0 +1,24 @@ +ALTER TABLE backtest.runs + ADD COLUMN deletion_requested_at timestamptz, + ADD COLUMN deleted_at timestamptz; + +ALTER TABLE backtest.runs + ADD CONSTRAINT backtest_deletion_state_consistent + CHECK ( + deleted_at IS NULL + OR (deletion_requested_at IS NOT NULL AND deleted_at >= deletion_requested_at) + ), + ADD CONSTRAINT backtest_deleted_run_is_terminal + CHECK ( + deleted_at IS NULL + OR status IN ('COMPLETED', 'FAILED', 'UNAVAILABLE', 'CANCELLED') + ); + +CREATE INDEX runs_owner_account_id_deleted_at_queued_at_idx + ON backtest.runs (owner_account_id, deleted_at, queued_at DESC); + +COMMENT ON COLUMN backtest.runs.deletion_requested_at IS + 'Owner-requested removal time. Running work remains durable until cooperative cancellation reaches a terminal state.'; + +COMMENT ON COLUMN backtest.runs.deleted_at IS + 'Soft-delete completion time. Deleted runs are hidden from owner APIs but retained as immutable execution evidence.'; diff --git a/db/canonical-baseline/V20260902000000__pipeline_backtest_object_cleanup_capability.sql b/db/canonical-baseline/V20260902000000__pipeline_backtest_object_cleanup_capability.sql new file mode 100644 index 0000000..4a21b02 --- /dev/null +++ b/db/canonical-baseline/V20260902000000__pipeline_backtest_object_cleanup_capability.sql @@ -0,0 +1,404 @@ +-- The backtest worker must compensate only its own uncommitted object versions. +-- It deliberately has no DELETE on storage.objects and no SELECT on every table +-- that may acquire a future FK to storage.objects. This transaction-scoped +-- capability performs that narrow operation with migration-owner privileges. + +CREATE OR REPLACE FUNCTION storage.prepare_backtest_object_cleanup(p_candidates jsonb) +RETURNS SETOF storage.objects +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = pg_catalog, pg_temp +SET lock_timeout = '5s' +AS $cleanup$ +DECLARE + v_after jsonb; + v_before jsonb; + v_candidate_count integer; + v_candidate_ids uuid[]; + v_deleted_count integer; + v_existing_count integer; + v_reference_exists boolean; + v_source record; + v_unique_count integer; +BEGIN + IF jsonb_typeof(p_candidates) IS DISTINCT FROM 'array' + OR jsonb_array_length(p_candidates) = 0 THEN + RAISE EXCEPTION 'backtest object cleanup candidates must be a non-empty JSON array'; + END IF; + + IF EXISTS ( + SELECT 1 + FROM jsonb_array_elements(p_candidates) AS offered(candidate) + WHERE jsonb_typeof(offered.candidate) IS DISTINCT FROM 'object' + OR ( + SELECT array_agg(key ORDER BY key) + FROM jsonb_object_keys(offered.candidate) AS keys(key) + ) IS DISTINCT FROM ARRAY[ + 'bucket_name', + 'content_hash', + 'object_id', + 'object_key', + 'provider_version_id', + 'storage_provider' + ]::text[] + ) THEN + RAISE EXCEPTION 'backtest object cleanup candidate shape is invalid'; + END IF; + + SELECT count(*), count(DISTINCT candidate.object_id), + array_agg(candidate.object_id ORDER BY candidate.object_id) + INTO v_candidate_count, v_unique_count, v_candidate_ids + FROM jsonb_to_recordset(p_candidates) AS candidate( + object_id uuid, + storage_provider text, + bucket_name text, + object_key text, + provider_version_id text, + content_hash text + ); + + IF v_candidate_count IS DISTINCT FROM v_unique_count THEN + RAISE EXCEPTION 'backtest object cleanup candidate ids must be unique'; + END IF; + + IF EXISTS ( + SELECT 1 + FROM jsonb_to_recordset(p_candidates) AS candidate( + object_id uuid, + storage_provider text, + bucket_name text, + object_key text, + provider_version_id text, + content_hash text + ) + WHERE candidate.object_id IS NULL + OR nullif(candidate.storage_provider, '') IS NULL + OR nullif(candidate.bucket_name, '') IS NULL + OR nullif(candidate.object_key, '') IS NULL + OR nullif(candidate.provider_version_id, '') IS NULL + OR candidate.content_hash !~ '^[0-9a-f]{64}$' + OR NOT ( + ( + candidate.object_key ~ + '^backtest-results/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/[0-9a-f]{64}[.]json$' + AND candidate.object_key LIKE '%/' || candidate.content_hash || '.json' + ) + OR + ( + candidate.object_key ~ + '^backtest-results/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/[A-Z][A-Z0-9_]{0,49}/week_start=[0-9]{4}-[0-9]{2}-[0-9]{2}/part=[0-9]{4}/[0-9a-f]{64}[.]parquet$' + AND candidate.object_key LIKE '%/' || candidate.content_hash || '.parquet' + ) + ) + ) THEN + RAISE EXCEPTION + 'backtest object cleanup requires exact identities in the canonical backtest object namespace'; + END IF; + + WITH foreign_keys AS ( + SELECT fk.oid AS constraint_oid, + fk.conname AS constraint_name, + source.oid AS source_oid, + source_namespace.nspname AS source_schema, + source.relname AS source_table, + source.relkind AS source_relkind, + source.relispartition AS source_is_partition, + EXISTS ( + SELECT 1 + FROM pg_inherits AS inheritance + WHERE inheritance.inhrelid = source.oid + OR inheritance.inhparent = source.oid + ) AS source_has_inheritance, + ARRAY( + SELECT source_column.attname + FROM unnest(fk.conkey) WITH ORDINALITY AS source_key(attnum, ordinality) + JOIN pg_attribute AS source_column + ON source_column.attrelid = source.oid + AND source_column.attnum = source_key.attnum + ORDER BY source_key.ordinality + ) AS source_columns, + target.oid AS target_oid, + target.relkind AS target_relkind, + target.relispartition AS target_is_partition, + EXISTS ( + SELECT 1 + FROM pg_inherits AS inheritance + WHERE inheritance.inhrelid = target.oid + OR inheritance.inhparent = target.oid + ) AS target_has_inheritance, + ARRAY( + SELECT target_column.attname + FROM unnest(fk.confkey) WITH ORDINALITY AS target_key(attnum, ordinality) + JOIN pg_attribute AS target_column + ON target_column.attrelid = target.oid + AND target_column.attnum = target_key.attnum + ORDER BY target_key.ordinality + ) AS target_columns, + fk.convalidated AS validated, + fk.condeferrable AS deferrable, + fk.confdeltype AS delete_action + FROM pg_constraint AS fk + JOIN pg_class AS source ON source.oid = fk.conrelid + JOIN pg_namespace AS source_namespace + ON source_namespace.oid = source.relnamespace + JOIN pg_class AS target ON target.oid = fk.confrelid + WHERE fk.contype = 'f' + AND fk.confrelid = 'storage.objects'::regclass + ) + SELECT coalesce( + jsonb_agg(to_jsonb(foreign_key) ORDER BY + foreign_key.source_schema, + foreign_key.source_table, + foreign_key.constraint_name, + foreign_key.constraint_oid), + '[]'::jsonb + ) + INTO v_before + FROM foreign_keys AS foreign_key; + + FOR v_source IN + SELECT reference + FROM jsonb_array_elements(v_before) AS reference_rows(reference) + LOOP + IF jsonb_array_length(v_source.reference->'source_columns') <> 1 + OR v_source.reference->'target_columns' <> '["id"]'::jsonb + OR v_source.reference->>'source_relkind' <> 'r' + OR (v_source.reference->>'source_is_partition')::boolean + OR (v_source.reference->>'source_has_inheritance')::boolean + OR v_source.reference->>'target_relkind' <> 'r' + OR (v_source.reference->>'target_is_partition')::boolean + OR (v_source.reference->>'target_has_inheritance')::boolean + OR v_source.reference->>'delete_action' <> 'a' THEN + RAISE EXCEPTION + 'unsupported storage.objects foreign-key shape at %.% (constraint %); cleanup fails closed', + v_source.reference->>'source_schema', + v_source.reference->>'source_table', + v_source.reference->>'constraint_name'; + END IF; + END LOOP; + + -- Source relations come first. An ALTER TABLE that already owns a source + -- lock may then acquire the target and finish; cleanup never holds the target + -- while waiting for that source, so the inverse ordering cannot deadlock. + FOR v_source IN + SELECT DISTINCT reference->>'source_schema' AS source_schema, + reference->>'source_table' AS source_table, + (reference->>'source_oid')::oid AS source_oid + FROM jsonb_array_elements(v_before) AS reference_rows(reference) + ORDER BY source_schema, source_table, source_oid + LOOP + BEGIN + EXECUTE format( + 'LOCK TABLE %I.%I IN ACCESS SHARE MODE', + v_source.source_schema, + v_source.source_table + ); + EXCEPTION + WHEN undefined_table THEN + RAISE EXCEPTION + 'storage.objects foreign-key catalog changed while cleanup acquired source locks'; + END; + END LOOP; + + LOCK TABLE storage.objects IN SHARE UPDATE EXCLUSIVE MODE; + + WITH foreign_keys AS ( + SELECT fk.oid AS constraint_oid, + fk.conname AS constraint_name, + source.oid AS source_oid, + source_namespace.nspname AS source_schema, + source.relname AS source_table, + source.relkind AS source_relkind, + source.relispartition AS source_is_partition, + EXISTS ( + SELECT 1 + FROM pg_inherits AS inheritance + WHERE inheritance.inhrelid = source.oid + OR inheritance.inhparent = source.oid + ) AS source_has_inheritance, + ARRAY( + SELECT source_column.attname + FROM unnest(fk.conkey) WITH ORDINALITY AS source_key(attnum, ordinality) + JOIN pg_attribute AS source_column + ON source_column.attrelid = source.oid + AND source_column.attnum = source_key.attnum + ORDER BY source_key.ordinality + ) AS source_columns, + target.oid AS target_oid, + target.relkind AS target_relkind, + target.relispartition AS target_is_partition, + EXISTS ( + SELECT 1 + FROM pg_inherits AS inheritance + WHERE inheritance.inhrelid = target.oid + OR inheritance.inhparent = target.oid + ) AS target_has_inheritance, + ARRAY( + SELECT target_column.attname + FROM unnest(fk.confkey) WITH ORDINALITY AS target_key(attnum, ordinality) + JOIN pg_attribute AS target_column + ON target_column.attrelid = target.oid + AND target_column.attnum = target_key.attnum + ORDER BY target_key.ordinality + ) AS target_columns, + fk.convalidated AS validated, + fk.condeferrable AS deferrable, + fk.confdeltype AS delete_action + FROM pg_constraint AS fk + JOIN pg_class AS source ON source.oid = fk.conrelid + JOIN pg_namespace AS source_namespace + ON source_namespace.oid = source.relnamespace + JOIN pg_class AS target ON target.oid = fk.confrelid + WHERE fk.contype = 'f' + AND fk.confrelid = 'storage.objects'::regclass + ) + SELECT coalesce( + jsonb_agg(to_jsonb(foreign_key) ORDER BY + foreign_key.source_schema, + foreign_key.source_table, + foreign_key.constraint_name, + foreign_key.constraint_oid), + '[]'::jsonb + ) + INTO v_after + FROM foreign_keys AS foreign_key; + + IF v_before IS DISTINCT FROM v_after THEN + RAISE EXCEPTION + 'storage.objects foreign-key catalog changed while cleanup acquired locks'; + END IF; + + FOR v_source IN + SELECT reference + FROM jsonb_array_elements(v_after) AS reference_rows(reference) + LOOP + IF jsonb_array_length(v_source.reference->'source_columns') <> 1 + OR v_source.reference->'target_columns' <> '["id"]'::jsonb + OR v_source.reference->>'source_relkind' <> 'r' + OR (v_source.reference->>'source_is_partition')::boolean + OR (v_source.reference->>'source_has_inheritance')::boolean + OR v_source.reference->>'target_relkind' <> 'r' + OR (v_source.reference->>'target_is_partition')::boolean + OR (v_source.reference->>'target_has_inheritance')::boolean + OR v_source.reference->>'delete_action' <> 'a' THEN + RAISE EXCEPTION + 'unsupported storage.objects foreign-key shape at %.% (constraint %); cleanup fails closed', + v_source.reference->>'source_schema', + v_source.reference->>'source_table', + v_source.reference->>'constraint_name'; + END IF; + END LOOP; + + -- The row locks serialize every immediate FK KEY SHARE check. They are + -- acquired before the reference scan so a writer that commits while cleanup + -- waits is visible to the following READ COMMITTED statements. + PERFORM object_row.id + FROM storage.objects AS object_row + JOIN jsonb_to_recordset(p_candidates) AS candidate( + object_id uuid, + storage_provider text, + bucket_name text, + object_key text, + provider_version_id text, + content_hash text + ) ON candidate.object_id = object_row.id + ORDER BY object_row.id + FOR UPDATE OF object_row; + + SELECT count(*) + INTO v_existing_count + FROM storage.objects AS object_row + JOIN jsonb_to_recordset(p_candidates) AS candidate( + object_id uuid, + storage_provider text, + bucket_name text, + object_key text, + provider_version_id text, + content_hash text + ) ON candidate.object_id = object_row.id; + + IF EXISTS ( + SELECT 1 + FROM storage.objects AS object_row + JOIN jsonb_to_recordset(p_candidates) AS candidate( + object_id uuid, + storage_provider text, + bucket_name text, + object_key text, + provider_version_id text, + content_hash text + ) ON candidate.object_id = object_row.id + WHERE object_row.storage_provider IS DISTINCT FROM candidate.storage_provider + OR object_row.bucket_name IS DISTINCT FROM candidate.bucket_name + OR object_row.object_key IS DISTINCT FROM candidate.object_key + OR object_row.provider_version_id IS DISTINCT FROM candidate.provider_version_id + OR object_row.content_hash IS DISTINCT FROM candidate.content_hash + ) THEN + RAISE EXCEPTION + 'refusing to clean a storage object whose provider, bucket, key, provider version, or hash changed'; + END IF; + + FOR v_source IN + SELECT reference->>'source_schema' AS source_schema, + reference->>'source_table' AS source_table, + reference->>'constraint_name' AS constraint_name, + reference->'source_columns'->>0 AS source_column + FROM jsonb_array_elements(v_after) AS reference_rows(reference) + ORDER BY source_schema, source_table, constraint_name + LOOP + EXECUTE format( + 'SELECT EXISTS (' + 'SELECT 1 FROM %I.%I AS source_row ' + 'WHERE source_row.%I = ANY ($1))', + v_source.source_schema, + v_source.source_table, + v_source.source_column + ) + INTO v_reference_exists + USING v_candidate_ids; + + IF v_reference_exists THEN + RAISE EXCEPTION + 'storage object cleanup is referenced by %.%.% (constraint %)', + v_source.source_schema, + v_source.source_table, + v_source.source_column, + v_source.constraint_name; + END IF; + END LOOP; + + -- DELETE is deliberately before the external-object boundary. The caller's + -- transaction remains open while bytes are removed: an external failure rolls + -- this deletion back, while a trigger/FK rejection arrives before any bytes go. + RETURN QUERY + DELETE FROM storage.objects AS object_row + USING jsonb_to_recordset(p_candidates) AS candidate( + object_id uuid, + storage_provider text, + bucket_name text, + object_key text, + provider_version_id text, + content_hash text + ) + WHERE object_row.id = candidate.object_id + AND object_row.storage_provider = candidate.storage_provider + AND object_row.bucket_name = candidate.bucket_name + AND object_row.object_key = candidate.object_key + AND object_row.provider_version_id = candidate.provider_version_id + AND object_row.content_hash = candidate.content_hash + RETURNING object_row.*; + + GET DIAGNOSTICS v_deleted_count = ROW_COUNT; + IF v_deleted_count IS DISTINCT FROM v_existing_count THEN + RAISE EXCEPTION 'a storage object changed before transactional cleanup deletion'; + END IF; + + SET CONSTRAINTS ALL IMMEDIATE; + RETURN; +END; +$cleanup$; + +REVOKE ALL ON FUNCTION storage.prepare_backtest_object_cleanup(jsonb) FROM PUBLIC; + +COMMENT ON FUNCTION storage.prepare_backtest_object_cleanup(jsonb) IS +'Transaction-scoped, SECURITY DEFINER compensation for exact unreferenced objects in the canonical backtest-results namespace. Source FK locks precede the storage.objects target lock; exact rows are deleted before the external-object boundary and remain rollbackable until the caller commits.'; diff --git a/db/canonical-baseline/V20260902000001__pipeline_bind_backtest_cleanup_ownership.sql b/db/canonical-baseline/V20260902000001__pipeline_bind_backtest_cleanup_ownership.sql new file mode 100644 index 0000000..540ec51 --- /dev/null +++ b/db/canonical-baseline/V20260902000001__pipeline_bind_backtest_cleanup_ownership.sql @@ -0,0 +1,990 @@ +-- Backtest compensation is allowed only for rows that were atomically bound to +-- the live producing attempt when the storage row was first registered. This +-- forward migration also closes the ADD FOREIGN KEY ... NOT VALID race left by +-- V20260902000000 without rewriting that already-applied migration. + +CREATE TABLE storage.backtest_attempt_cleanup_capabilities ( + attempt_id uuid PRIMARY KEY + REFERENCES backtest.run_attempts(id) ON DELETE CASCADE, + run_id uuid NOT NULL + REFERENCES backtest.runs(id), + claim_token uuid NOT NULL, + capability_hash character varying(64) NOT NULL UNIQUE + CHECK (capability_hash ~ '^[0-9a-f]{64}$'), + created_at timestamp with time zone DEFAULT clock_timestamp() NOT NULL +); + +COMMENT ON TABLE storage.backtest_attempt_cleanup_capabilities IS +'Protected non-forgeable cleanup identity generated inside the transaction that creates an attempt. Application roles receive no direct read or mutation privilege.'; + +CREATE OR REPLACE FUNCTION storage.capture_backtest_attempt_cleanup_capability() +RETURNS trigger +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = pg_catalog, pg_temp +AS $attempt_capability$ +DECLARE + v_capability text; +BEGIN + IF NEW.claim_token IS NULL THEN + RETURN NEW; + END IF; + + v_capability := encode(public.gen_random_bytes(32), 'hex'); + INSERT INTO storage.backtest_attempt_cleanup_capabilities( + attempt_id, + run_id, + claim_token, + capability_hash + ) VALUES ( + NEW.id, + NEW.run_id, + NEW.claim_token, + encode(public.digest(v_capability, 'sha256'), 'hex') + ); + PERFORM set_config( + 'idea2strategy.backtest_attempt_cleanup_capability', + v_capability, + true + ); + RETURN NEW; +END; +$attempt_capability$; + +REVOKE ALL ON FUNCTION storage.capture_backtest_attempt_cleanup_capability() FROM PUBLIC; + +CREATE TRIGGER capture_backtest_attempt_cleanup_capability +AFTER INSERT ON backtest.run_attempts +FOR EACH ROW +EXECUTE FUNCTION storage.capture_backtest_attempt_cleanup_capability(); + +CREATE TABLE storage.backtest_object_ownerships ( + object_id uuid PRIMARY KEY + REFERENCES storage.objects(id) ON DELETE CASCADE, + -- Do not add a redundant FK from run_id to backtest.runs. Terminal + -- publication holds that run row FOR UPDATE while this ownership row is + -- registered and committed through its narrow storage transaction; an FK + -- check on the second connection would self-deadlock. The producing-attempt + -- FK plus the definer trigger's exact attempt.run_id check proves the same + -- relationship without a second lock edge. + run_id uuid NOT NULL, + producing_attempt_id uuid NOT NULL + REFERENCES backtest.run_attempts(id), + producing_claim_token uuid NOT NULL, + cleanup_token_hash character varying(64) NOT NULL UNIQUE + CHECK (cleanup_token_hash ~ '^[0-9a-f]{64}$'), + created_at timestamp with time zone DEFAULT clock_timestamp() NOT NULL +); + +CREATE INDEX ix_backtest_object_ownerships_run_attempt + ON storage.backtest_object_ownerships(run_id, producing_attempt_id); + +COMMENT ON TABLE storage.backtest_object_ownerships IS +'Migration-owner ledger binding a newly registered canonical backtest object to its exact producing run and attempt. Application roles receive no direct mutation privilege.'; + +CREATE OR REPLACE FUNCTION storage.capture_backtest_object_ownership() +RETURNS trigger +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = pg_catalog, pg_temp +AS $capture$ +DECLARE + v_attempt_id uuid; + v_attempt_text text; + v_claim_token uuid; + v_claim_text text; + v_attempt_capability text; + v_cleanup_token_hash text; + v_key_run_id uuid; + v_run_id uuid; + v_run_text text; +BEGIN + v_run_text := nullif(current_setting('idea2strategy.backtest_run_id', true), ''); + v_attempt_text := nullif(current_setting('idea2strategy.backtest_attempt_id', true), ''); + v_claim_text := nullif(current_setting('idea2strategy.backtest_claim_token', true), ''); + v_attempt_capability := nullif( + current_setting('idea2strategy.backtest_attempt_cleanup_capability', true), + '' + ); + v_cleanup_token_hash := nullif( + current_setting('idea2strategy.backtest_cleanup_token_hash', true), + '' + ); + + -- Other producers still register storage rows through their own policy. A + -- backtest row is cleanup-owned only when the engine deliberately supplies + -- all four transaction-local ownership values before the INSERT. + IF v_run_text IS NULL + AND v_attempt_text IS NULL + AND v_claim_text IS NULL + AND v_attempt_capability IS NULL + AND v_cleanup_token_hash IS NULL THEN + RETURN NEW; + END IF; + IF v_run_text IS NULL + OR v_attempt_text IS NULL + OR v_claim_text IS NULL + OR v_attempt_capability IS NULL + OR v_cleanup_token_hash IS NULL THEN + RAISE EXCEPTION + 'backtest object producer ownership requires run, attempt, claim, and cleanup token together'; + END IF; + IF v_cleanup_token_hash !~ '^[0-9a-f]{64}$' THEN + RAISE EXCEPTION + 'backtest object producer cleanup token hash is invalid'; + END IF; + + BEGIN + v_run_id := v_run_text::uuid; + v_attempt_id := v_attempt_text::uuid; + v_claim_token := v_claim_text::uuid; + v_key_run_id := substring( + NEW.object_key FROM + '^backtest-results/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/' + )::uuid; + EXCEPTION + WHEN invalid_text_representation THEN + RAISE EXCEPTION + 'backtest object producer ownership contains an invalid UUID'; + END; + + IF v_key_run_id IS NULL OR v_key_run_id IS DISTINCT FROM v_run_id THEN + RAISE EXCEPTION + 'backtest object producer run does not match its canonical object key'; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM backtest.run_attempts AS attempt + WHERE attempt.id = v_attempt_id + AND attempt.run_id = v_run_id + AND attempt.claim_token = v_claim_token + AND attempt.status = 'RUNNING' + AND attempt.claim_expires_at > clock_timestamp() + AND EXISTS ( + SELECT 1 + FROM storage.backtest_attempt_cleanup_capabilities AS capability + WHERE capability.attempt_id = attempt.id + AND capability.run_id = attempt.run_id + AND capability.claim_token = attempt.claim_token + AND capability.capability_hash = encode( + public.digest(v_attempt_capability, 'sha256'), + 'hex' + ) + ) + ) THEN + RAISE EXCEPTION + 'backtest object producer ownership requires the current live attempt claim'; + END IF; + + INSERT INTO storage.backtest_object_ownerships( + object_id, + run_id, + producing_attempt_id, + producing_claim_token, + cleanup_token_hash + ) VALUES ( + NEW.id, + v_run_id, + v_attempt_id, + v_claim_token, + v_cleanup_token_hash + ); + RETURN NEW; +END; +$capture$; + +REVOKE ALL ON FUNCTION storage.capture_backtest_object_ownership() FROM PUBLIC; + +CREATE TRIGGER capture_backtest_object_ownership +AFTER INSERT ON storage.objects +FOR EACH ROW +EXECUTE FUNCTION storage.capture_backtest_object_ownership(); + +-- PostgreSQL reserves event-trigger administration to superusers. The deployed +-- Flyway identity is the RDS-managed main user (`idea2strategy_admin`), which AWS +-- assigns `rds_superuser`; local/rehearsal PostgreSQL uses a real superuser. Fail +-- here with an actionable contract message if deployment ever drifts to a weaker +-- migration identity rather than reaching CREATE EVENT TRIGGER ambiguously. +DO $event_trigger_capability$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM pg_roles AS caller + WHERE caller.rolname = current_user + AND ( + caller.rolsuper + OR EXISTS ( + SELECT 1 + FROM pg_roles AS rds_role + WHERE rds_role.rolname = 'rds_superuser' + AND pg_has_role(caller.oid, rds_role.oid, 'MEMBER') + ) + ) + ) THEN + RAISE EXCEPTION + 'storage FK safety requires Flyway to use a PostgreSQL superuser or the RDS main/rds_superuser role'; + END IF; +END; +$event_trigger_capability$; + +CREATE OR REPLACE FUNCTION storage.reject_unvalidated_storage_object_fks() +RETURNS event_trigger +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = pg_catalog, pg_temp +AS $reject$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM pg_event_trigger_ddl_commands() AS command + JOIN pg_constraint AS fk + ON fk.oid = command.objid + OR fk.conrelid = command.objid + WHERE fk.contype = 'f' + AND fk.confrelid = 'storage.objects'::regclass + AND NOT fk.convalidated + ) THEN + RAISE EXCEPTION + 'unvalidated foreign keys targeting storage.objects are forbidden'; + END IF; +END; +$reject$; + +REVOKE ALL ON FUNCTION storage.reject_unvalidated_storage_object_fks() FROM PUBLIC; + +CREATE EVENT TRIGGER storage_reject_unvalidated_object_fks +ON ddl_command_end +WHEN TAG IN ('ALTER TABLE', 'CREATE TABLE', 'CREATE TABLE AS') +EXECUTE FUNCTION storage.reject_unvalidated_storage_object_fks(); + +COMMENT ON EVENT TRIGGER storage_reject_unvalidated_object_fks IS +'Rejects only DDL that leaves an unvalidated foreign key targeting storage.objects. AWS RDS major upgrades require this event trigger to be dropped before upgrade and recreated immediately afterwards; see db migration README.'; + +CREATE OR REPLACE FUNCTION storage.reissue_backtest_object_cleanup( + p_candidate jsonb, + p_new_cleanup_token_hash text +) +RETURNS uuid +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = pg_catalog, pg_temp +SET lock_timeout = '5s' +AS $reissue$ +DECLARE + v_attempt_capability text; + v_attempt_id uuid; + v_attempt_text text; + v_candidate record; + v_claim_text text; + v_claim_token uuid; + v_reference_exists boolean; + v_run_id uuid; + v_run_text text; + v_source record; +BEGIN + IF jsonb_typeof(p_candidate) IS DISTINCT FROM 'object' + OR ( + SELECT array_agg(key ORDER BY key) + FROM jsonb_object_keys(p_candidate) AS keys(key) + ) IS DISTINCT FROM ARRAY[ + 'bucket_name', + 'content_hash', + 'object_id', + 'object_key', + 'provider_version_id', + 'storage_provider' + ]::text[] THEN + RAISE EXCEPTION 'backtest object cleanup reissue candidate shape is invalid'; + END IF; + IF p_new_cleanup_token_hash !~ '^[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'backtest object cleanup reissue token hash is invalid'; + END IF; + + SELECT * + INTO v_candidate + FROM jsonb_to_record(p_candidate) AS candidate( + object_id uuid, + storage_provider text, + bucket_name text, + object_key text, + provider_version_id text, + content_hash text + ); + IF v_candidate.object_id IS NULL + OR nullif(v_candidate.storage_provider, '') IS NULL + OR nullif(v_candidate.bucket_name, '') IS NULL + OR nullif(v_candidate.object_key, '') IS NULL + OR nullif(v_candidate.provider_version_id, '') IS NULL + OR v_candidate.content_hash !~ '^[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'backtest object cleanup reissue requires an exact object identity'; + END IF; + + v_run_text := nullif(current_setting('idea2strategy.backtest_run_id', true), ''); + v_attempt_text := nullif(current_setting('idea2strategy.backtest_attempt_id', true), ''); + v_claim_text := nullif(current_setting('idea2strategy.backtest_claim_token', true), ''); + v_attempt_capability := nullif( + current_setting('idea2strategy.backtest_attempt_cleanup_capability', true), + '' + ); + IF v_run_text IS NULL + OR v_attempt_text IS NULL + OR v_claim_text IS NULL + OR v_attempt_capability IS NULL THEN + RAISE EXCEPTION 'backtest object cleanup reissue requires current attempt capability context'; + END IF; + BEGIN + v_run_id := v_run_text::uuid; + v_attempt_id := v_attempt_text::uuid; + v_claim_token := v_claim_text::uuid; + EXCEPTION + WHEN invalid_text_representation THEN + RAISE EXCEPTION 'backtest object cleanup reissue attempt context is invalid'; + END; + + -- Lock the live successor attempt, rather than its run row. Attempt creation + -- always locks the run and then the previous latest attempt; therefore this + -- lock serializes expiry/reclaim and successor insertion without deadlocking + -- terminal publication, which already owns the run row on its outer UOW while + -- storage registration commits through a separate narrow UOW. + PERFORM caller.id + FROM backtest.run_attempts AS caller + JOIN storage.backtest_attempt_cleanup_capabilities AS capability + ON capability.attempt_id = caller.id + AND capability.run_id = caller.run_id + AND capability.claim_token = caller.claim_token + WHERE caller.id = v_attempt_id + AND caller.run_id = v_run_id + AND caller.claim_token = v_claim_token + AND caller.status = 'RUNNING' + AND caller.claim_expires_at > clock_timestamp() + AND capability.capability_hash = encode( + public.digest(v_attempt_capability, 'sha256'), + 'hex' + ) + AND NOT EXISTS ( + SELECT 1 + FROM backtest.run_attempts AS newer + WHERE newer.run_id = caller.run_id + AND newer.attempt_number > caller.attempt_number + ) + FOR UPDATE OF caller; + IF NOT FOUND THEN + RAISE EXCEPTION 'backtest object cleanup reissue claim is wrong, expired, or superseded'; + END IF; + + PERFORM object_row.id + FROM storage.objects AS object_row + WHERE object_row.id = v_candidate.object_id + AND object_row.storage_provider = v_candidate.storage_provider + AND object_row.bucket_name = v_candidate.bucket_name + AND object_row.object_key = v_candidate.object_key + AND object_row.provider_version_id = v_candidate.provider_version_id + AND object_row.content_hash = v_candidate.content_hash + FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'backtest object cleanup reissue identity changed'; + END IF; + + IF NOT EXISTS ( + WITH RECURSIVE caller_lineage AS ( + SELECT attempt.id, attempt.previous_attempt_id, 0 AS depth + FROM backtest.run_attempts AS attempt + WHERE attempt.id = v_attempt_id + UNION ALL + SELECT predecessor.id, predecessor.previous_attempt_id, lineage.depth + 1 + FROM backtest.run_attempts AS predecessor + JOIN caller_lineage AS lineage + ON predecessor.id = lineage.previous_attempt_id + ) + SELECT 1 + FROM storage.backtest_object_ownerships AS ownership + JOIN backtest.run_attempts AS producer + ON producer.id = ownership.producing_attempt_id + AND producer.run_id = ownership.run_id + AND producer.claim_token = ownership.producing_claim_token + JOIN caller_lineage AS lineage + ON lineage.id = producer.id + WHERE ownership.object_id = v_candidate.object_id + AND ownership.run_id = v_run_id + AND ( + lineage.depth = 0 + OR producer.status IN ('FAILED', 'CANCELLED', 'SKIPPED') + ) + ) THEN + -- Exact immutable objects are intentionally reusable across runs. No + -- ownership mutation and a NULL result means this caller may publish a + -- reference, but receives no capability to compensate someone else's + -- bytes. This also covers pre-migration/unowned reconciliations. + RETURN NULL; + END IF; + + IF EXISTS ( + SELECT 1 + FROM storage.objects AS object_row + WHERE object_row.id = v_candidate.object_id + AND ( + object_row.legal_hold + OR ( + object_row.retention_until IS NOT NULL + AND object_row.retention_until > clock_timestamp() + ) + ) + ) THEN + RETURN NULL; + END IF; + + FOR v_source IN + SELECT source_namespace.nspname AS source_schema, + source.relname AS source_table, + source_column.attname AS source_column, + fk.conname AS constraint_name, + fk.convalidated AS validated, + cardinality(fk.conkey) AS source_column_count, + target_column.attname AS target_column, + source.relkind AS source_relkind, + source.relispartition AS source_is_partition + FROM pg_constraint AS fk + JOIN pg_class AS source ON source.oid = fk.conrelid + JOIN pg_namespace AS source_namespace + ON source_namespace.oid = source.relnamespace + JOIN pg_attribute AS source_column + ON source_column.attrelid = source.oid + AND source_column.attnum = fk.conkey[1] + JOIN pg_attribute AS target_column + ON target_column.attrelid = fk.confrelid + AND target_column.attnum = fk.confkey[1] + WHERE fk.contype = 'f' + AND fk.confrelid = 'storage.objects'::regclass + ORDER BY source_namespace.nspname, source.relname, fk.conname + LOOP + IF NOT v_source.validated THEN + RAISE EXCEPTION 'unvalidated foreign key targets storage.objects; reissue fails closed'; + END IF; + IF v_source.source_schema = 'storage' + AND v_source.source_table = 'backtest_object_ownerships' + AND v_source.source_column = 'object_id' THEN + CONTINUE; + END IF; + IF v_source.source_column_count <> 1 + OR v_source.target_column <> 'id' + OR v_source.source_relkind <> 'r' + OR v_source.source_is_partition THEN + RAISE EXCEPTION 'unsupported storage.objects foreign-key shape; reissue fails closed'; + END IF; + EXECUTE format( + 'SELECT EXISTS (SELECT 1 FROM %I.%I WHERE %I = $1)', + v_source.source_schema, + v_source.source_table, + v_source.source_column + ) INTO v_reference_exists USING v_candidate.object_id; + IF v_reference_exists THEN + -- A committed reference makes the existing object non-compensable. + -- Preserve it and do not rotate its cleanup capability. + RETURN NULL; + END IF; + END LOOP; + + UPDATE storage.backtest_object_ownerships + SET producing_attempt_id = v_attempt_id, + producing_claim_token = v_claim_token, + cleanup_token_hash = p_new_cleanup_token_hash + WHERE object_id = v_candidate.object_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'backtest object cleanup reissue ownership vanished'; + END IF; + RETURN v_candidate.object_id; +END; +$reissue$; + +REVOKE ALL ON FUNCTION storage.reissue_backtest_object_cleanup(jsonb, text) FROM PUBLIC; + +CREATE OR REPLACE FUNCTION storage.prepare_backtest_object_cleanup(p_candidates jsonb) +RETURNS SETOF storage.objects +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = pg_catalog, pg_temp +SET lock_timeout = '5s' +AS $cleanup$ +DECLARE + v_attempt_id uuid; + v_attempt_capability text; + v_attempt_text text; + v_candidate_count integer; + v_candidate_ids uuid[]; + v_claim_token uuid; + v_claim_text text; + v_deleted_count integer; + v_existing_count integer; + v_foreign_keys jsonb; + v_lock_acquired boolean := false; + v_lock_attempt integer; + v_reference_exists boolean; + v_relation record; + v_run_id uuid; + v_run_text text; + v_source record; + v_unique_count integer; +BEGIN + IF jsonb_typeof(p_candidates) IS DISTINCT FROM 'array' + OR jsonb_array_length(p_candidates) = 0 THEN + RAISE EXCEPTION 'backtest object cleanup candidates must be a non-empty JSON array'; + END IF; + + IF EXISTS ( + SELECT 1 + FROM jsonb_array_elements(p_candidates) AS offered(candidate) + WHERE jsonb_typeof(offered.candidate) IS DISTINCT FROM 'object' + OR ( + SELECT array_agg(key ORDER BY key) + FROM jsonb_object_keys(offered.candidate) AS keys(key) + ) IS DISTINCT FROM ARRAY[ + 'bucket_name', + 'cleanup_token', + 'content_hash', + 'object_id', + 'object_key', + 'provider_version_id', + 'storage_provider' + ]::text[] + ) THEN + RAISE EXCEPTION 'backtest object cleanup candidate shape is invalid'; + END IF; + + SELECT count(*), count(DISTINCT candidate.object_id), + array_agg(candidate.object_id ORDER BY candidate.object_id) + INTO v_candidate_count, v_unique_count, v_candidate_ids + FROM jsonb_to_recordset(p_candidates) AS candidate( + object_id uuid, + storage_provider text, + bucket_name text, + object_key text, + provider_version_id text, + content_hash text + ); + + IF v_candidate_count IS DISTINCT FROM v_unique_count THEN + RAISE EXCEPTION 'backtest object cleanup candidate ids must be unique'; + END IF; + + IF EXISTS ( + SELECT 1 + FROM jsonb_to_recordset(p_candidates) AS candidate( + object_id uuid, + storage_provider text, + bucket_name text, + object_key text, + provider_version_id text, + content_hash text, + cleanup_token text + ) + WHERE candidate.object_id IS NULL + OR nullif(candidate.storage_provider, '') IS NULL + OR nullif(candidate.bucket_name, '') IS NULL + OR nullif(candidate.object_key, '') IS NULL + OR nullif(candidate.provider_version_id, '') IS NULL + OR candidate.content_hash !~ '^[0-9a-f]{64}$' + OR candidate.cleanup_token !~ '^[0-9a-f]{64}$' + OR NOT ( + ( + candidate.object_key ~ + '^backtest-results/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/[0-9a-f]{64}[.]json$' + AND candidate.object_key LIKE '%/' || candidate.content_hash || '.json' + ) + OR + ( + candidate.object_key ~ + '^backtest-results/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/[A-Z][A-Z0-9_]{0,49}/week_start=[0-9]{4}-[0-9]{2}-[0-9]{2}/part=[0-9]{4}/[0-9a-f]{64}[.]parquet$' + AND candidate.object_key LIKE '%/' || candidate.content_hash || '.parquet' + ) + ) + ) THEN + RAISE EXCEPTION + 'backtest object cleanup requires exact identities in the canonical backtest object namespace'; + END IF; + + -- Target-first locking prevents a new ADD FK from becoming visible between + -- catalog inspection and DELETE. Every durable table is then locked in a + -- DML-compatible mode using NOWAIT. If DDL already owns any possible source + -- and is waiting for the target, the PL/pgSQL exception subtransaction rolls + -- back immediately, releasing the target before a bounded retry. + FOR v_lock_attempt IN 1..12 LOOP + v_lock_acquired := false; + BEGIN + LOCK TABLE storage.objects + IN SHARE UPDATE EXCLUSIVE MODE NOWAIT; + + FOR v_relation IN + SELECT relation.oid AS relation_oid, + namespace.nspname AS relation_schema, + relation.relname AS relation_name + FROM pg_class AS relation + JOIN pg_namespace AS namespace + ON namespace.oid = relation.relnamespace + WHERE relation.relkind IN ('r', 'p') + AND relation.oid <> 'storage.objects'::regclass + AND namespace.nspname <> 'information_schema' + AND namespace.nspname !~ '^pg_(catalog|toast|temp_)' + ORDER BY namespace.nspname, relation.relname, relation.oid + LOOP + BEGIN + EXECUTE format( + 'LOCK TABLE %I.%I IN SHARE UPDATE EXCLUSIVE MODE NOWAIT', + v_relation.relation_schema, + v_relation.relation_name + ); + EXCEPTION + WHEN undefined_table THEN + RAISE lock_not_available USING MESSAGE = + 'a possible storage.objects foreign-key source changed during cleanup locking'; + END; + END LOOP; + v_lock_acquired := true; + EXCEPTION + WHEN lock_not_available OR deadlock_detected THEN + v_lock_acquired := false; + END; + + EXIT WHEN v_lock_acquired; + IF v_lock_attempt = 12 THEN + RAISE lock_not_available USING MESSAGE = + 'backtest object cleanup exhausted 12 bounded DDL-lock retries before external deletion'; + END IF; + PERFORM pg_sleep(least(0.01 * v_lock_attempt, 0.10)); + END LOOP; + + WITH foreign_keys AS ( + SELECT fk.oid AS constraint_oid, + fk.conname AS constraint_name, + source.oid AS source_oid, + source_namespace.nspname AS source_schema, + source.relname AS source_table, + source.relkind AS source_relkind, + source.relispartition AS source_is_partition, + EXISTS ( + SELECT 1 + FROM pg_inherits AS inheritance + WHERE inheritance.inhrelid = source.oid + OR inheritance.inhparent = source.oid + ) AS source_has_inheritance, + ARRAY( + SELECT source_column.attname + FROM unnest(fk.conkey) WITH ORDINALITY AS source_key(attnum, ordinality) + JOIN pg_attribute AS source_column + ON source_column.attrelid = source.oid + AND source_column.attnum = source_key.attnum + ORDER BY source_key.ordinality + ) AS source_columns, + target.relkind AS target_relkind, + target.relispartition AS target_is_partition, + EXISTS ( + SELECT 1 + FROM pg_inherits AS inheritance + WHERE inheritance.inhrelid = target.oid + OR inheritance.inhparent = target.oid + ) AS target_has_inheritance, + ARRAY( + SELECT target_column.attname + FROM unnest(fk.confkey) WITH ORDINALITY AS target_key(attnum, ordinality) + JOIN pg_attribute AS target_column + ON target_column.attrelid = target.oid + AND target_column.attnum = target_key.attnum + ORDER BY target_key.ordinality + ) AS target_columns, + fk.convalidated AS validated, + fk.condeferrable AS deferrable, + fk.confdeltype AS delete_action + FROM pg_constraint AS fk + JOIN pg_class AS source ON source.oid = fk.conrelid + JOIN pg_namespace AS source_namespace + ON source_namespace.oid = source.relnamespace + JOIN pg_class AS target ON target.oid = fk.confrelid + WHERE fk.contype = 'f' + AND fk.confrelid = 'storage.objects'::regclass + ) + SELECT coalesce( + jsonb_agg(to_jsonb(foreign_key) ORDER BY + foreign_key.source_schema, + foreign_key.source_table, + foreign_key.constraint_name, + foreign_key.constraint_oid), + '[]'::jsonb + ) + INTO v_foreign_keys + FROM foreign_keys AS foreign_key; + + FOR v_source IN + SELECT reference + FROM jsonb_array_elements(v_foreign_keys) AS reference_rows(reference) + LOOP + IF NOT (v_source.reference->>'validated')::boolean THEN + RAISE EXCEPTION + 'unvalidated foreign key %.% (constraint %) targets storage.objects; cleanup fails closed', + v_source.reference->>'source_schema', + v_source.reference->>'source_table', + v_source.reference->>'constraint_name'; + END IF; + + IF jsonb_array_length(v_source.reference->'source_columns') <> 1 + OR v_source.reference->'target_columns' <> '["id"]'::jsonb + OR v_source.reference->>'source_relkind' <> 'r' + OR (v_source.reference->>'source_is_partition')::boolean + OR (v_source.reference->>'source_has_inheritance')::boolean + OR v_source.reference->>'target_relkind' <> 'r' + OR (v_source.reference->>'target_is_partition')::boolean + OR (v_source.reference->>'target_has_inheritance')::boolean + OR ( + v_source.reference->>'delete_action' <> 'a' + AND NOT ( + v_source.reference->>'source_schema' = 'storage' + AND v_source.reference->>'source_table' = 'backtest_object_ownerships' + AND v_source.reference->'source_columns' = '["object_id"]'::jsonb + AND v_source.reference->>'delete_action' = 'c' + ) + ) THEN + RAISE EXCEPTION + 'unsupported storage.objects foreign-key shape at %.% (constraint %); cleanup fails closed', + v_source.reference->>'source_schema', + v_source.reference->>'source_table', + v_source.reference->>'constraint_name'; + END IF; + END LOOP; + + v_run_text := nullif(current_setting('idea2strategy.backtest_run_id', true), ''); + v_attempt_text := nullif(current_setting('idea2strategy.backtest_attempt_id', true), ''); + v_claim_text := nullif(current_setting('idea2strategy.backtest_claim_token', true), ''); + v_attempt_capability := nullif( + current_setting('idea2strategy.backtest_attempt_cleanup_capability', true), + '' + ); + IF v_run_text IS NULL + OR v_attempt_text IS NULL + OR v_claim_text IS NULL + OR v_attempt_capability IS NULL THEN + RAISE EXCEPTION + 'backtest object cleanup requires current producer ownership claim context'; + END IF; + BEGIN + v_run_id := v_run_text::uuid; + v_attempt_id := v_attempt_text::uuid; + v_claim_token := v_claim_text::uuid; + EXCEPTION + WHEN invalid_text_representation THEN + RAISE EXCEPTION + 'backtest object cleanup producer ownership claim contains an invalid UUID'; + END; + + -- Attempt creation/reclaim locks the run row first. Holding the same row + -- through external deletion fences a successor attempt from appearing after + -- the stale-predecessor check below. + PERFORM run_row.id + FROM backtest.runs AS run_row + WHERE run_row.id = v_run_id + FOR UPDATE; + + IF NOT FOUND OR NOT EXISTS ( + SELECT 1 + FROM backtest.run_attempts AS caller + WHERE caller.id = v_attempt_id + AND caller.run_id = v_run_id + AND caller.claim_token = v_claim_token + AND EXISTS ( + SELECT 1 + FROM storage.backtest_attempt_cleanup_capabilities AS capability + WHERE capability.attempt_id = caller.id + AND capability.run_id = caller.run_id + AND capability.claim_token = caller.claim_token + AND capability.capability_hash = encode( + public.digest(v_attempt_capability, 'sha256'), + 'hex' + ) + ) + AND ( + ( + caller.status = 'RUNNING' + AND caller.claim_expires_at > clock_timestamp() + ) + OR caller.status IN ('SUCCEEDED', 'FAILED', 'CANCELLED', 'SKIPPED') + ) + AND NOT EXISTS ( + SELECT 1 + FROM backtest.run_attempts AS successor + WHERE successor.run_id = caller.run_id + AND successor.attempt_number > caller.attempt_number + ) + ) THEN + RAISE EXCEPTION + 'backtest object cleanup claim is wrong, expired, stale, or superseded'; + END IF; + + PERFORM object_row.id + FROM storage.objects AS object_row + JOIN jsonb_to_recordset(p_candidates) AS candidate( + object_id uuid, + storage_provider text, + bucket_name text, + object_key text, + provider_version_id text, + content_hash text + ) ON candidate.object_id = object_row.id + ORDER BY object_row.id + FOR UPDATE OF object_row; + + SELECT count(*) + INTO v_existing_count + FROM storage.objects AS object_row + JOIN jsonb_to_recordset(p_candidates) AS candidate( + object_id uuid, + storage_provider text, + bucket_name text, + object_key text, + provider_version_id text, + content_hash text + ) ON candidate.object_id = object_row.id; + + IF EXISTS ( + SELECT 1 + FROM storage.objects AS object_row + JOIN jsonb_to_recordset(p_candidates) AS candidate( + object_id uuid, + storage_provider text, + bucket_name text, + object_key text, + provider_version_id text, + content_hash text + ) ON candidate.object_id = object_row.id + WHERE object_row.storage_provider IS DISTINCT FROM candidate.storage_provider + OR object_row.bucket_name IS DISTINCT FROM candidate.bucket_name + OR object_row.object_key IS DISTINCT FROM candidate.object_key + OR object_row.provider_version_id IS DISTINCT FROM candidate.provider_version_id + OR object_row.content_hash IS DISTINCT FROM candidate.content_hash + ) THEN + RAISE EXCEPTION + 'refusing to clean a storage object whose provider, bucket, key, provider version, or hash changed'; + END IF; + + IF EXISTS ( + SELECT 1 + FROM storage.objects AS object_row + JOIN jsonb_to_recordset(p_candidates) AS candidate( + object_id uuid, + storage_provider text, + bucket_name text, + object_key text, + provider_version_id text, + content_hash text + ) ON candidate.object_id = object_row.id + WHERE object_row.legal_hold + OR object_row.retention_until > clock_timestamp() + ) THEN + RAISE EXCEPTION + 'backtest object cleanup is blocked by legal hold or unexpired retention'; + END IF; + + IF ( + WITH RECURSIVE caller_lineage AS ( + SELECT attempt.id, attempt.previous_attempt_id + FROM backtest.run_attempts AS attempt + WHERE attempt.id = v_attempt_id + UNION ALL + SELECT predecessor.id, predecessor.previous_attempt_id + FROM backtest.run_attempts AS predecessor + JOIN caller_lineage AS lineage + ON predecessor.id = lineage.previous_attempt_id + ) + SELECT count(*) + FROM storage.objects AS object_row + JOIN jsonb_to_recordset(p_candidates) AS candidate( + object_id uuid, + storage_provider text, + bucket_name text, + object_key text, + provider_version_id text, + content_hash text, + cleanup_token text + ) ON candidate.object_id = object_row.id + JOIN storage.backtest_object_ownerships AS ownership + ON ownership.object_id = object_row.id + JOIN backtest.run_attempts AS producer + ON producer.id = ownership.producing_attempt_id + AND producer.run_id = ownership.run_id + AND producer.claim_token = ownership.producing_claim_token + WHERE ownership.run_id = v_run_id + AND ownership.cleanup_token_hash = encode( + public.digest(candidate.cleanup_token, 'sha256'), + 'hex' + ) + AND ownership.producing_attempt_id IN ( + SELECT lineage.id FROM caller_lineage AS lineage + ) + ) IS DISTINCT FROM v_existing_count THEN + RAISE EXCEPTION + 'backtest object cleanup candidate lacks exact producer ownership in the caller lineage'; + END IF; + + FOR v_source IN + SELECT reference->>'source_schema' AS source_schema, + reference->>'source_table' AS source_table, + reference->>'constraint_name' AS constraint_name, + reference->'source_columns'->>0 AS source_column + FROM jsonb_array_elements(v_foreign_keys) AS reference_rows(reference) + WHERE NOT ( + reference->>'source_schema' = 'storage' + AND reference->>'source_table' = 'backtest_object_ownerships' + AND reference->'source_columns' = '["object_id"]'::jsonb + ) + ORDER BY source_schema, source_table, constraint_name + LOOP + EXECUTE format( + 'SELECT EXISTS (' + 'SELECT 1 FROM %I.%I AS source_row ' + 'WHERE source_row.%I = ANY ($1))', + v_source.source_schema, + v_source.source_table, + v_source.source_column + ) + INTO v_reference_exists + USING v_candidate_ids; + + IF v_reference_exists THEN + RAISE EXCEPTION + 'storage object cleanup is referenced by %.%.% (constraint %)', + v_source.source_schema, + v_source.source_table, + v_source.source_column, + v_source.constraint_name; + END IF; + END LOOP; + + RETURN QUERY + DELETE FROM storage.objects AS object_row + USING jsonb_to_recordset(p_candidates) AS candidate( + object_id uuid, + storage_provider text, + bucket_name text, + object_key text, + provider_version_id text, + content_hash text + ) + WHERE object_row.id = candidate.object_id + AND object_row.storage_provider = candidate.storage_provider + AND object_row.bucket_name = candidate.bucket_name + AND object_row.object_key = candidate.object_key + AND object_row.provider_version_id = candidate.provider_version_id + AND object_row.content_hash = candidate.content_hash + RETURNING object_row.*; + + GET DIAGNOSTICS v_deleted_count = ROW_COUNT; + IF v_deleted_count IS DISTINCT FROM v_existing_count THEN + RAISE EXCEPTION 'a storage object changed before transactional cleanup deletion'; + END IF; + + SET CONSTRAINTS ALL IMMEDIATE; + RETURN; +END; +$cleanup$; + +REVOKE ALL ON FUNCTION storage.prepare_backtest_object_cleanup(jsonb) FROM PUBLIC; + +COMMENT ON FUNCTION storage.prepare_backtest_object_cleanup(jsonb) IS +'Transaction-scoped cleanup for exact backtest objects owned by the caller attempt lineage. Target-first NOWAIT retries serialize every durable FK source; unvalidated constraints, legal holds, and live retention always fail before external deletion.'; diff --git a/db/canonical-baseline/V20260902000002__backtest_narrow_runtime_attempt_writes.sql b/db/canonical-baseline/V20260902000002__backtest_narrow_runtime_attempt_writes.sql new file mode 100644 index 0000000..e7ffd52 --- /dev/null +++ b/db/canonical-baseline/V20260902000002__backtest_narrow_runtime_attempt_writes.sql @@ -0,0 +1,337 @@ +-- Attempt rows are protected ownership evidence. Runtime workers may claim, +-- heartbeat, close, and recover them only through these fenced capabilities. + +CREATE FUNCTION backtest.claim_run_attempt( + p_run_id uuid, + p_worker_id text, + p_execution_key text, + p_lease_milliseconds bigint +) +RETURNS SETOF backtest.run_attempts +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = pg_catalog, pg_temp +AS $claim$ +DECLARE + v_attempt_id uuid; + v_attempt_key text; + v_claim_token uuid; + v_inserted backtest.run_attempts%ROWTYPE; + v_latest backtest.run_attempts%ROWTYPE; + v_next_number integer := 1; + v_now timestamp with time zone := clock_timestamp(); + v_run record; +BEGIN + IF nullif(btrim(p_worker_id), '') IS NULL + OR nullif(btrim(p_execution_key), '') IS NULL THEN + RAISE EXCEPTION 'worker id and execution key must not be blank'; + END IF; + IF p_lease_milliseconds <= 0 OR p_lease_milliseconds > 86400000 THEN + RAISE EXCEPTION 'attempt lease must be between one millisecond and one day'; + END IF; + + SELECT run_row.status, run_row.cancellation_requested_at + INTO v_run + FROM backtest.runs AS run_row + WHERE run_row.id = p_run_id + FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'backtest run not found: %', p_run_id; + END IF; + IF v_run.status IN ('COMPLETED', 'FAILED', 'CANCELLED', 'UNAVAILABLE') + OR v_run.cancellation_requested_at IS NOT NULL THEN + RETURN; + END IF; + + SELECT attempt.* + INTO v_latest + FROM backtest.run_attempts AS attempt + WHERE attempt.run_id = p_run_id + ORDER BY attempt.attempt_number DESC + LIMIT 1 + FOR UPDATE; + + IF FOUND THEN + v_next_number := v_latest.attempt_number + 1; + IF v_latest.status IN ('SUCCEEDED', 'CANCELLED', 'SKIPPED') THEN + RETURN; + END IF; + IF v_latest.status = 'FAILED' + AND v_latest.terminal_reason_code NOT IN ('LEASE_EXPIRED', 'RETRY_RELEASED') THEN + RETURN; + END IF; + IF v_latest.status = 'RUNNING' THEN + IF v_latest.claim_expires_at IS NOT NULL + AND v_latest.claim_expires_at > v_now THEN + RETURN; + END IF; + UPDATE backtest.run_attempts AS attempt + SET status = 'FAILED', + completed_at = v_now, + failure_code = 'LEASE_EXPIRED', + terminal_reason_code = 'LEASE_EXPIRED' + WHERE attempt.id = v_latest.id + AND attempt.claim_token = v_latest.claim_token + AND attempt.status = 'RUNNING' + AND attempt.claim_expires_at <= v_now; + IF NOT FOUND THEN + RAISE EXCEPTION 'expired attempt was reclaimed concurrently'; + END IF; + END IF; + END IF; + + v_attempt_id := public.gen_random_uuid(); + v_claim_token := public.gen_random_uuid(); + v_attempt_key := p_execution_key || ':' || v_next_number; + IF length(v_attempt_key) > 160 THEN + RAISE EXCEPTION 'versioned worker execution key exceeds varchar(160)'; + END IF; + + INSERT INTO backtest.run_attempts( + id, + run_id, + attempt_number, + worker_execution_key, + status, + claim_token, + worker_id, + claimed_at, + claim_expires_at, + last_heartbeat_at, + previous_attempt_id, + started_at + ) VALUES ( + v_attempt_id, + p_run_id, + v_next_number, + v_attempt_key, + 'RUNNING', + v_claim_token, + p_worker_id, + v_now, + v_now + make_interval(secs => p_lease_milliseconds::double precision / 1000.0), + v_now, + CASE WHEN v_next_number = 1 THEN NULL ELSE v_latest.id END, + v_now + ) + ON CONFLICT DO NOTHING + RETURNING * INTO v_inserted; + IF NOT FOUND THEN + RAISE EXCEPTION 'attempt slot or execution key was claimed concurrently'; + END IF; + + UPDATE backtest.runs AS run_row + SET status = 'RUNNING', + started_at = coalesce(run_row.started_at, v_now) + WHERE run_row.id = p_run_id + AND run_row.status = 'QUEUED'; + + RETURN NEXT v_inserted; +END; +$claim$; + +REVOKE ALL ON FUNCTION backtest.claim_run_attempt(uuid, text, text, bigint) FROM PUBLIC; + +CREATE FUNCTION backtest.heartbeat_run_attempt( + p_attempt_id uuid, + p_claim_token uuid, + p_lease_milliseconds bigint +) +RETURNS SETOF backtest.run_attempts +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = pg_catalog, pg_temp +AS $heartbeat$ +DECLARE + v_updated backtest.run_attempts%ROWTYPE; + v_now timestamp with time zone := clock_timestamp(); +BEGIN + IF p_lease_milliseconds <= 0 OR p_lease_milliseconds > 86400000 THEN + RAISE EXCEPTION 'attempt lease must be between one millisecond and one day'; + END IF; + UPDATE backtest.run_attempts AS attempt + SET last_heartbeat_at = v_now, + claim_expires_at = v_now + + make_interval(secs => p_lease_milliseconds::double precision / 1000.0) + WHERE attempt.id = p_attempt_id + AND attempt.claim_token = p_claim_token + AND attempt.status = 'RUNNING' + AND attempt.claim_expires_at > v_now + RETURNING attempt.* INTO v_updated; + IF FOUND THEN + RETURN NEXT v_updated; + END IF; +END; +$heartbeat$; + +REVOKE ALL ON FUNCTION backtest.heartbeat_run_attempt(uuid, uuid, bigint) FROM PUBLIC; + +CREATE FUNCTION backtest.close_run_attempt( + p_attempt_id uuid, + p_claim_token uuid, + p_status text, + p_terminal_reason_code text, + p_failure_code text, + p_requeue boolean +) +RETURNS SETOF backtest.run_attempts +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = pg_catalog, pg_temp +AS $close$ +DECLARE + v_effective_failure text := p_failure_code; + v_effective_reason text := p_terminal_reason_code; + v_effective_status text := p_status; + v_existing backtest.run_attempts%ROWTYPE; + v_now timestamp with time zone := clock_timestamp(); + v_run record; + v_run_id uuid; + v_updated backtest.run_attempts%ROWTYPE; +BEGIN + IF p_status NOT IN ('SUCCEEDED', 'FAILED', 'CANCELLED', 'SKIPPED') + OR nullif(btrim(p_terminal_reason_code), '') IS NULL THEN + RAISE EXCEPTION 'attempt close requires a terminal status and reason'; + END IF; + IF p_requeue + AND (p_status <> 'FAILED' OR p_terminal_reason_code <> 'RETRY_RELEASED') THEN + RAISE EXCEPTION 'only RETRY_RELEASED may requeue a closed attempt'; + END IF; + + SELECT attempt.run_id + INTO v_run_id + FROM backtest.run_attempts AS attempt + WHERE attempt.id = p_attempt_id; + IF NOT FOUND THEN + RETURN; + END IF; + + SELECT run_row.status, run_row.cancellation_requested_at + INTO v_run + FROM backtest.runs AS run_row + WHERE run_row.id = v_run_id + FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'backtest run not found: %', v_run_id; + END IF; + + PERFORM attempt.id + FROM backtest.run_attempts AS attempt + WHERE attempt.id = p_attempt_id + FOR UPDATE; + IF NOT FOUND THEN + RETURN; + END IF; + + IF v_run.cancellation_requested_at IS NOT NULL + AND p_status = 'SUCCEEDED' THEN + v_effective_status := 'CANCELLED'; + v_effective_reason := 'CANCELLED_BY_REQUEST'; + v_effective_failure := NULL; + END IF; + + UPDATE backtest.run_attempts AS attempt + SET status = v_effective_status::operations.work_status, + completed_at = v_now, + terminal_reason_code = v_effective_reason, + failure_code = v_effective_failure + WHERE attempt.id = p_attempt_id + AND attempt.claim_token = p_claim_token + AND attempt.status = 'RUNNING' + AND attempt.claim_expires_at > v_now + RETURNING attempt.* INTO v_updated; + + IF NOT FOUND THEN + SELECT attempt.* + INTO v_existing + FROM backtest.run_attempts AS attempt + WHERE attempt.id = p_attempt_id; + IF FOUND + AND v_existing.claim_token = p_claim_token + AND v_existing.status::text = v_effective_status THEN + RETURN NEXT v_existing; + END IF; + RETURN; + END IF; + + IF v_effective_status = 'CANCELLED' + AND p_status = 'SUCCEEDED' THEN + UPDATE backtest.runs AS run_row + SET status = 'CANCELLED', + cancelled_at = v_now, + completed_at = v_now + WHERE run_row.id = v_run_id + AND run_row.status = 'RUNNING'; + END IF; + + IF p_requeue THEN + UPDATE backtest.runs AS run_row + SET status = 'QUEUED' + WHERE run_row.id = v_run_id + AND run_row.status = 'RUNNING' + AND run_row.cancellation_requested_at IS NULL; + END IF; + RETURN NEXT v_updated; +END; +$close$; + +REVOKE ALL ON FUNCTION + backtest.close_run_attempt(uuid, uuid, text, text, text, boolean) + FROM PUBLIC; + +CREATE FUNCTION backtest.recover_expired_run_attempt( + p_attempt_id uuid, + p_status text, + p_reason text +) +RETURNS integer +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = pg_catalog, pg_temp +AS $recover$ +DECLARE + v_now timestamp with time zone := clock_timestamp(); + v_row_count integer; +BEGIN + IF p_status NOT IN ('FAILED', 'CANCELLED') + OR nullif(btrim(p_reason), '') IS NULL THEN + RAISE EXCEPTION 'expired-attempt recovery requires FAILED or CANCELLED and a reason'; + END IF; + UPDATE backtest.run_attempts AS attempt + SET status = p_status::operations.work_status, + completed_at = v_now, + failure_code = CASE WHEN p_status = 'CANCELLED' THEN NULL ELSE p_reason END, + terminal_reason_code = p_reason + WHERE attempt.id = p_attempt_id + AND attempt.status = 'RUNNING' + AND (attempt.claim_expires_at IS NULL OR attempt.claim_expires_at <= v_now) + AND ( + (p_status = 'CANCELLED' AND EXISTS ( + SELECT 1 + FROM backtest.runs AS run_row + WHERE run_row.id = attempt.run_id + AND run_row.cancellation_requested_at IS NOT NULL + )) + OR + (p_status = 'FAILED' AND EXISTS ( + SELECT 1 + FROM backtest.runs AS run_row + WHERE run_row.id = attempt.run_id + AND run_row.cancellation_requested_at IS NULL + )) + ) + AND NOT EXISTS ( + SELECT 1 + FROM backtest.run_attempts AS newer + WHERE newer.run_id = attempt.run_id + AND newer.attempt_number > attempt.attempt_number + ); + GET DIAGNOSTICS v_row_count = ROW_COUNT; + RETURN v_row_count; +END; +$recover$; + +REVOKE ALL ON FUNCTION backtest.recover_expired_run_attempt(uuid, text, text) FROM PUBLIC; + +COMMENT ON FUNCTION backtest.claim_run_attempt(uuid, text, text, bigint) IS +'Fenced database-time claim capability; runtime roles cannot insert or update run_attempts directly.'; diff --git a/db/canonical-baseline/V20260902000003__pipeline_narrow_backtest_object_writes.sql b/db/canonical-baseline/V20260902000003__pipeline_narrow_backtest_object_writes.sql new file mode 100644 index 0000000..e5d9024 --- /dev/null +++ b/db/canonical-baseline/V20260902000003__pipeline_narrow_backtest_object_writes.sql @@ -0,0 +1,518 @@ +-- Runtime backtest workers may publish only through the staged-object lifecycle. +-- Keep the already-hardened +-- cleanup implementations from V20260902000001, but put a direct-successor gate +-- in front of them. Applied migrations remain untouched. + +CREATE OR REPLACE FUNCTION storage.capture_backtest_object_ownership() +RETURNS trigger +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = pg_catalog, pg_temp +AS $capture$ +DECLARE + v_attempt_id uuid; + v_attempt_text text; + v_claim_token uuid; + v_claim_text text; + v_attempt_capability text; + v_cleanup_token_hash text; + v_key_run_id uuid; + v_run_id uuid; + v_run_text text; +BEGIN + v_run_text := nullif(current_setting('idea2strategy.backtest_run_id', true), ''); + v_attempt_text := nullif(current_setting('idea2strategy.backtest_attempt_id', true), ''); + v_claim_text := nullif(current_setting('idea2strategy.backtest_claim_token', true), ''); + v_attempt_capability := nullif( + current_setting('idea2strategy.backtest_attempt_cleanup_capability', true), + '' + ); + v_cleanup_token_hash := nullif( + current_setting('idea2strategy.backtest_cleanup_token_hash', true), + '' + ); + + -- Non-backtest producers supply no attempt context and remain outside this + -- ledger. A backtest registration always supplies all four attempt fields. + -- The cleanup token alone is optional: provider-reconciled bytes that have no + -- authoritative row are registered for reading, but deliberately stay unowned. + IF v_run_text IS NULL + AND v_attempt_text IS NULL + AND v_claim_text IS NULL + AND v_attempt_capability IS NULL + AND v_cleanup_token_hash IS NULL THEN + RETURN NEW; + END IF; + IF v_run_text IS NULL + OR v_attempt_text IS NULL + OR v_claim_text IS NULL + OR v_attempt_capability IS NULL THEN + RAISE EXCEPTION + 'backtest object registration requires run, attempt, claim, and attempt capability together'; + END IF; + IF v_cleanup_token_hash IS NOT NULL + AND v_cleanup_token_hash !~ '^[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'backtest object producer cleanup token hash is invalid'; + END IF; + + BEGIN + v_run_id := v_run_text::uuid; + v_attempt_id := v_attempt_text::uuid; + v_claim_token := v_claim_text::uuid; + v_key_run_id := substring( + NEW.object_key FROM + '^backtest-results/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/' + )::uuid; + EXCEPTION + WHEN invalid_text_representation THEN + RAISE EXCEPTION 'backtest object producer ownership contains an invalid UUID'; + END; + + IF v_key_run_id IS NULL OR v_key_run_id IS DISTINCT FROM v_run_id THEN + RAISE EXCEPTION 'backtest object producer run does not match its canonical object key'; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM backtest.run_attempts AS attempt + JOIN storage.backtest_attempt_cleanup_capabilities AS capability + ON capability.attempt_id = attempt.id + AND capability.run_id = attempt.run_id + AND capability.claim_token = attempt.claim_token + WHERE attempt.id = v_attempt_id + AND attempt.run_id = v_run_id + AND attempt.claim_token = v_claim_token + AND attempt.status = 'RUNNING' + AND attempt.claim_expires_at > clock_timestamp() + AND capability.capability_hash = encode( + public.digest(v_attempt_capability, 'sha256'), + 'hex' + ) + ) THEN + RAISE EXCEPTION 'backtest object registration requires the current live attempt claim'; + END IF; + + IF v_cleanup_token_hash IS NULL THEN + RETURN NEW; + END IF; + + INSERT INTO storage.backtest_object_ownerships( + object_id, + run_id, + producing_attempt_id, + producing_claim_token, + cleanup_token_hash + ) VALUES ( + NEW.id, + v_run_id, + v_attempt_id, + v_claim_token, + v_cleanup_token_hash + ); + RETURN NEW; +END; +$capture$; + +ALTER FUNCTION storage.reissue_backtest_object_cleanup(jsonb, text) + RENAME TO reissue_backtest_object_cleanup_recursive_legacy; +ALTER FUNCTION storage.prepare_backtest_object_cleanup(jsonb) + RENAME TO prepare_backtest_object_cleanup_recursive_legacy; + +REVOKE ALL ON FUNCTION + storage.reissue_backtest_object_cleanup_recursive_legacy(jsonb, text) + FROM PUBLIC; +REVOKE ALL ON FUNCTION + storage.prepare_backtest_object_cleanup_recursive_legacy(jsonb) + FROM PUBLIC; + +DO $revoke_legacy_cleanup$ +DECLARE + v_role text; +BEGIN + FOREACH v_role IN ARRAY ARRAY[ + 'idea2strategy_backend', + 'idea2strategy_batch', + 'idea2strategy_trading', + 'idea2strategy_backtest', + 'idea2strategy_pipeline' + ] LOOP + IF to_regrole(v_role) IS NOT NULL THEN + EXECUTE format( + 'REVOKE ALL ON FUNCTION storage.reissue_backtest_object_cleanup_recursive_legacy(jsonb, text) FROM %I', + v_role + ); + EXECUTE format( + 'REVOKE ALL ON FUNCTION storage.prepare_backtest_object_cleanup_recursive_legacy(jsonb) FROM %I', + v_role + ); + END IF; + END LOOP; +END; +$revoke_legacy_cleanup$; + +CREATE FUNCTION storage.reissue_backtest_object_cleanup( + p_candidate jsonb, + p_new_cleanup_token_hash text +) +RETURNS uuid +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = pg_catalog, pg_temp +SET lock_timeout = '5s' +AS $reissue$ +DECLARE + v_attempt_id uuid; + v_attempt_text text; + v_candidate_id uuid; + v_owner_attempt_id uuid; + v_previous_attempt_id uuid; + v_run_id uuid; + v_run_text text; +BEGIN + -- Preserve the legacy function's closed input contract before inspecting the + -- protected ownership ledger. + IF jsonb_typeof(p_candidate) IS DISTINCT FROM 'object' + OR ( + SELECT array_agg(key ORDER BY key) + FROM jsonb_object_keys(p_candidate) AS keys(key) + ) IS DISTINCT FROM ARRAY[ + 'bucket_name', + 'content_hash', + 'object_id', + 'object_key', + 'provider_version_id', + 'storage_provider' + ]::text[] THEN + RAISE EXCEPTION 'backtest object cleanup reissue candidate shape is invalid'; + END IF; + IF p_new_cleanup_token_hash !~ '^[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'backtest object cleanup reissue token hash is invalid'; + END IF; + + v_attempt_text := nullif(current_setting('idea2strategy.backtest_attempt_id', true), ''); + v_run_text := nullif(current_setting('idea2strategy.backtest_run_id', true), ''); + IF v_attempt_text IS NULL OR v_run_text IS NULL THEN + RAISE EXCEPTION 'backtest object cleanup reissue requires current attempt capability context'; + END IF; + BEGIN + v_attempt_id := v_attempt_text::uuid; + v_run_id := v_run_text::uuid; + v_candidate_id := (p_candidate->>'object_id')::uuid; + EXCEPTION + WHEN invalid_text_representation THEN + RAISE EXCEPTION 'backtest object cleanup reissue attempt context is invalid'; + END; + + SELECT attempt.previous_attempt_id + INTO v_previous_attempt_id + FROM backtest.run_attempts AS attempt + WHERE attempt.id = v_attempt_id + AND attempt.run_id = v_run_id; + + SELECT ownership.producing_attempt_id + INTO v_owner_attempt_id + FROM storage.backtest_object_ownerships AS ownership + WHERE ownership.object_id = v_candidate_id + AND ownership.run_id = v_run_id; + + -- An exact unowned object, an unrelated object, and an older ancestor are all + -- reusable immutable bytes, but none may be adopted for compensation. + IF v_owner_attempt_id IS NULL + OR v_owner_attempt_id NOT IN (v_attempt_id, v_previous_attempt_id) THEN + RETURN NULL; + END IF; + + RETURN storage.reissue_backtest_object_cleanup_recursive_legacy( + p_candidate, + p_new_cleanup_token_hash + ); +END; +$reissue$; + +REVOKE ALL ON FUNCTION storage.reissue_backtest_object_cleanup(jsonb, text) FROM PUBLIC; + +CREATE FUNCTION storage.prepare_backtest_object_cleanup(p_candidates jsonb) +RETURNS SETOF storage.objects +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = pg_catalog, pg_temp +SET lock_timeout = '5s' +AS $cleanup$ +DECLARE + v_attempt_id uuid; + v_attempt_text text; + v_previous_attempt_id uuid; + v_run_id uuid; + v_run_text text; +BEGIN + IF jsonb_typeof(p_candidates) IS DISTINCT FROM 'array' THEN + RETURN QUERY + SELECT * + FROM storage.prepare_backtest_object_cleanup_recursive_legacy(p_candidates); + RETURN; + END IF; + + v_attempt_text := nullif(current_setting('idea2strategy.backtest_attempt_id', true), ''); + v_run_text := nullif(current_setting('idea2strategy.backtest_run_id', true), ''); + IF v_attempt_text IS NULL OR v_run_text IS NULL THEN + RAISE EXCEPTION 'backtest object cleanup requires current producer ownership claim context'; + END IF; + BEGIN + v_attempt_id := v_attempt_text::uuid; + v_run_id := v_run_text::uuid; + EXCEPTION + WHEN invalid_text_representation THEN + RAISE EXCEPTION 'backtest object cleanup producer ownership claim contains an invalid UUID'; + END; + + SELECT attempt.previous_attempt_id + INTO v_previous_attempt_id + FROM backtest.run_attempts AS attempt + WHERE attempt.id = v_attempt_id + AND attempt.run_id = v_run_id; + + IF EXISTS ( + SELECT 1 + FROM jsonb_to_recordset(p_candidates) AS candidate(object_id uuid) + JOIN storage.backtest_object_ownerships AS ownership + ON ownership.object_id = candidate.object_id + WHERE ownership.run_id = v_run_id + AND ownership.producing_attempt_id NOT IN ( + v_attempt_id, + v_previous_attempt_id + ) + ) THEN + RAISE EXCEPTION + 'backtest object cleanup candidate lacks exact producer ownership by the attempt or its immediate successor'; + END IF; + + RETURN QUERY + SELECT * + FROM storage.prepare_backtest_object_cleanup_recursive_legacy(p_candidates); +END; +$cleanup$; + +REVOKE ALL ON FUNCTION storage.prepare_backtest_object_cleanup(jsonb) FROM PUBLIC; + +CREATE FUNCTION storage.register_backtest_object(p_object jsonb) +RETURNS SETOF storage.objects +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = pg_catalog, pg_temp +AS $register$ +DECLARE + v_object record; + v_registered storage.objects%ROWTYPE; +BEGIN + IF jsonb_typeof(p_object) IS DISTINCT FROM 'object' + OR ( + SELECT array_agg(key ORDER BY key) + FROM jsonb_object_keys(p_object) AS keys(key) + ) IS DISTINCT FROM ARRAY[ + 'bucket_name', 'byte_size', 'compression_codec', 'content_hash', + 'created_at', 'deleted_at', 'encryption_key_ref', 'file_format', 'id', + 'legal_hold', 'media_type', 'object_key', 'period_end', 'period_start', + 'provider_version_id', 'quarantined_at', 'retention_policy_version', + 'retention_until', 'row_count', 'schema_version', 'status', + 'storage_provider', 'superseded_at', 'verified_at' + ]::text[] THEN + RAISE EXCEPTION 'backtest storage registration document shape is invalid'; + END IF; + + SELECT * + INTO v_object + FROM jsonb_to_record(p_object) AS object_document( + id uuid, + status text, + storage_provider text, + bucket_name text, + object_key text, + provider_version_id text, + content_hash text, + byte_size bigint, + file_format text, + compression_codec text, + media_type text, + schema_version text, + row_count bigint, + period_start timestamp with time zone, + period_end timestamp with time zone, + encryption_key_ref text, + retention_policy_version text, + retention_until timestamp with time zone, + legal_hold boolean, + created_at timestamp with time zone, + verified_at timestamp with time zone, + quarantined_at timestamp with time zone, + superseded_at timestamp with time zone, + deleted_at timestamp with time zone + ); + IF v_object.id IS NULL + OR v_object.status IS DISTINCT FROM 'STAGED' + OR nullif(v_object.storage_provider, '') IS NULL + OR nullif(v_object.bucket_name, '') IS NULL + OR nullif(v_object.object_key, '') IS NULL + OR nullif(v_object.provider_version_id, '') IS NULL + OR v_object.content_hash !~ '^[0-9a-f]{64}$' + OR v_object.byte_size < 0 + OR nullif(v_object.file_format, '') IS NULL + OR nullif(v_object.compression_codec, '') IS NULL + OR nullif(v_object.media_type, '') IS NULL + OR nullif(v_object.schema_version, '') IS NULL + OR (v_object.row_count IS NOT NULL AND v_object.row_count < 0) + OR (v_object.period_start IS NOT NULL AND v_object.period_end < v_object.period_start) + OR nullif(v_object.retention_policy_version, '') IS NULL + OR v_object.legal_hold IS NULL + OR v_object.created_at IS NULL + OR v_object.verified_at IS NOT NULL + OR v_object.quarantined_at IS NOT NULL + OR v_object.superseded_at IS NOT NULL + OR v_object.deleted_at IS NOT NULL THEN + RAISE EXCEPTION 'backtest storage registration requires one exact STAGED object'; + END IF; + IF nullif(current_setting('idea2strategy.backtest_run_id', true), '') IS NULL + OR nullif(current_setting('idea2strategy.backtest_attempt_id', true), '') IS NULL + OR nullif(current_setting('idea2strategy.backtest_claim_token', true), '') IS NULL + OR nullif(current_setting('idea2strategy.backtest_attempt_cleanup_capability', true), '') IS NULL THEN + RAISE EXCEPTION 'backtest storage registration requires current attempt context'; + END IF; + + INSERT INTO storage.objects( + id, status, storage_provider, bucket_name, object_key, + provider_version_id, content_hash, byte_size, file_format, + compression_codec, media_type, schema_version, row_count, + period_start, period_end, encryption_key_ref, retention_policy_version, + retention_until, legal_hold, created_at, verified_at, quarantined_at, + superseded_at, deleted_at + ) VALUES ( + v_object.id, 'STAGED', v_object.storage_provider, v_object.bucket_name, + v_object.object_key, v_object.provider_version_id, v_object.content_hash, + v_object.byte_size, v_object.file_format, v_object.compression_codec, + v_object.media_type, v_object.schema_version, v_object.row_count, + v_object.period_start, v_object.period_end, v_object.encryption_key_ref, + v_object.retention_policy_version, v_object.retention_until, + v_object.legal_hold, v_object.created_at, NULL, NULL, NULL, NULL + ) + ON CONFLICT DO NOTHING + RETURNING * INTO v_registered; + IF FOUND THEN + RETURN NEXT v_registered; + END IF; +END; +$register$; + +REVOKE ALL ON FUNCTION storage.register_backtest_object(jsonb) FROM PUBLIC; + +CREATE FUNCTION storage.transition_backtest_object( + p_object_id uuid, + p_target text, + p_at timestamp with time zone +) +RETURNS SETOF storage.objects +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = pg_catalog, pg_temp +AS $transition$ +DECLARE + v_attempt_capability text; + v_attempt_id uuid; + v_attempt_text text; + v_claim_token uuid; + v_claim_text text; + v_key_run_id uuid; + v_run_id uuid; + v_run_text text; + v_updated storage.objects%ROWTYPE; +BEGIN + IF p_target NOT IN ('AVAILABLE', 'QUARANTINED') OR p_at IS NULL THEN + RAISE EXCEPTION 'backtest object transition target is invalid'; + END IF; + v_run_text := nullif(current_setting('idea2strategy.backtest_run_id', true), ''); + v_attempt_text := nullif(current_setting('idea2strategy.backtest_attempt_id', true), ''); + v_claim_text := nullif(current_setting('idea2strategy.backtest_claim_token', true), ''); + v_attempt_capability := nullif( + current_setting('idea2strategy.backtest_attempt_cleanup_capability', true), + '' + ); + IF v_run_text IS NULL + OR v_attempt_text IS NULL + OR v_claim_text IS NULL + OR v_attempt_capability IS NULL THEN + RAISE EXCEPTION 'backtest object transition requires current attempt context'; + END IF; + BEGIN + v_run_id := v_run_text::uuid; + v_attempt_id := v_attempt_text::uuid; + v_claim_token := v_claim_text::uuid; + EXCEPTION + WHEN invalid_text_representation THEN + RAISE EXCEPTION 'backtest object transition attempt context is invalid'; + END; + + IF NOT EXISTS ( + SELECT 1 + FROM backtest.run_attempts AS attempt + JOIN storage.backtest_attempt_cleanup_capabilities AS capability + ON capability.attempt_id = attempt.id + AND capability.run_id = attempt.run_id + AND capability.claim_token = attempt.claim_token + WHERE attempt.id = v_attempt_id + AND attempt.run_id = v_run_id + AND attempt.claim_token = v_claim_token + AND attempt.status = 'RUNNING' + AND attempt.claim_expires_at > clock_timestamp() + AND capability.capability_hash = encode( + public.digest(v_attempt_capability, 'sha256'), + 'hex' + ) + ) THEN + RAISE EXCEPTION 'backtest object transition requires the current live attempt claim'; + END IF; + + SELECT object_row.* + INTO v_updated + FROM storage.objects AS object_row + WHERE object_row.id = p_object_id; + IF FOUND AND v_updated.status = p_target::storage.object_status THEN + RETURN NEXT v_updated; + RETURN; + END IF; + + SELECT substring( + object_row.object_key FROM + '^backtest-results/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/' + )::uuid + INTO v_key_run_id + FROM storage.objects AS object_row + WHERE object_row.id = p_object_id; + IF v_key_run_id IS NULL OR v_key_run_id IS DISTINCT FROM v_run_id THEN + RAISE EXCEPTION 'backtest object transition run does not match its canonical object key'; + END IF; + + IF p_target = 'AVAILABLE' THEN + UPDATE storage.objects AS object_row + SET status = 'AVAILABLE', verified_at = p_at + WHERE object_row.id = p_object_id + AND object_row.status = 'STAGED' + RETURNING object_row.* INTO v_updated; + ELSE + UPDATE storage.objects AS object_row + SET status = 'QUARANTINED', quarantined_at = p_at + WHERE object_row.id = p_object_id + AND object_row.status IN ('STAGED', 'AVAILABLE') + RETURNING object_row.* INTO v_updated; + END IF; + IF FOUND THEN + RETURN NEXT v_updated; + END IF; +END; +$transition$; + +REVOKE ALL ON FUNCTION + storage.transition_backtest_object(uuid, text, timestamp with time zone) + FROM PUBLIC; + +COMMENT ON FUNCTION storage.register_backtest_object(jsonb) IS +'Registers only a STAGED canonical backtest object for a live attempt; reconciled provider bytes may remain deliberately unowned.'; +COMMENT ON FUNCTION storage.prepare_backtest_object_cleanup(jsonb) IS +'Direct-producer or immediate-successor gate around the DDL-safe exact-version cleanup implementation.'; diff --git a/db/canonical-baseline/baseline.manifest b/db/canonical-baseline/baseline.manifest index f93e97d..132a139 100644 --- a/db/canonical-baseline/baseline.manifest +++ b/db/canonical-baseline/baseline.manifest @@ -1,3 +1,11 @@ idea2strategy-canonical-baseline-v1 -R__database_runtime_grants.sql ea0098679329c5fc3c5115e2ddb07a3a4a3e84d2da9f76d47bf462d3aa03eab6 -V1__initial_schema.sql e3bec37557b570d9a33c10a07e3e5c706ab56105dec409ad5ddb800720517282 +R__database_runtime_grants.sql 30a9381d6ccf07c5dddfab0614f82f3613b3dafe678aeacd953f1ef2d3dfada7 +V1__initial_schema.sql ccc5950a4d23b9c8f07b895a83dbea18a9fb072523b56b121eecb65bec15c533 +V20260825000000__backend_basic_strategy_execution_completion.sql 5847cef02039bd9b327ac6ffbe35b097ef476f1a973ad87307957f6a3c440418 +V20260825000001__pipeline_basic_strategy_feature_catalog.sql 436585f89fb6943560986934b4f9e49a07a3e5c743860f426222c7e7ef0bb18b +V20260826010000__backend_bind_room_invitations_to_accounts.sql 0c3aa10b846b36331fcfa662b4016ba94108111020e166a35c4a46db88883c02 +V20260827090000__backtest_add_owner_soft_delete.sql 1233961c05bb4d25d55d101d6448456dda2116a5b08303e15c499d4abe209bb2 +V20260902000000__pipeline_backtest_object_cleanup_capability.sql b994b7c21a9f772d09bb17c027a6c0423a8be3db2d757e326bb3fbf92a135288 +V20260902000001__pipeline_bind_backtest_cleanup_ownership.sql 0d2a0944cf9812d0cdc36b21ff8850a67d8e021b07f95c97279001547f195c62 +V20260902000002__backtest_narrow_runtime_attempt_writes.sql 28e695e043aa69d6450be704dd8246a6f5d249f5aa2e2662d14206af55015cb6 +V20260902000003__pipeline_narrow_backtest_object_writes.sql c891135328d19c2c6efb7db658ac48e41c45f590a6b35c765a5d112ec27a0068 diff --git a/db/canonical-baseline/baseline.sha256 b/db/canonical-baseline/baseline.sha256 index b52a4dd..d3fb384 100644 --- a/db/canonical-baseline/baseline.sha256 +++ b/db/canonical-baseline/baseline.sha256 @@ -1 +1 @@ -4833d2ac64733c44a9dd50fd225dc53146de956582d196645fff7939eb3b1908 +1dc826948878b358058b19b7623562a5e8fd85855677dd0791008eea433d138e diff --git a/modules/trading-persistence/src/test/java/com/idea2strategy/trading/persistence/canonical/CanonicalBaselineContractTest.java b/modules/trading-persistence/src/test/java/com/idea2strategy/trading/persistence/canonical/CanonicalBaselineContractTest.java index e2b938e..c956ac6 100644 --- a/modules/trading-persistence/src/test/java/com/idea2strategy/trading/persistence/canonical/CanonicalBaselineContractTest.java +++ b/modules/trading-persistence/src/test/java/com/idea2strategy/trading/persistence/canonical/CanonicalBaselineContractTest.java @@ -58,9 +58,19 @@ void everyPinnedMigrationMatchesItsRecordedDigest() { } @Test - void theBaselineContainsOnlyTheRebasedV1AndRuntimeGrants() { + void theBaselineContainsTheRebasedV1TheApprovedLaterMigrationsAndRuntimeGrants() { assertEquals( - List.of("R__database_runtime_grants.sql", "V1__initial_schema.sql"), + List.of( + "R__database_runtime_grants.sql", + "V1__initial_schema.sql", + "V20260825000000__backend_basic_strategy_execution_completion.sql", + "V20260825000001__pipeline_basic_strategy_feature_catalog.sql", + "V20260826010000__backend_bind_room_invitations_to_accounts.sql", + "V20260827090000__backtest_add_owner_soft_delete.sql", + "V20260902000000__pipeline_backtest_object_cleanup_capability.sql", + "V20260902000001__pipeline_bind_backtest_cleanup_ownership.sql", + "V20260902000002__backtest_narrow_runtime_attempt_writes.sql", + "V20260902000003__pipeline_narrow_backtest_object_writes.sql"), CanonicalBaseline.presentMigrations()); } @@ -73,7 +83,7 @@ select count(*) from information_schema.tables .param(APPLICATION_SCHEMAS.toArray(String[]::new)) .query(Integer.class) .single(); - assertEquals(181, tables, "the pinned canonical baseline no longer produces the canonical schema"); + assertEquals(185, tables, "the pinned canonical baseline no longer produces the canonical schema"); } @Test