ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.
Python active-directorycloud-securitydefensive-validationfastapigood-first-issuemitre-attackopsecreactred-teamreportingsecurity
fix(db): reconcile managed schemas
Mafifrizif135b301bffb
diff --git a/ares/db/postgres.py b/ares/db/postgres.pyindex fc5292e..c1e54c5 100644--- a/ares/db/postgres.py+++ b/ares/db/postgres.py@@ -321,6 +321,257 @@ CREATE INDEX IF NOT EXISTS idx_ws_tickets_api_keyON websocket_tickets(api_key_id);"""+_POSTGRES_MANAGED_REVISION = "0008"+_POSTGRES_OLDER_REVISIONS = frozenset(+ {"0001", "0002", "0003", "0004", "0005", "0006", "0007"}+)+_POSTGRES_MIGRATION_REQUIRED_ERROR = "PostgreSQL schema migration required"+_POSTGRES_MANAGED_SCHEMA_ERROR = "Incompatible managed PostgreSQL schema"+_POSTGRES_SCHEMA_VALIDATION_ERROR = "PostgreSQL schema validation failed"+++class _PostgresMigrationRequiredError(RuntimeError):+ pass+++class _PostgresManagedSchemaError(RuntimeError):+ pass+++_POSTGRES_MANAGED_TABLES = frozenset(+ {+ "campaigns",+ "module_runs",+ "findings",+ "hosts",+ "credentials",+ "loot",+ "audit_log",+ "users",+ "api_keys",+ "refresh_tokens",+ "revoked_access_tokens",+ "rate_limit_events",+ "websocket_tickets",+ }+)++_POSTGRES_MANAGED_INDEXES = (+ ("module_runs", "idx_module_runs_campaign", ("campaign_id",)),+ ("module_runs", "idx_module_runs_completed", ("completed_at",)),+ ("findings", "idx_findings_campaign", ("campaign_id",)),+ ("findings", "idx_findings_severity", ("severity",)),+ ("findings", "idx_findings_fp", ("false_positive",)),+ ("findings", "idx_findings_mitre", ("mitre_technique",)),+ ("findings", "idx_findings_cvss", ("cvss_score",)),+ ("hosts", "idx_hosts_campaign", ("campaign_id",)),+ ("hosts", "idx_hosts_ip", ("ip_address",)),+ ("hosts", "idx_hosts_domain", ("domain",)),+ ("credentials", "idx_creds_campaign", ("campaign_id",)),+ ("credentials", "idx_creds_username", ("username",)),+ ("credentials", "idx_creds_type", ("cred_type",)),+ ("loot", "idx_loot_campaign", ("campaign_id",)),+ ("loot", "idx_loot_type", ("loot_type",)),+ ("audit_log", "idx_audit_campaign", ("campaign_id",)),+ ("audit_log", "idx_audit_actor", ("actor",)),+ ("audit_log", "idx_audit_action", ("action",)),+ ("users", "idx_users_username", ("username",)),+ ("users", "idx_users_role", ("role",)),+ ("api_keys", "idx_apikeys_user", ("user_id",)),+ ("api_keys", "idx_apikeys_prefix", ("key_prefix",)),+ ("refresh_tokens", "idx_refresh_user", ("user_id",)),+ ("refresh_tokens", "idx_refresh_exp", ("expires_at",)),+ ("revoked_access_tokens", "idx_rat_expires", ("expires_at",)),+ ("rate_limit_events", "idx_rle_ip", ("ip_address",)),+ ("rate_limit_events", "idx_rle_timestamp", ("timestamp",)),+ ("rate_limit_events", "idx_rle_blocked", ("blocked",)),+)++_POSTGRES_MANAGED_PRIMARY_KEYS = (+ ("campaigns", "campaigns_pkey", ("id",)),+ ("module_runs", "module_runs_pkey", ("id",)),+ ("findings", "findings_pkey", ("id",)),+ ("hosts", "hosts_pkey", ("id",)),+ ("credentials", "credentials_pkey", ("id",)),+ ("loot", "loot_pkey", ("id",)),+ ("audit_log", "audit_log_pkey", ("id",)),+ ("users", "users_pkey", ("id",)),+ ("api_keys", "api_keys_pkey", ("id",)),+ ("refresh_tokens", "refresh_tokens_pkey", ("id",)),+ (+ "revoked_access_tokens",+ "revoked_access_tokens_pkey",+ ("jti",),+ ),+ ("rate_limit_events", "rate_limit_events_pkey", ("id",)),+)++_POSTGRES_MANAGED_FOREIGN_KEYS = (+ (+ "module_runs",+ "fk_module_runs_campaign",+ ("campaign_id",),+ "campaigns",+ ("id",),+ "CASCADE",+ "c",+ ),+ (+ "findings",+ "fk_findings_campaign",+ ("campaign_id",),+ "campaigns",+ ("id",),+ "CASCADE",+ "c",+ ),+ (+ "hosts",+ "fk_hosts_campaign",+ ("campaign_id",),+ "campaigns",+ ("id",),+ "CASCADE",+ "c",+ ),+ (+ "credentials",+ "fk_credentials_campaign",+ ("campaign_id",),+ "campaigns",+ ("id",),+ "CASCADE",+ "c",+ ),+ (+ "credentials",+ "fk_credentials_host",+ ("host_id",),+ "hosts",+ ("id",),+ "SET NULL",+ "n",+ ),+ (+ "loot",+ "fk_loot_campaign",+ ("campaign_id",),+ "campaigns",+ ("id",),+ "CASCADE",+ "c",+ ),+ (+ "loot",+ "fk_loot_host",+ ("host_id",),+ "hosts",+ ("id",),+ "SET NULL",+ "n",+ ),+ (+ "audit_log",+ "fk_audit_campaign",+ ("campaign_id",),+ "campaigns",+ ("id",),+ "SET NULL",+ "n",+ ),+ (+ "api_keys",+ "fk_api_keys_user",+ ("user_id",),+ "users",+ ("id",),+ "CASCADE",+ "c",+ ),+ (+ "refresh_tokens",+ "fk_refresh_tokens_user",+ ("user_id",),+ "users",+ ("id",),+ "CASCADE",+ "c",+ ),+)++_POSTGRES_MANAGED_UNIQUES = (+ ("hosts", "uq_hosts_campaign_ip", ("campaign_id", "ip_address")),+ ("users", "uq_users_username", ("username",)),+)++_POSTGRES_MANAGED_FINITE_CHECKS = (+ ("campaigns", "created_at", False),+ ("campaigns", "updated_at", False),+ ("module_runs", "completed_at", False),+ ("findings", "discovered_at", False),+ ("hosts", "first_seen", False),+ ("hosts", "last_seen", False),+ ("credentials", "captured_at", False),+ ("loot", "captured_at", False),+ ("audit_log", "timestamp", False),+ ("users", "created_at", False),+ ("users", "last_login", True),+ ("api_keys", "last_used", True),+ ("api_keys", "expires_at", True),+ ("api_keys", "created_at", False),+ ("refresh_tokens", "expires_at", False),+ ("refresh_tokens", "created_at", False),+ ("refresh_tokens", "used_at", True),+ ("rate_limit_events", "timestamp", False),+ ("revoked_access_tokens", "revoked_at", False),+ ("revoked_access_tokens", "expires_at", False),+)+++def _postgres_finite_check_name(table: str, column: str) -> str:+ if table == "module_runs":+ return "ck_module_runs_completed_at_finite"+ if table == "audit_log":+ return "ck_audit_log_timestamp_finite"+ if table == "rate_limit_events":+ return "ck_rate_limit_events_timestamp_finite"+ return f"ck_{table}_{column}_finite"+++def _postgres_constraint_definition(value: object) -> str:+ return " ".join(str(value).split())+++def _postgres_index_opclass(table: str, column: str) -> str:+ if (table, column) in {+ ("findings", "false_positive"),+ ("rate_limit_events", "blocked"),+ }:+ return "int4_ops"+ if (table, column) == ("findings", "cvss_score"):+ return "float8_ops"+ if (table, column) in {+ ("module_runs", "completed_at"),+ ("refresh_tokens", "expires_at"),+ ("revoked_access_tokens", "expires_at"),+ ("rate_limit_events", "timestamp"),+ }:+ return "timestamptz_ops"+ return "text_ops"+++def _classify_postgres_revision(values: tuple[object, ...]) -> str:+ if len(values) != 1 or not isinstance(values[0], str):+ raise _PostgresManagedSchemaError(_POSTGRES_MANAGED_SCHEMA_ERROR)+ revision = values[0]+ if revision == _POSTGRES_MANAGED_REVISION:+ return revision+ if revision in _POSTGRES_OLDER_REVISIONS:+ raise _PostgresMigrationRequiredError(+ _POSTGRES_MIGRATION_REQUIRED_ERROR+ )+ raise _PostgresManagedSchemaError(_POSTGRES_MANAGED_SCHEMA_ERROR)+class PostgresDatabase:"""@@ -416,27 +667,1340 @@ class PostgresDatabase:if self._pool:await self._pool.close()+ @staticmethod+ async def _managed_schema_revision(connection: Any) -> str | None:+ relation_rows = await connection.fetch(+ """+ SELECT rel.oid::bigint AS table_oid,+ nsp.nspname AS schema_name,+ relation_type.oid::bigint AS type_oid,+ type_nsp.nspname AS type_schema,+ relation_type.typname AS type_name,+ relation_type.typtype,+ relation_type.typrelid::bigint AS type_relation_oid,+ rel.relkind,+ rel.relpersistence,+ rel.relispartition,+ rel.relrowsecurity,+ rel.relforcerowsecurity,+ (+ SELECT count(*)+ FROM pg_inherits AS inherited+ WHERE inherited.inhrelid=rel.oid+ ) AS parent_count,+ (+ SELECT count(*)+ FROM pg_inherits AS inherited+ WHERE inherited.inhparent=rel.oid+ ) AS child_count,+ (+ SELECT count(*)+ FROM pg_policy AS policy+ WHERE policy.polrelid=rel.oid+ ) AS policy_count,+ (+ SELECT count(*)+ FROM pg_trigger AS trigger_record+ WHERE trigger_record.tgrelid=rel.oid+ AND NOT trigger_record.tgisinternal+ ) AS user_trigger_count,+ (+ SELECT count(*)+ FROM pg_rewrite AS rewrite+ WHERE rewrite.ev_class=rel.oid+ ) AS user_rule_count+ FROM pg_class AS rel+ JOIN pg_namespace AS nsp ON nsp.oid=rel.relnamespace+ LEFT JOIN pg_type AS relation_type+ ON relation_type.oid=rel.reltype+ LEFT JOIN pg_namespace AS type_nsp+ ON type_nsp.oid=relation_type.typnamespace+ WHERE nsp.nspname=current_schema()+ AND rel.relname='alembic_version'+ """+ )+ if not relation_rows:+ return None+ if len(relation_rows) != 1:+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)+ relation = relation_rows[0]+ try:+ table_oid = int(relation["table_oid"])+ schema_name = relation["schema_name"]+ type_oid = int(relation["type_oid"])+ type_contract = (+ relation["type_schema"],+ relation["type_name"],+ str(relation["typtype"]),+ int(relation["type_relation_oid"]),+ )+ relation_contract = (+ str(relation["relkind"]),+ str(relation["relpersistence"]),+ bool(relation["relispartition"]),+ bool(relation["relrowsecurity"]),+ bool(relation["relforcerowsecurity"]),+ int(relation["parent_count"]),+ int(relation["child_count"]),+ int(relation["policy_count"]),+ int(relation["user_trigger_count"]),+ int(relation["user_rule_count"]),+ )+ except (KeyError, TypeError, ValueError):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR) from None+ if (+ not isinstance(schema_name, str)+ or not schema_name+ or type_oid <= 0+ or type_contract+ != (schema_name, "alembic_version", "c", table_oid)+ or relation_contract+ != ("r", "p", False, False, False, 0, 0, 0, 0, 0)+ ):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)++ column_rows = await connection.fetch(+ """+ SELECT att.attnum,+ att.attname AS column_name,+ pg_catalog.format_type(+ att.atttypid,+ att.atttypmod+ ) AS data_type,+ att.attnotnull,+ att.attidentity,+ att.attgenerated,+ att.attisdropped,+ att.attinhcount,+ att.attislocal,+ att.atthasmissing,+ att.attmissingval::text AS missing_value,+ att.attcollation=type_record.typcollation+ AS collation_is_default,+ pg_get_expr(def.adbin, def.adrelid) AS column_default+ FROM pg_attribute AS att+ LEFT JOIN pg_type AS type_record+ ON type_record.oid=att.atttypid+ LEFT JOIN pg_attrdef AS def+ ON def.adrelid=att.attrelid+ AND def.adnum=att.attnum+ WHERE att.attrelid=$1::oid+ AND att.attnum > 0+ ORDER BY att.attnum+ """,+ table_oid,+ )+ try:+ columns = tuple(+ (+ int(row["attnum"]),+ str(row["column_name"]),+ str(row["data_type"]),+ bool(row["attnotnull"]),+ str(row["attidentity"]),+ str(row["attgenerated"]),+ bool(row["attisdropped"]),+ int(row["attinhcount"]),+ bool(row["attislocal"]),+ bool(row["atthasmissing"]),+ row["missing_value"],+ bool(row["collation_is_default"]),+ row["column_default"],+ )+ for row in column_rows+ )+ except (KeyError, TypeError, ValueError):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR) from None+ if columns != (+ (+ 1,+ "version_num",+ "character varying(32)",+ True,+ "",+ "",+ False,+ 0,+ True,+ False,+ None,+ True,+ None,+ ),+ ):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)++ primary_rows = await connection.fetch(+ """+ SELECT con.conname,+ con.contype,+ con.convalidated,+ con.condeferrable,+ con.condeferred,+ ARRAY(+ SELECT att.attname+ FROM unnest(con.conkey)+ WITH ORDINALITY AS key(attnum, position)+ JOIN pg_attribute AS att+ ON att.attrelid=con.conrelid+ AND att.attnum=key.attnum+ ORDER BY key.position+ ) AS columns+ FROM pg_constraint AS con+ WHERE con.conrelid=$1::oid+ ORDER BY con.conname+ """,+ table_oid,+ )+ try:+ primary_contract = tuple(+ (+ str(row["conname"]),+ str(row["contype"]),+ bool(row["convalidated"]),+ bool(row["condeferrable"]),+ bool(row["condeferred"]),+ tuple(str(column) for column in row["columns"]),+ )+ for row in primary_rows+ )+ except (KeyError, TypeError, ValueError):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR) from None+ if primary_contract != (+ (+ "alembic_version_pkc",+ "p",+ True,+ False,+ False,+ ("version_num",),+ ),+ ):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)++ version_index_rows = await connection.fetch(+ """+ SELECT index_rel.relname AS index_name,+ index_rel.relkind AS index_relkind,+ index_rel.relpersistence AS index_relpersistence,+ index_rel.relispartition AS index_is_partition,+ access_method.amname AS access_method,+ ind.indisunique,+ ind.indisprimary,+ ind.indisvalid,+ ind.indisready,+ ind.indislive,+ ind.indnkeyatts,+ ind.indnatts,+ con.conname AS constraint_name,+ ARRAY(+ SELECT att.attname+ FROM unnest(ind.indkey)+ WITH ORDINALITY AS key(attnum, position)+ LEFT JOIN pg_attribute AS att+ ON att.attrelid=ind.indrelid+ AND att.attnum=key.attnum+ ORDER BY key.position+ ) AS columns,+ ARRAY(+ SELECT option+ FROM unnest(ind.indoption)+ WITH ORDINALITY AS item(option, position)+ ORDER BY item.position+ ) AS column_options,+ ARRAY(+ SELECT opc.opcname+ FROM unnest(ind.indclass)+ WITH ORDINALITY AS item(opclass, position)+ JOIN pg_opclass AS opc ON opc.oid=item.opclass+ ORDER BY item.position+ ) AS operator_classes,+ ARRAY(+ SELECT opc_nsp.nspname+ FROM unnest(ind.indclass)+ WITH ORDINALITY AS item(opclass, position)+ JOIN pg_opclass AS opc ON opc.oid=item.opclass+ JOIN pg_namespace AS opc_nsp+ ON opc_nsp.oid=opc.opcnamespace+ ORDER BY item.position+ ) AS operator_class_namespaces,+ ARRAY(+ SELECT item.collation=att.attcollation+ FROM unnest(ind.indcollation)+ WITH ORDINALITY AS item(collation, position)+ JOIN unnest(ind.indkey)+ WITH ORDINALITY AS key(attnum, position)+ ON key.position=item.position+ LEFT JOIN pg_attribute AS att+ ON att.attrelid=ind.indrelid+ AND att.attnum=key.attnum+ ORDER BY item.position+ ) AS column_collations_match,+ pg_get_expr(ind.indexprs, ind.indrelid) AS expressions,+ pg_get_expr(ind.indpred, ind.indrelid) AS predicate+ FROM pg_index AS ind+ JOIN pg_class AS index_rel ON index_rel.oid=ind.indexrelid+ JOIN pg_am AS access_method ON access_method.oid=index_rel.relam+ LEFT JOIN pg_constraint AS con+ ON con.conindid=ind.indexrelid+ WHERE ind.indrelid=$1::oid+ ORDER BY index_rel.relname+ """,+ table_oid,+ )+ try:+ version_indexes = tuple(+ (+ str(row["index_name"]),+ str(row["index_relkind"]),+ str(row["index_relpersistence"]),+ bool(row["index_is_partition"]),+ str(row["access_method"]),+ bool(row["indisunique"]),+ bool(row["indisprimary"]),+ bool(row["indisvalid"]),+ bool(row["indisready"]),+ bool(row["indislive"]),+ int(row["indnkeyatts"]),+ int(row["indnatts"]),+ row["constraint_name"],+ tuple(str(column) for column in row["columns"]),+ tuple(int(option) for option in row["column_options"]),+ tuple(+ str(opclass) for opclass in row["operator_classes"]+ ),+ tuple(+ str(namespace)+ for namespace in row["operator_class_namespaces"]+ ),+ tuple(+ bool(value)+ for value in row["column_collations_match"]+ ),+ row["expressions"],+ row["predicate"],+ )+ for row in version_index_rows+ )+ except (KeyError, TypeError, ValueError):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR) from None+ if version_indexes != (+ (+ "alembic_version_pkc",+ "i",+ "p",+ False,+ "btree",+ True,+ True,+ True,+ True,+ True,+ 1,+ 1,+ "alembic_version_pkc",+ ("version_num",),+ (0,),+ ("text_ops",),+ ("pg_catalog",),+ (True,),+ None,+ None,+ ),+ ):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)++ quoted_schema = '"' + schema_name.replace('"', '""') + '"'+ revision_rows = await connection.fetch(+ f'SELECT version_num FROM {quoted_schema}."alembic_version"' # noqa: S608+ )+ try:+ values = tuple(row["version_num"] for row in revision_rows)+ except (KeyError, TypeError):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR) from None+ return _classify_postgres_revision(values)++ @staticmethod+ async def _validate_managed_schema(connection: Any) -> None:+ table_rows = await connection.fetch(+ """+ SELECT rel.oid::bigint AS table_oid,+ rel.relname AS table_name,+ nsp.nspname AS table_schema,+ relation_type.oid::bigint AS type_oid,+ type_nsp.nspname AS type_schema,+ relation_type.typname AS type_name,+ relation_type.typtype,+ relation_type.typrelid::bigint AS type_relation_oid,+ rel.relkind,+ rel.relpersistence,+ rel.relispartition,+ rel.relrowsecurity,+ rel.relforcerowsecurity,+ (+ SELECT count(*)+ FROM pg_inherits AS inherited+ WHERE inherited.inhrelid=rel.oid+ ) AS parent_count,+ (+ SELECT count(*)+ FROM pg_inherits AS inherited+ WHERE inherited.inhparent=rel.oid+ ) AS child_count,+ (+ SELECT count(*)+ FROM pg_policy AS policy+ WHERE policy.polrelid=rel.oid+ ) AS policy_count,+ (+ SELECT count(*)+ FROM pg_trigger AS trigger_record+ WHERE trigger_record.tgrelid=rel.oid+ AND NOT trigger_record.tgisinternal+ ) AS user_trigger_count,+ (+ SELECT count(*)+ FROM pg_rewrite AS rewrite+ WHERE rewrite.ev_class=rel.oid+ ) AS user_rule_count+ FROM pg_class AS rel+ JOIN pg_namespace AS nsp ON nsp.oid=rel.relnamespace+ JOIN pg_type AS relation_type ON relation_type.oid=rel.reltype+ JOIN pg_namespace AS type_nsp+ ON type_nsp.oid=relation_type.typnamespace+ WHERE nsp.nspname=current_schema()+ AND rel.relname=ANY($1::text[])+ ORDER BY rel.relname+ """,+ sorted(_POSTGRES_MANAGED_TABLES),+ )+ try:+ table_contract = {+ str(row["table_name"]): (+ int(row["table_oid"]),+ str(row["relkind"]),+ str(row["relpersistence"]),+ bool(row["relispartition"]),+ bool(row["relrowsecurity"]),+ bool(row["relforcerowsecurity"]),+ int(row["parent_count"]),+ int(row["child_count"]),+ int(row["policy_count"]),+ int(row["user_trigger_count"]),+ int(row["user_rule_count"]),+ str(row["table_schema"]),+ int(row["type_oid"]),+ str(row["type_schema"]),+ str(row["type_name"]),+ str(row["typtype"]),+ int(row["type_relation_oid"]),+ )+ for row in table_rows+ }+ except (KeyError, TypeError, ValueError):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR) from None+ if set(table_contract) != _POSTGRES_MANAGED_TABLES:+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)+ for table, metadata in table_contract.items():+ expected = (+ ("r", "p", False)+ if table == "websocket_tickets"+ else (+ "r",+ "p",+ False,+ False,+ False,+ 0,+ 0,+ 0,+ 0,+ 0,+ )+ )+ actual = (+ metadata[1:4]+ if table == "websocket_tickets"+ else metadata[1:11]+ )+ (+ table_schema,+ type_oid,+ type_schema,+ type_name,+ type_kind,+ type_relation_oid,+ ) = metadata[11:]+ if (+ actual != expected+ or not table_schema+ or type_oid <= 0+ or type_schema != table_schema+ or type_name != table+ or type_kind != "c"+ or type_relation_oid != metadata[0]+ ):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)++ non_ticket_tables = sorted(+ _POSTGRES_MANAGED_TABLES - {"websocket_tickets"}+ )+ legacy_index_rows = await connection.fetch(+ """+ SELECT table_rel.relname AS table_name,+ index_rel.relname AS index_name+ FROM pg_index AS ind+ JOIN pg_class AS table_rel ON table_rel.oid=ind.indrelid+ JOIN pg_namespace AS table_nsp+ ON table_nsp.oid=table_rel.relnamespace+ JOIN pg_class AS index_rel ON index_rel.oid=ind.indexrelid+ WHERE table_nsp.nspname=current_schema()+ AND table_rel.relname=ANY($1::text[])+ AND left(index_rel.relname, 7)='idx_pg_'+ ORDER BY table_rel.relname, index_rel.relname+ """,+ sorted(_POSTGRES_MANAGED_TABLES),+ )+ if legacy_index_rows:+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)++ index_rows = await connection.fetch(+ """+ SELECT table_rel.relname AS table_name,+ index_rel.relname AS index_name,+ index_rel.relkind AS index_relkind,+ index_rel.relpersistence AS index_relpersistence,+ index_rel.relispartition AS index_is_partition,+ access_method.amname AS access_method,+ ind.indisunique,+ ind.indisprimary,+ ind.indisvalid,+ ind.indisready,+ ind.indislive,+ ind.indnkeyatts,+ ind.indnatts,+ ARRAY(+ SELECT attribute.attname+ FROM unnest(ind.indkey)+ WITH ORDINALITY AS key(attnum, position)+ LEFT JOIN pg_attribute AS attribute+ ON attribute.attrelid=ind.indrelid+ AND attribute.attnum=key.attnum+ ORDER BY key.position+ ) AS index_columns,+ ARRAY(+ SELECT CASE+ WHEN key.attnum=0 THEN NULL+ ELSE att.attname+ END+ FROM unnest(ind.indkey)+ WITH ORDINALITY AS key(attnum, position)+ LEFT JOIN pg_attribute AS att+ ON att.attrelid=ind.indrelid+ AND att.attnum=key.attnum+ ORDER BY key.position+ ) AS columns,+ ARRAY(+ SELECT option+ FROM unnest(ind.indoption)+ WITH ORDINALITY AS item(option, position)+ ORDER BY item.position+ ) AS column_options,+ ARRAY(+ SELECT opc.opcname+ FROM unnest(ind.indclass)+ WITH ORDINALITY AS item(opclass, position)+ JOIN pg_opclass AS opc ON opc.oid=item.opclass+ ORDER BY item.position+ ) AS operator_classes,+ ARRAY(+ SELECT opc_nsp.nspname+ FROM unnest(ind.indclass)+ WITH ORDINALITY AS item(opclass, position)+ JOIN pg_opclass AS opc ON opc.oid=item.opclass+ JOIN pg_namespace AS opc_nsp+ ON opc_nsp.oid=opc.opcnamespace+ ORDER BY item.position+ ) AS operator_class_namespaces,+ ARRAY(+ SELECT item.collation=att.attcollation+ FROM unnest(ind.indcollation)+ WITH ORDINALITY AS item(collation, position)+ JOIN unnest(ind.indkey)+ WITH ORDINALITY AS key(attnum, position)+ ON key.position=item.position+ LEFT JOIN pg_attribute AS att+ ON att.attrelid=ind.indrelid+ AND att.attnum=key.attnum+ ORDER BY item.position+ ) AS column_collations_match,+ pg_get_expr(ind.indexprs, ind.indrelid) AS expressions,+ pg_get_expr(ind.indpred, ind.indrelid) AS predicate+ FROM pg_index AS ind+ JOIN pg_class AS table_rel ON table_rel.oid=ind.indrelid+ JOIN pg_namespace AS table_nsp+ ON table_nsp.oid=table_rel.relnamespace+ JOIN pg_class AS index_rel ON index_rel.oid=ind.indexrelid+ JOIN pg_am AS access_method+ ON access_method.oid=index_rel.relam+ WHERE table_nsp.nspname=current_schema()+ AND table_rel.relname=ANY($1::text[])+ AND NOT EXISTS (+ SELECT 1+ FROM pg_constraint AS con+ WHERE con.conindid=ind.indexrelid+ )+ ORDER BY table_rel.relname, index_rel.relname+ """,+ non_ticket_tables,+ )+ try:+ index_contract = {+ (str(row["table_name"]), str(row["index_name"])): (+ tuple(str(column) for column in row["columns"]),+ bool(row["indisunique"]),+ row["predicate"],+ str(row["index_relkind"]),+ str(row["index_relpersistence"]),+ bool(row["index_is_partition"]),+ str(row["access_method"]),+ bool(row["indisprimary"]),+ bool(row["indisvalid"]),+ bool(row["indisready"]),+ bool(row["indislive"]),+ int(row["indnkeyatts"]),+ int(row["indnatts"]),+ tuple(int(option) for option in row["column_options"]),+ tuple(+ str(opclass) for opclass in row["operator_classes"]+ ),+ tuple(+ str(namespace)+ for namespace in row["operator_class_namespaces"]+ ),+ tuple(+ bool(value)+ for value in row["column_collations_match"]+ ),+ row["expressions"],+ )+ for row in index_rows+ }+ except (KeyError, TypeError, ValueError):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR) from None+ expected_indexes = {+ (table, name): columns+ for table, name, columns in _POSTGRES_MANAGED_INDEXES+ }+ if set(index_contract) != set(expected_indexes):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)+ for key, columns in expected_indexes.items():+ actual = index_contract[key]+ if actual != (+ columns,+ False,+ None,+ "i",+ "p",+ False,+ "btree",+ False,+ True,+ True,+ True,+ len(columns),+ len(columns),+ (0,) * len(columns),+ tuple(+ _postgres_index_opclass(key[0], column)+ for column in columns+ ),+ ("pg_catalog",) * len(columns),+ (True,) * len(columns),+ None,+ ):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)++ primary_rows = await connection.fetch(+ """+ SELECT source.relname AS table_name,+ con.conname,+ con.contype,+ con.convalidated,+ con.condeferrable,+ con.condeferred,+ con.conindid::bigint AS constraint_index_oid,+ ARRAY(+ SELECT att.attname+ FROM unnest(con.conkey)+ WITH ORDINALITY AS key(attnum, position)+ JOIN pg_attribute AS att+ ON att.attrelid=con.conrelid+ AND att.attnum=key.attnum+ ORDER BY key.position+ ) AS local_columns,+ index_rel.relkind AS index_relkind,+ index_rel.relpersistence AS index_relpersistence,+ index_rel.relispartition AS index_is_partition,+ ind.indisunique,+ ind.indisprimary,+ ind.indisvalid,+ ind.indisready,+ ind.indislive+ FROM pg_constraint AS con+ JOIN pg_class AS source ON source.oid=con.conrelid+ JOIN pg_namespace AS source_nsp+ ON source_nsp.oid=source.relnamespace+ JOIN pg_class AS index_rel ON index_rel.oid=con.conindid+ JOIN pg_index AS ind ON ind.indexrelid=con.conindid+ WHERE source_nsp.nspname=current_schema()+ AND source.relname=ANY($1::text[])+ AND con.contype='p'+ ORDER BY source.relname, con.conname+ """,+ non_ticket_tables,+ )+ try:+ primary_contract = {+ (str(row["table_name"]), str(row["conname"])): (+ str(row["contype"]),+ bool(row["convalidated"]),+ bool(row["condeferrable"]),+ bool(row["condeferred"]),+ tuple(str(value) for value in row["local_columns"]),+ int(row["constraint_index_oid"]),+ str(row["index_relkind"]),+ str(row["index_relpersistence"]),+ bool(row["index_is_partition"]),+ bool(row["indisunique"]),+ bool(row["indisprimary"]),+ bool(row["indisvalid"]),+ bool(row["indisready"]),+ bool(row["indislive"]),+ )+ for row in primary_rows+ }+ except (KeyError, TypeError, ValueError):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR) from None+ expected_primary_keys = {+ (table, name): columns+ for table, name, columns in _POSTGRES_MANAGED_PRIMARY_KEYS+ }+ if set(primary_contract) != set(expected_primary_keys):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)+ for key, columns in expected_primary_keys.items():+ actual = primary_contract[key]+ if actual != (+ "p",+ True,+ False,+ False,+ columns,+ actual[5],+ "i",+ "p",+ False,+ True,+ True,+ True,+ True,+ True,+ ) or actual[5] <= 0:+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)++ await PostgresDatabase._validate_managed_constraints(+ connection,+ non_ticket_tables,+ )+ await PostgresDatabase._validate_managed_serials(connection)++ @staticmethod+ async def _validate_managed_constraints(+ connection: Any,+ non_ticket_tables: list[str],+ ) -> None:+ rows = await connection.fetch(+ """+ SELECT source_nsp.nspname AS source_schema,+ source.relname AS table_name,+ con.conname,+ con.contype,+ con.convalidated,+ con.condeferrable,+ con.condeferred,+ con.conindid::bigint AS constraint_index_oid,+ pg_get_constraintdef(con.oid, true) AS definition,+ reference_nsp.nspname AS referenced_schema,+ reference.relname AS referenced_table,+ con.confupdtype,+ con.confdeltype,+ ARRAY(+ SELECT attribute.attname+ FROM unnest(con.conkey)+ WITH ORDINALITY AS key(attnum, position)+ JOIN pg_attribute AS attribute+ ON attribute.attrelid=con.conrelid+ AND attribute.attnum=key.attnum+ ORDER BY key.position+ ) AS local_columns,+ ARRAY(+ SELECT attribute.attname+ FROM unnest(con.confkey)+ WITH ORDINALITY AS key(attnum, position)+ JOIN pg_attribute AS attribute+ ON attribute.attrelid=con.confrelid+ AND attribute.attnum=key.attnum+ ORDER BY key.position+ ) AS remote_columns,+ index_nsp.nspname AS index_schema,+ index_rel.relname AS index_name,+ index_rel.relkind AS index_relkind,+ index_rel.relpersistence AS index_relpersistence,+ index_rel.relispartition AS index_is_partition,+ access_method.amname AS access_method,+ ind.indisunique,+ ind.indisprimary,+ ind.indisvalid,+ ind.indisready,+ ind.indislive,+ ind.indnkeyatts,+ ind.indnatts,+ ARRAY(+ SELECT attribute.attname+ FROM unnest(ind.indkey)+ WITH ORDINALITY AS key(attnum, position)+ LEFT JOIN pg_attribute AS attribute+ ON attribute.attrelid=ind.indrelid+ AND attribute.attnum=key.attnum+ ORDER BY key.position+ ) AS index_columns,+ ARRAY(+ SELECT option+ FROM unnest(ind.indoption)+ WITH ORDINALITY AS item(option, position)+ ORDER BY item.position+ ) AS column_options,+ ARRAY(+ SELECT opc.opcname+ FROM unnest(ind.indclass)+ WITH ORDINALITY AS item(opclass, position)+ JOIN pg_opclass AS opc ON opc.oid=item.opclass+ ORDER BY item.position+ ) AS operator_classes,+ ARRAY(+ SELECT opc_nsp.nspname+ FROM unnest(ind.indclass)+ WITH ORDINALITY AS item(opclass, position)+ JOIN pg_opclass AS opc ON opc.oid=item.opclass+ JOIN pg_namespace AS opc_nsp+ ON opc_nsp.oid=opc.opcnamespace+ ORDER BY item.position+ ) AS operator_class_namespaces,+ ARRAY(+ SELECT item.collation=attribute.attcollation+ FROM unnest(ind.indcollation)+ WITH ORDINALITY AS item(collation, position)+ JOIN unnest(ind.indkey)+ WITH ORDINALITY AS key(attnum, position)+ ON key.position=item.position+ LEFT JOIN pg_attribute AS attribute+ ON attribute.attrelid=ind.indrelid+ AND attribute.attnum=key.attnum+ ORDER BY item.position+ ) AS column_collations_match,+ pg_get_expr(ind.indexprs, ind.indrelid) AS expressions,+ pg_get_expr(ind.indpred, ind.indrelid) AS predicate+ FROM pg_constraint AS con+ JOIN pg_class AS source ON source.oid=con.conrelid+ JOIN pg_namespace AS source_nsp+ ON source_nsp.oid=source.relnamespace+ LEFT JOIN pg_class AS reference+ ON reference.oid=con.confrelid+ LEFT JOIN pg_namespace AS reference_nsp+ ON reference_nsp.oid=reference.relnamespace+ LEFT JOIN pg_class AS index_rel+ ON index_rel.oid=con.conindid+ LEFT JOIN pg_namespace AS index_nsp+ ON index_nsp.oid=index_rel.relnamespace+ LEFT JOIN pg_index AS ind+ ON ind.indexrelid=con.conindid+ LEFT JOIN pg_am AS access_method+ ON access_method.oid=index_rel.relam+ WHERE source_nsp.nspname=current_schema()+ AND source.relname=ANY($1::text[])+ AND con.contype <> 'p'+ ORDER BY source.relname, con.conname+ """,+ non_ticket_tables,+ )+ try:+ actual = {+ (str(row["table_name"]), str(row["conname"])): row+ for row in rows+ }+ except (KeyError, TypeError, ValueError):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR) from None++ expected_foreign = {+ (table, name): (+ local,+ parent,+ remote,+ on_delete,+ delete_code,+ )+ for (+ table,+ name,+ local,+ parent,+ remote,+ on_delete,+ delete_code,+ ) in _POSTGRES_MANAGED_FOREIGN_KEYS+ }+ expected_unique = {+ (table, name): columns+ for table, name, columns in _POSTGRES_MANAGED_UNIQUES+ }+ expected_checks = {+ (+ table,+ _postgres_finite_check_name(table, column),+ ): (+ f"CHECK ({column} IS NULL OR isfinite({column}))"+ if nullable+ else f"CHECK (isfinite({column}))"+ )+ for table, column, nullable in (+ _POSTGRES_MANAGED_FINITE_CHECKS+ )+ }+ expected_checks[+ (+ "rate_limit_events",+ "ck_rate_limit_events_blocked_bool",+ )+ ] = "CHECK (blocked = ANY (ARRAY[0, 1]))"+ expected_keys = (+ set(expected_foreign)+ | set(expected_unique)+ | set(expected_checks)+ )+ if len(rows) != len(actual) or set(actual) != expected_keys:+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)++ for key, contract in actual.items():+ try:+ source_schema = str(contract["source_schema"])+ common = (+ bool(contract["convalidated"]),+ bool(contract["condeferrable"]),+ bool(contract["condeferred"]),+ )+ definition = _postgres_constraint_definition(+ contract["definition"]+ )+ local_columns = tuple(+ str(column) for column in contract["local_columns"]+ )+ remote_columns = tuple(+ str(column) for column in contract["remote_columns"]+ )+ except (KeyError, TypeError, ValueError):+ raise RuntimeError(+ _POSTGRES_MANAGED_SCHEMA_ERROR+ ) from None+ if not source_schema or common != (True, False, False):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)++ if key in expected_checks:+ if (+ str(contract["contype"]) != "c"+ or definition != expected_checks[key]+ or local_columns == ()+ or remote_columns+ or int(contract["constraint_index_oid"]) != 0+ ):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)+ continue++ if key in expected_foreign:+ (+ expected_local,+ parent,+ expected_remote,+ on_delete,+ delete_code,+ ) = expected_foreign[key]+ expected_definition = (+ f"FOREIGN KEY ({', '.join(expected_local)}) "+ f"REFERENCES {parent}({', '.join(expected_remote)}) "+ f"ON DELETE {on_delete}"+ )+ if (+ str(contract["contype"]) != "f"+ or definition != expected_definition+ or local_columns != expected_local+ or remote_columns != expected_remote+ or str(contract["referenced_schema"])+ != source_schema+ or str(contract["referenced_table"]) != parent+ or str(contract["confupdtype"]) != "a"+ or str(contract["confdeltype"]) != delete_code+ ):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)+ try:+ foreign_index_contract = (+ int(contract["constraint_index_oid"]),+ str(contract["index_schema"]),+ str(contract["index_name"]),+ str(contract["index_relkind"]),+ str(contract["index_relpersistence"]),+ bool(contract["index_is_partition"]),+ str(contract["access_method"]),+ bool(contract["indisunique"]),+ bool(contract["indisprimary"]),+ bool(contract["indisvalid"]),+ bool(contract["indisready"]),+ bool(contract["indislive"]),+ int(contract["indnkeyatts"]),+ int(contract["indnatts"]),+ tuple(+ str(column)+ for column in contract["index_columns"]+ ),+ tuple(+ int(option)+ for option in contract["column_options"]+ ),+ tuple(+ str(opclass)+ for opclass in contract["operator_classes"]+ ),+ tuple(+ str(namespace)+ for namespace in contract[+ "operator_class_namespaces"+ ]+ ),+ tuple(+ bool(value)+ for value in contract[+ "column_collations_match"+ ]+ ),+ contract["expressions"],+ contract["predicate"],+ )+ except (KeyError, TypeError, ValueError):+ raise RuntimeError(+ _POSTGRES_MANAGED_SCHEMA_ERROR+ ) from None+ if foreign_index_contract != (+ foreign_index_contract[0],+ source_schema,+ f"{parent}_pkey",+ "i",+ "p",+ False,+ "btree",+ True,+ True,+ True,+ True,+ True,+ len(expected_remote),+ len(expected_remote),+ expected_remote,+ (0,) * len(expected_remote),+ ("text_ops",) * len(expected_remote),+ ("pg_catalog",) * len(expected_remote),+ (True,) * len(expected_remote),+ None,+ None,+ ) or foreign_index_contract[0] <= 0:+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)+ continue++ columns = expected_unique[key]+ expected_definition = f"UNIQUE ({', '.join(columns)})"+ try:+ unique_contract = (+ str(contract["contype"]),+ definition,+ local_columns,+ contract["referenced_schema"],+ contract["referenced_table"],+ remote_columns,+ str(contract["index_schema"]),+ str(contract["index_name"]),+ str(contract["index_relkind"]),+ str(contract["index_relpersistence"]),+ bool(contract["index_is_partition"]),+ str(contract["access_method"]),+ bool(contract["indisunique"]),+ bool(contract["indisprimary"]),+ bool(contract["indisvalid"]),+ bool(contract["indisready"]),+ bool(contract["indislive"]),+ int(contract["indnkeyatts"]),+ int(contract["indnatts"]),+ tuple(+ str(column)+ for column in contract["index_columns"]+ ),+ tuple(+ int(option)+ for option in contract["column_options"]+ ),+ tuple(+ str(opclass)+ for opclass in contract["operator_classes"]+ ),+ tuple(+ str(namespace)+ for namespace in (+ contract["operator_class_namespaces"]+ )+ ),+ tuple(+ bool(value)+ for value in contract[+ "column_collations_match"+ ]+ ),+ contract["expressions"],+ contract["predicate"],+ )+ except (KeyError, TypeError, ValueError):+ raise RuntimeError(+ _POSTGRES_MANAGED_SCHEMA_ERROR+ ) from None+ if unique_contract != (+ "u",+ expected_definition,+ columns,+ None,+ None,+ (),+ source_schema,+ key[1],+ "i",+ "p",+ False,+ "btree",+ True,+ False,+ True,+ True,+ True,+ len(columns),+ len(columns),+ columns,+ (0,) * len(columns),+ ("text_ops",) * len(columns),+ ("pg_catalog",) * len(columns),+ (True,) * len(columns),+ None,+ None,+ ) or int(contract["constraint_index_oid"]) <= 0:+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)++ @staticmethod+ async def _validate_managed_serials(connection: Any) -> None:+ rows = await connection.fetch(+ """+ SELECT sequence_nsp.nspname AS sequence_schema,+ sequence_rel.relname AS sequence_name,+ sequence_rel.relkind,+ sequence_rel.relpersistence,+ format_type(sequence_def.seqtypid, NULL) AS data_type,+ sequence_def.seqstart,+ sequence_def.seqincrement,+ sequence_def.seqmax,+ sequence_def.seqmin,+ sequence_def.seqcache,+ sequence_def.seqcycle,+ owner_nsp.nspname AS owner_schema,+ owner_rel.relname AS owner_table,+ owner_att.attname AS owner_column,+ dependency.deptype,+ format_type(+ owner_att.atttypid,+ owner_att.atttypmod+ ) AS owner_data_type,+ owner_att.attnotnull,+ owner_att.attidentity,+ owner_att.attgenerated,+ owner_att.attcollation=owner_type.typcollation+ AS collation_is_default,+ pg_get_expr(+ owner_default.adbin,+ owner_default.adrelid+ ) AS column_default+ FROM pg_class AS sequence_rel+ JOIN pg_namespace AS sequence_nsp+ ON sequence_nsp.oid=sequence_rel.relnamespace+ JOIN pg_sequence AS sequence_def+ ON sequence_def.seqrelid=sequence_rel.oid+ LEFT JOIN pg_depend AS dependency+ ON dependency.classid='pg_class'::regclass+ AND dependency.objid=sequence_rel.oid+ AND dependency.objsubid=0+ AND dependency.refclassid='pg_class'::regclass+ AND dependency.deptype IN ('a', 'i')+ LEFT JOIN pg_class AS owner_rel+ ON owner_rel.oid=dependency.refobjid+ LEFT JOIN pg_namespace AS owner_nsp+ ON owner_nsp.oid=owner_rel.relnamespace+ LEFT JOIN pg_attribute AS owner_att+ ON owner_att.attrelid=dependency.refobjid+ AND owner_att.attnum=dependency.refobjsubid+ LEFT JOIN pg_type AS owner_type+ ON owner_type.oid=owner_att.atttypid+ LEFT JOIN pg_attrdef AS owner_default+ ON owner_default.adrelid=owner_att.attrelid+ AND owner_default.adnum=owner_att.attnum+ WHERE sequence_nsp.nspname=current_schema()+ AND sequence_rel.relname=ANY($1::text[])+ ORDER BY sequence_rel.relname+ """,+ ["audit_log_id_seq", "rate_limit_events_id_seq"],+ )+ expected = {+ "audit_log_id_seq": (+ "audit_log",+ "id",+ "nextval('audit_log_id_seq'::regclass)",+ ),+ "rate_limit_events_id_seq": (+ "rate_limit_events",+ "id",+ "nextval('rate_limit_events_id_seq'::regclass)",+ ),+ }+ if len(rows) != len(expected):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)+ seen: set[str] = set()+ for row in rows:+ try:+ name = str(row["sequence_name"])+ owner = expected.get(name)+ contract = (+ str(row["relkind"]),+ str(row["relpersistence"]),+ str(row["data_type"]),+ int(row["seqstart"]),+ int(row["seqincrement"]),+ int(row["seqmax"]),+ int(row["seqmin"]),+ int(row["seqcache"]),+ bool(row["seqcycle"]),+ str(row["owner_schema"]),+ str(row["owner_table"]),+ str(row["owner_column"]),+ str(row["deptype"]),+ str(row["owner_data_type"]),+ bool(row["attnotnull"]),+ str(row["attidentity"]),+ str(row["attgenerated"]),+ bool(row["collation_is_default"]),+ row["column_default"],+ )+ except (KeyError, TypeError, ValueError):+ raise RuntimeError(+ _POSTGRES_MANAGED_SCHEMA_ERROR+ ) from None+ if owner is None or name in seen:+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)+ if contract != (+ "S",+ "p",+ "integer",+ 1,+ 1,+ 2147483647,+ 1,+ 1,+ False,+ str(row["sequence_schema"]),+ owner[0],+ owner[1],+ "a",+ "integer",+ True,+ "",+ "",+ True,+ owner[2],+ ):+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)+ seen.add(name)+async def _init_schema(self) -> None:async with self._pool.acquire() as conn:async with conn.transaction():- ticket_table_exists = bool(- await conn.fetchval(- """- SELECT EXISTS(- SELECT 1- FROM pg_class AS rel- JOIN pg_namespace AS nsp- ON nsp.oid=rel.relnamespace- WHERE nsp.nspname=current_schema()- AND rel.relname='websocket_tickets'+ try:+ revision = await self._managed_schema_revision(conn)+ except (+ _PostgresManagedSchemaError,+ _PostgresMigrationRequiredError,+ ):+ raise+ except RuntimeError as exc:+ if str(exc) == _POSTGRES_MANAGED_SCHEMA_ERROR:+ raise _PostgresManagedSchemaError(+ _POSTGRES_MANAGED_SCHEMA_ERROR+ ) from None+ raise RuntimeError(+ _POSTGRES_SCHEMA_VALIDATION_ERROR+ ) from None+ except Exception:+ raise RuntimeError(+ _POSTGRES_SCHEMA_VALIDATION_ERROR+ ) from None+ if revision is not None:+ try:+ await self._validate_managed_schema(conn)+ await self._validate_websocket_ticket_schema(conn)+ except _PostgresManagedSchemaError:+ raise+ except RuntimeError as exc:+ if str(exc) == _POSTGRES_MANAGED_SCHEMA_ERROR:+ raise _PostgresManagedSchemaError(+ _POSTGRES_MANAGED_SCHEMA_ERROR+ ) from None+ if str(exc) == (+ "Incompatible WebSocket ticket schema"+ ):+ raise+ raise RuntimeError(+ _POSTGRES_SCHEMA_VALIDATION_ERROR+ ) from None+ except Exception:+ raise RuntimeError(+ _POSTGRES_SCHEMA_VALIDATION_ERROR+ ) from None+ else:+ ticket_table_exists = bool(+ await conn.fetchval(+ """+ SELECT EXISTS(+ SELECT 1+ FROM pg_class AS rel+ JOIN pg_namespace AS nsp+ ON nsp.oid=rel.relnamespace+ WHERE nsp.nspname=current_schema()+ AND rel.relname='websocket_tickets'+ )+ """)- """)- )- if ticket_table_exists:+ if ticket_table_exists:+ await self._validate_websocket_ticket_schema(conn)+ await conn.execute(_PG_CREATE_TABLES)await self._validate_websocket_ticket_schema(conn)- await conn.execute(_PG_CREATE_TABLES)- await self._validate_websocket_ticket_schema(conn)logger.info("pg_schema_ready")@staticmethoddiff --git a/migrations/versions/0008_reconcile_schema_parity.py b/migrations/versions/0008_reconcile_schema_parity.pynew file mode 100644index 0000000..35171b8--- /dev/null+++ b/migrations/versions/0008_reconcile_schema_parity.py@@ -0,0 +1,4133 @@+"""Reconcile audited historical and runtime schema variants.++Revision ID: 0008+Revises: 0007+Create Date: 2026-07-31 00:00:00++Revision 0008 is deliberately forward-only. It accepts only the audited+revision-0007 catalog variants, validates all data needed by stronger+constraints before changing the catalog, and converges them on the repaired+Alembic contract. Unknown or unsafe catalogs fail without mutation.+"""+from __future__ import annotations++import re+from typing import Any++import sqlalchemy as sa+from alembic import op++revision: str = "0008"+down_revision: str | None = "0007"+branch_labels: str | None = None+depends_on: str | None = None++_CATALOG_ERROR = "Incompatible catalog for migration 0008"+_DATA_ERROR = "Unsafe data for migration 0008"+_DOWNGRADE_ERROR = "Migration 0008 is forward-only"+_DIALECT_ERROR = "Unsupported migration dialect"+_TEMP_PREFIX = "__ares_m0008_"++_Column = tuple[str, str, bool, str | None, int]+_ForeignKey = tuple[str, str, str, str, str]+++def _column(+ name: str,+ kind: str,+ nullable: bool,+ default: str | None = None,+ primary_key: int = 0,+) -> _Column:+ return name, kind, nullable, default, primary_key+++_SQLITE_COLUMNS: dict[str, tuple[_Column, ...]] = {+ "schema_version": (+ _column("version", "INTEGER", False, primary_key=1),+ _column("applied_at", "TEXT", False, "datetime('now')"),+ ),+ "campaigns": (+ _column("id", "TEXT", False, primary_key=1),+ _column("name", "TEXT", False),+ _column("client", "TEXT", False, "Internal"),+ _column("operator", "TEXT", False, "unknown"),+ _column("noise_profile", "TEXT", False, "stealth"),+ _column("status", "TEXT", False, "created"),+ _column("scope_json", "TEXT", False, "[]"),+ _column("targets_json", "TEXT", False, "[]"),+ _column("notes", "TEXT", True, ""),+ _column("created_at", "TEXT", False, "datetime('now')"),+ _column("updated_at", "TEXT", False, "datetime('now')"),+ ),+ "module_runs": (+ _column("id", "TEXT", False, primary_key=1),+ _column("campaign_id", "TEXT", False),+ _column("module_id", "TEXT", False),+ _column("outcome", "TEXT", False),+ _column("success", "INTEGER", False, "0"),+ _column("duration_ms", "FLOAT", False, "0.0"),+ _column("completed_at", "TEXT", False, "datetime('now')"),+ ),+ "findings": (+ _column("id", "TEXT", False, primary_key=1),+ _column("campaign_id", "TEXT", False),+ _column("module_id", "TEXT", False),+ _column("title", "TEXT", False),+ _column("description", "TEXT", False),+ _column("severity", "TEXT", False),+ _column("confidence", "FLOAT", False, "1.0"),+ _column("mitre_technique", "TEXT", True),+ _column("mitre_tactic", "TEXT", True),+ _column("cvss_score", "FLOAT", False, "0.0"),+ _column("cvss_vector", "TEXT", False, ""),+ _column("evidence_json", "TEXT", False, "{}"),+ _column("remediation", "TEXT", True, ""),+ _column("host", "TEXT", True),+ _column("validated", "INTEGER", False, "0"),+ _column("false_positive", "INTEGER", False, "0"),+ _column("discovered_at", "TEXT", False, "datetime('now')"),+ _column("trace_id", "TEXT", False, ""),+ ),+ "hosts": (+ _column("id", "TEXT", False, primary_key=1),+ _column("campaign_id", "TEXT", False),+ _column("ip_address", "TEXT", False),+ _column("hostname", "TEXT", True),+ _column("fqdn", "TEXT", True),+ _column("os", "TEXT", True),+ _column("os_version", "TEXT", True),+ _column("domain", "TEXT", True),+ _column("is_dc", "INTEGER", False, "0"),+ _column("open_ports_json", "TEXT", False, "[]"),+ _column("tags_json", "TEXT", False, "[]"),+ _column("first_seen", "TEXT", False, "datetime('now')"),+ _column("last_seen", "TEXT", False, "datetime('now')"),+ ),+ "credentials": (+ _column("id", "TEXT", False, primary_key=1),+ _column("campaign_id", "TEXT", False),+ _column("host_id", "TEXT", True),+ _column("username", "TEXT", False),+ _column("secret_enc", "TEXT", True),+ _column("cred_type", "TEXT", False),+ _column("domain", "TEXT", True),+ _column("source_module", "TEXT", True),+ _column("notes", "TEXT", True, ""),+ _column("cracked", "INTEGER", False, "0"),+ _column("cracked_value_enc", "TEXT", True),+ _column("captured_at", "TEXT", False, "datetime('now')"),+ ),+ "loot": (+ _column("id", "TEXT", False, primary_key=1),+ _column("campaign_id", "TEXT", False),+ _column("host_id", "TEXT", True),+ _column("loot_type", "TEXT", False),+ _column("name", "TEXT", False),+ _column("description", "TEXT", True, ""),+ _column("content_enc", "TEXT", True),+ _column("size_bytes", "INTEGER", True, "0"),+ _column("path_on_target", "TEXT", True),+ _column("source_module", "TEXT", True),+ _column("tags_json", "TEXT", False, "[]"),+ _column("captured_at", "TEXT", False, "datetime('now')"),+ ),+ "audit_log": (+ _column("id", "INTEGER", False, primary_key=1),+ _column("campaign_id", "TEXT", True),+ _column("actor", "TEXT", False, "system"),+ _column("action", "TEXT", False),+ _column("detail", "TEXT", True, ""),+ _column("module_id", "TEXT", True),+ _column("timestamp", "TEXT", False, "datetime('now')"),+ ),+ "users": (+ _column("id", "TEXT", False, primary_key=1),+ _column("username", "TEXT", False),+ _column("hashed_password", "TEXT", False),+ _column("role", "TEXT", False, "reporter"),+ _column("is_active", "INTEGER", False, "1"),+ _column("created_by", "TEXT", False, "system"),+ _column("created_at", "TEXT", False, "datetime('now')"),+ _column("last_login", "TEXT", True),+ ),+ "api_keys": (+ _column("id", "TEXT", False, primary_key=1),+ _column("user_id", "TEXT", False),+ _column("name", "TEXT", False),+ _column("key_hash", "TEXT", False),+ _column("key_prefix", "TEXT", False),+ _column("scopes", "TEXT", False, "read"),+ _column("is_active", "INTEGER", False, "1"),+ _column("last_used", "TEXT", True),+ _column("expires_at", "TEXT", True),+ _column("created_at", "TEXT", False, "datetime('now')"),+ ),+ "refresh_tokens": (+ _column("id", "TEXT", False, primary_key=1),+ _column("user_id", "TEXT", False),+ _column("is_revoked", "INTEGER", False, "0"),+ _column("expires_at", "TEXT", False),+ _column("created_at", "TEXT", False, "datetime('now')"),+ _column("used_at", "TEXT", True),+ ),+ "rate_limit_events": (+ _column("id", "INTEGER", False, primary_key=1),+ _column("ip_address", "TEXT", False),+ _column("bucket", "TEXT", False),+ _column("username", "TEXT", True),+ _column("blocked", "INTEGER", False, "0"),+ _column("timestamp", "TEXT", False, "datetime('now')"),+ ),+ "revoked_access_tokens": (+ _column("jti", "TEXT", False, primary_key=1),+ _column("user_id", "TEXT", False),+ _column("revoked_at", "TEXT", False, "datetime('now')"),+ _column("expires_at", "TEXT", False),+ ),+ "websocket_tickets": (+ _column("ticket_hash", "TEXT", False, primary_key=1),+ _column("campaign_id", "TEXT", False),+ _column("user_id", "TEXT", False),+ _column("credential_kind", "TEXT", False),+ _column("bearer_subject", "TEXT", True),+ _column("bearer_jti", "TEXT", True),+ _column("bearer_expires_at", "TEXT", True),+ _column("api_key_id", "TEXT", True),+ _column("required_scope", "TEXT", True),+ _column("created_at", "TEXT", False),+ _column("expires_at", "TEXT", False),+ _column("consumed_at", "TEXT", True),+ ),+}++_SQLITE_FOREIGN_KEYS: dict[str, frozenset[_ForeignKey]] = {+ "module_runs": frozenset(+ {("campaign_id", "campaigns", "id", "NO ACTION", "CASCADE")}+ ),+ "findings": frozenset(+ {("campaign_id", "campaigns", "id", "NO ACTION", "CASCADE")}+ ),+ "hosts": frozenset(+ {("campaign_id", "campaigns", "id", "NO ACTION", "CASCADE")}+ ),+ "credentials": frozenset(+ {+ ("campaign_id", "campaigns", "id", "NO ACTION", "CASCADE"),+ ("host_id", "hosts", "id", "NO ACTION", "SET NULL"),+ }+ ),+ "loot": frozenset(+ {+ ("campaign_id", "campaigns", "id", "NO ACTION", "CASCADE"),+ ("host_id", "hosts", "id", "NO ACTION", "SET NULL"),+ }+ ),+ "audit_log": frozenset(+ {("campaign_id", "campaigns", "id", "NO ACTION", "SET NULL")}+ ),+ "api_keys": frozenset(+ {("user_id", "users", "id", "NO ACTION", "CASCADE")}+ ),+ "refresh_tokens": frozenset(+ {("user_id", "users", "id", "NO ACTION", "CASCADE")}+ ),+ "websocket_tickets": frozenset(+ {+ ("campaign_id", "campaigns", "id", "NO ACTION", "CASCADE"),+ ("user_id", "users", "id", "NO ACTION", "CASCADE"),+ ("api_key_id", "api_keys", "id", "NO ACTION", "CASCADE"),+ }+ ),+}++_SQLITE_INDEXES: dict[str, dict[str, tuple[str, ...]]] = {+ "module_runs": {+ "idx_module_runs_campaign": ("campaign_id",),+ "idx_module_runs_completed": ("completed_at",),+ },+ "findings": {+ "idx_findings_campaign": ("campaign_id",),+ "idx_findings_severity": ("severity",),+ "idx_findings_fp": ("false_positive",),+ "idx_findings_mitre": ("mitre_technique",),+ "idx_findings_cvss": ("cvss_score",),+ },+ "hosts": {+ "idx_hosts_campaign": ("campaign_id",),+ "idx_hosts_ip": ("ip_address",),+ "idx_hosts_domain": ("domain",),+ },+ "credentials": {+ "idx_creds_campaign": ("campaign_id",),+ "idx_creds_username": ("username",),+ "idx_creds_type": ("cred_type",),+ },+ "loot": {+ "idx_loot_campaign": ("campaign_id",),+ "idx_loot_type": ("loot_type",),+ },+ "audit_log": {+ "idx_audit_campaign": ("campaign_id",),+ "idx_audit_actor": ("actor",),+ "idx_audit_action": ("action",),+ },+ "users": {+ "idx_users_username": ("username",),+ "idx_users_role": ("role",),+ },+ "api_keys": {+ "idx_apikeys_user": ("user_id",),+ "idx_apikeys_prefix": ("key_prefix",),+ },+ "refresh_tokens": {+ "idx_refresh_user": ("user_id",),+ "idx_refresh_exp": ("expires_at",),+ },+ "rate_limit_events": {+ "idx_rle_ip": ("ip_address",),+ "idx_rle_timestamp": ("timestamp",),+ "idx_rle_blocked": ("blocked",),+ },+ "revoked_access_tokens": {+ "idx_rat_expires": ("expires_at",),+ },+ "websocket_tickets": {+ "idx_ws_tickets_expires": ("expires_at",),+ "idx_ws_tickets_user": ("user_id",),+ "idx_ws_tickets_campaign": ("campaign_id",),+ "idx_ws_tickets_api_key": ("api_key_id",),+ },+}++_REBUILD_ORDER = (+ "schema_version",+ "campaigns",+ "users",+ "revoked_access_tokens",+ "hosts",+ "module_runs",+ "findings",+ "credentials",+ "loot",+ "audit_log",+ "api_keys",+ "refresh_tokens",+ "rate_limit_events",+ "websocket_tickets",+)+_DROP_ORDER = (+ "websocket_tickets",+ "credentials",+ "loot",+ "module_runs",+ "findings",+ "hosts",+ "refresh_tokens",+ "api_keys",+ "audit_log",+ "rate_limit_events",+ "revoked_access_tokens",+ "users",+ "campaigns",+ "schema_version",+)++_SQLITE_TIMESTAMPS: dict[str, tuple[str, ...]] = {+ "schema_version": ("applied_at",),+ "campaigns": ("created_at", "updated_at"),+ "module_runs": ("completed_at",),+ "findings": ("discovered_at",),+ "hosts": ("first_seen", "last_seen"),+ "credentials": ("captured_at",),+ "loot": ("captured_at",),+ "audit_log": ("timestamp",),+ "users": ("created_at", "last_login"),+ "api_keys": ("last_used", "expires_at", "created_at"),+ "refresh_tokens": ("expires_at", "created_at", "used_at"),+ "rate_limit_events": ("timestamp",),+ "revoked_access_tokens": ("revoked_at", "expires_at"),+ "websocket_tickets": (+ "bearer_expires_at",+ "created_at",+ "expires_at",+ "consumed_at",+ ),+}++_BOOLEAN_INTEGER_COLUMNS = (+ ("module_runs", "success"),+ ("findings", "validated"),+ ("findings", "false_positive"),+ ("hosts", "is_dc"),+ ("credentials", "cracked"),+ ("users", "is_active"),+ ("api_keys", "is_active"),+ ("refresh_tokens", "is_revoked"),+ ("rate_limit_events", "blocked"),+)++_SQLITE_TEXT_PRIMARY_KEYS = {+ "alembic_version": "version_num",+ "campaigns": "id",+ "module_runs": "id",+ "findings": "id",+ "hosts": "id",+ "credentials": "id",+ "loot": "id",+ "users": "id",+ "api_keys": "id",+ "refresh_tokens": "id",+ "revoked_access_tokens": "jti",+ "websocket_tickets": "ticket_hash",+}++_SQLITE_INTEGER_PRIMARY_KEYS = frozenset(+ {"schema_version", "audit_log", "rate_limit_events"}+)++_SQLITE_RESERVED_INDEX_OWNERS = {+ name: table+ for table, indexes in _SQLITE_INDEXES.items()+ for name in indexes+}+_SQLITE_RESERVED_INDEX_OWNERS["idx_findings_validated"] = "findings"+++def _normalize_default(value: object) -> str | None:+ if value is None:+ return None+ normalized = str(value).strip()+ while (+ len(normalized) >= 2+ and normalized[0] == "("+ and normalized[-1] == ")"+ ):+ normalized = normalized[1:-1].strip()+ normalized = re.sub(r"::(?:text|double precision|integer)$", "", normalized)+ if (+ len(normalized) >= 2+ and normalized[0] == "'"+ and normalized[-1] == "'"+ ):+ normalized = normalized[1:-1].replace("''", "'")+ return " ".join(normalized.split())+++def _sqlite_columns(bind: Any, table: str) -> tuple[_Column, ...]:+ rows = bind.exec_driver_sql(f'PRAGMA table_info("{table}")').fetchall()+ return tuple(+ (+ str(row[1]),+ str(row[2]).upper(),+ not bool(row[3]),+ _normalize_default(row[4]),+ int(row[5]),+ )+ for row in rows+ )+++def _sqlite_foreign_keys(bind: Any, table: str) -> tuple[_ForeignKey, ...]:+ rows = bind.exec_driver_sql(+ f'PRAGMA foreign_key_list("{table}")'+ ).fetchall()+ return tuple(+ sorted(+ (+ str(row[3]),+ str(row[2]),+ str(row[4]),+ str(row[5]).upper(),+ str(row[6]).upper(),+ )+ for row in rows+ )+ )+++def _quote_sqlite_identifier(value: str) -> str:+ return '"' + value.replace('"', '""') + '"'+++def _require_sqlite_primary_key_index(bind: Any, table: str) -> None:+ rows = bind.exec_driver_sql(+ f'PRAGMA index_list({_quote_sqlite_identifier(table)})'+ ).fetchall()+ primary_rows = [row for row in rows if str(row[3]) == "pk"]+ expected_column = _SQLITE_TEXT_PRIMARY_KEYS.get(table)+ if expected_column is None:+ if table not in _SQLITE_INTEGER_PRIMARY_KEYS or primary_rows:+ raise RuntimeError(_CATALOG_ERROR)+ return+ if (+ len(primary_rows) != 1+ or not bool(primary_rows[0][2])+ or bool(primary_rows[0][4])+ ):+ raise RuntimeError(_CATALOG_ERROR)+ opaque_name = str(primary_rows[0][1])+ schema_rows = bind.execute(+ sa.text(+ "SELECT type, tbl_name, sql FROM sqlite_schema "+ "WHERE name=:name"+ ),+ {"name": opaque_name},+ ).fetchall()+ if (+ len(schema_rows) != 1+ or str(schema_rows[0][0]) != "index"+ or str(schema_rows[0][1]) != table+ or schema_rows[0][2] is not None+ ):+ raise RuntimeError(_CATALOG_ERROR)+ details = bind.exec_driver_sql(+ f'PRAGMA index_xinfo({_quote_sqlite_identifier(opaque_name)})'+ ).fetchall()+ if len(details) != 2:+ raise RuntimeError(_CATALOG_ERROR)+ key_rows = [row for row in details if bool(row[5])]+ auxiliary_rows = [row for row in details if not bool(row[5])]+ if (+ len(key_rows) != 1+ or int(key_rows[0][0]) != 0+ or int(key_rows[0][1]) < 0+ or str(key_rows[0][2]) != expected_column+ or bool(key_rows[0][3])+ or str(key_rows[0][4]).upper() != "BINARY"+ or len(auxiliary_rows) != 1+ or int(auxiliary_rows[0][0]) != 1+ or int(auxiliary_rows[0][1]) != -1+ or auxiliary_rows[0][2] is not None+ or bool(auxiliary_rows[0][3])+ or str(auxiliary_rows[0][4]).upper() != "BINARY"+ ):+ raise RuntimeError(_CATALOG_ERROR)+++def _require_sqlite_reserved_index_ownership(bind: Any) -> None:+ rows = bind.execute(+ sa.text("SELECT type, name, tbl_name FROM sqlite_schema")+ ).fetchall()+ for row in rows:+ name = str(row[1])+ owner = _SQLITE_RESERVED_INDEX_OWNERS.get(name)+ if owner is None:+ continue+ if str(row[0]) != "index" or str(row[2]) != owner:+ raise RuntimeError(_CATALOG_ERROR)+++def _require_sqlite_managed_name_ownership(bind: Any) -> None:+ managed_tables = set(_REBUILD_ORDER) | {"alembic_version"}+ rows = bind.execute(+ sa.text("SELECT type, name, tbl_name FROM sqlite_schema")+ ).fetchall()+ for row in rows:+ name = str(row[1])+ if name in managed_tables and (+ str(row[0]) != "table" or str(row[2]) != name+ ):+ raise RuntimeError(_CATALOG_ERROR)+++def _require_no_sqlite_temp_shadows(bind: Any) -> None:+ managed_tables = set(_REBUILD_ORDER) | {"alembic_version"}+ reserved_indexes = set(_SQLITE_RESERVED_INDEX_OWNERS)+ rows = bind.execute(+ sa.text("SELECT type, name, tbl_name FROM sqlite_temp_master")+ ).fetchall()+ for row in rows:+ object_type = str(row[0])+ name = str(row[1])+ owner = str(row[2])+ if (+ name in managed_tables+ or name in reserved_indexes+ or name.startswith(_TEMP_PREFIX)+ or (object_type == "trigger" and owner in managed_tables)+ ):+ raise RuntimeError(_CATALOG_ERROR)+++def _require_sqlite_alembic_version_relation(bind: Any) -> None:+ rows = bind.execute(+ sa.text(+ "SELECT type, name, tbl_name, sql FROM sqlite_schema "+ "WHERE name='alembic_version' OR tbl_name='alembic_version'"+ )+ ).fetchall()+ if (+ len(rows) != 2+ or sum(+ 1+ for row in rows+ if str(row[0]) == "table"+ and str(row[1]) == "alembic_version"+ and str(row[2]) == "alembic_version"+ and isinstance(row[3], str)+ )+ != 1+ or sum(+ 1+ for row in rows+ if str(row[0]) == "index"+ and str(row[2]) == "alembic_version"+ and row[3] is None+ )+ != 1+ ):+ raise RuntimeError(_CATALOG_ERROR)+ if _sqlite_columns(bind, "alembic_version") != (+ _column("version_num", "VARCHAR(32)", False, primary_key=1),+ ):+ raise RuntimeError(_CATALOG_ERROR)+ physical_columns = bind.exec_driver_sql(+ 'PRAGMA table_xinfo("alembic_version")'+ ).fetchall()+ if (+ len(physical_columns) != 1+ or int(physical_columns[0][0]) != 0+ or str(physical_columns[0][1]) != "version_num"+ or str(physical_columns[0][2]).upper() != "VARCHAR(32)"+ or not bool(physical_columns[0][3])+ or physical_columns[0][4] is not None+ or int(physical_columns[0][5]) != 1+ or int(physical_columns[0][6]) != 0+ ):+ raise RuntimeError(_CATALOG_ERROR)+ normalized_sql = _sqlite_table_sql(bind, "alembic_version")+ if normalized_sql != (+ "createtablealembic_version("+ "version_numvarchar(32)notnull,"+ "constraintalembic_version_pkcprimarykey(version_num))"+ ):+ raise RuntimeError(_CATALOG_ERROR)+ _require_sqlite_primary_key_index(bind, "alembic_version")+ values = tuple(+ str(row[0])+ for row in bind.exec_driver_sql(+ "SELECT version_num FROM main.alembic_version"+ ).fetchall()+ )+ if values != ("0007",):+ raise RuntimeError(_CATALOG_ERROR)+++def _require_sqlite_table_shape_metadata(bind: Any, table: str) -> None:+ rows = bind.exec_driver_sql(+ f'PRAGMA table_xinfo({_quote_sqlite_identifier(table)})'+ ).fetchall()+ if (+ len(rows) != len(_sqlite_columns(bind, table))+ or any(int(row[6]) != 0 for row in rows)+ ):+ raise RuntimeError(_CATALOG_ERROR)+ raw_sql = _sqlite_raw_table_sql(bind, table)+ if table in {+ "audit_log",+ "rate_limit_events",+ "websocket_tickets",+ } and ("--" in raw_sql or "/*" in raw_sql or "*/" in raw_sql):+ raise RuntimeError(_CATALOG_ERROR)+ if any(+ re.search(pattern, raw_sql, re.IGNORECASE)+ for pattern in (+ r"\bCOLLATE\b",+ r"\bWITHOUT\s+ROWID\b",+ r"\bSTRICT\b",+ r"\bON\s+CONFLICT\b",+ r"\bGENERATED\b",+ r"\bDEFERRABLE\b",+ r"\bINITIALLY\s+(?:DEFERRED|IMMEDIATE)\b",+ r"\bMATCH\s+\w+\b",+ )+ ):+ raise RuntimeError(_CATALOG_ERROR)+++def _sqlite_unique_contracts(+ bind: Any,+ table: str,+) -> tuple[tuple[str, ...], ...]:+ contracts: list[tuple[str, ...]] = []+ rows = bind.exec_driver_sql(f'PRAGMA index_list("{table}")').fetchall()+ for row in rows:+ if str(row[3]) != "u":+ continue+ if not bool(row[2]) or bool(row[4]):+ raise RuntimeError(_CATALOG_ERROR)+ name = str(row[1])+ schema_rows = bind.execute(+ sa.text(+ "SELECT type, tbl_name, sql FROM sqlite_schema "+ "WHERE name=:name"+ ),+ {"name": name},+ ).fetchall()+ if (+ len(schema_rows) != 1+ or str(schema_rows[0][0]) != "index"+ or str(schema_rows[0][1]) != table+ or schema_rows[0][2] is not None+ ):+ raise RuntimeError(_CATALOG_ERROR)+ details = bind.exec_driver_sql(+ f'PRAGMA index_xinfo({_quote_sqlite_identifier(name)})'+ ).fetchall()+ key_columns = [column for column in details if bool(column[5])]+ auxiliary_columns = [+ column for column in details if not bool(column[5])+ ]+ if (+ not key_columns+ or tuple(int(column[0]) for column in key_columns)+ != tuple(range(len(key_columns)))+ or any(+ int(column[1]) < 0+ or column[2] is None+ or bool(column[3])+ or str(column[4]).upper() != "BINARY"+ for column in key_columns+ )+ or len(auxiliary_columns) != 1+ or int(auxiliary_columns[0][0]) != len(key_columns)+ or int(auxiliary_columns[0][1]) != -1+ or auxiliary_columns[0][2] is not None+ or bool(auxiliary_columns[0][3])+ or str(auxiliary_columns[0][4]).upper() != "BINARY"+ ):+ raise RuntimeError(_CATALOG_ERROR)+ contracts.append(+ tuple(str(column[2]) for column in key_columns)+ )+ return tuple(sorted(contracts))+++def _sqlite_indexes(bind: Any, table: str) -> dict[str, tuple[str, ...]]:+ result: dict[str, tuple[str, ...]] = {}+ rows = bind.exec_driver_sql(f'PRAGMA index_list("{table}")').fetchall()+ for row in rows:+ name = str(row[1])+ origin = str(row[3])+ partial = bool(row[4])+ if origin != "c":+ continue+ if bool(row[2]) or partial:+ raise RuntimeError(_CATALOG_ERROR)+ details = bind.exec_driver_sql(+ f'PRAGMA index_xinfo({_quote_sqlite_identifier(name)})'+ ).fetchall()+ key_columns = [column for column in details if bool(column[5])]+ auxiliary_columns = [+ column for column in details if not bool(column[5])+ ]+ if (+ not key_columns+ or tuple(int(column[0]) for column in key_columns)+ != tuple(range(len(key_columns)))+ or any(+ int(column[1]) < 0+ or column[2] is None+ or bool(column[3])+ or str(column[4]).upper() != "BINARY"+ for column in key_columns+ )+ or len(auxiliary_columns) != 1+ or int(auxiliary_columns[0][0]) != len(key_columns)+ or int(auxiliary_columns[0][1]) != -1+ or auxiliary_columns[0][2] is not None+ or bool(auxiliary_columns[0][3])+ or str(auxiliary_columns[0][4]).upper() != "BINARY"+ ):+ raise RuntimeError(_CATALOG_ERROR)+ schema_rows = bind.execute(+ sa.text(+ "SELECT type, tbl_name, sql FROM sqlite_schema "+ "WHERE name=:name"+ ),+ {"name": name},+ ).fetchall()+ if (+ len(schema_rows) != 1+ or str(schema_rows[0][0]) != "index"+ or str(schema_rows[0][1]) != table+ or not isinstance(schema_rows[0][2], str)+ ):+ raise RuntimeError(_CATALOG_ERROR)+ normalized_sql = re.sub(+ r"\s+",+ "",+ str(schema_rows[0][2]),+ ).lower().replace('"', "")+ expected_sql = (+ f"createindex{name.lower()}on{table.lower()}("+ + ",".join(str(column[2]).lower() for column in key_columns)+ + ")"+ )+ if normalized_sql != expected_sql:+ raise RuntimeError(_CATALOG_ERROR)+ result[name] = tuple(str(column[2]) for column in key_columns)+ return result+++def _sqlite_raw_table_sql(bind: Any, table: str) -> str:+ row = bind.execute(+ sa.text(+ "SELECT sql FROM sqlite_master "+ "WHERE type='table' AND name=:name"+ ),+ {"name": table},+ ).scalar_one_or_none()+ if not isinstance(row, str):+ raise RuntimeError(_CATALOG_ERROR)+ return row+++def _normalize_sql_syntax(+ value: object,+ *,+ strip_postgres_casts: bool = False,+) -> str:+ text = str(value)+ chunks: list[str] = []+ position = 0+ unquoted_start = 0++ def append_unquoted(segment: str) -> None:+ normalized = segment.lower().replace('"', "")+ if strip_postgres_casts:+ normalized = re.sub(+ r"::(?:text|double precision|integer|character varying)",+ "",+ normalized,+ )+ chunks.append(re.sub(r"\s+", "", normalized))++ while position < len(text):+ if text[position] != "'":+ position += 1+ continue+ append_unquoted(text[unquoted_start:position])+ literal_start = position+ position += 1+ while position < len(text):+ if text[position] != "'":+ position += 1+ continue+ if position + 1 < len(text) and text[position + 1] == "'":+ position += 2+ continue+ position += 1+ break+ else:+ raise RuntimeError(_CATALOG_ERROR)+ chunks.append(text[literal_start:position])+ unquoted_start = position+ append_unquoted(text[unquoted_start:])+ return "".join(chunks)+++def _sqlite_table_sql(bind: Any, table: str) -> str:+ return _normalize_sql_syntax(_sqlite_raw_table_sql(bind, table))+++def _sqlite_ticket_snapshot(bind: Any) -> tuple[object, ...]:+ rows = bind.execute(+ sa.text(+ "SELECT ticket_hash, campaign_id, user_id, credential_kind, "+ "bearer_subject, bearer_jti, bearer_expires_at, api_key_id, "+ "required_scope, created_at, expires_at, consumed_at "+ "FROM websocket_tickets ORDER BY ticket_hash"+ )+ ).fetchall()+ return tuple(+ tuple(value for value in row)+ for row in rows+ )+++def _columns_compatible(+ table: str,+ actual: tuple[_Column, ...],+) -> bool:+ expected = _SQLITE_COLUMNS[table]+ actual_names = tuple(column[0] for column in actual)+ expected_names = tuple(column[0] for column in expected)+ allowed_orders = {expected_names}+ if table == "findings":+ runtime = list(expected_names)+ runtime.remove("trace_id")+ runtime.insert(runtime.index("evidence_json"), "trace_id")+ historical = (+ "id",+ "campaign_id",+ "module_id",+ "title",+ "description",+ "severity",+ "cvss_score",+ "cvss_vector",+ "confidence",+ "mitre_technique",+ "mitre_tactic",+ "evidence_json",+ "remediation",+ "host",+ "validated",+ "false_positive",+ "discovered_at",+ "trace_id",+ )+ allowed_orders.update({tuple(runtime), historical})+ elif table == "credentials":+ historical = list(expected_names)+ historical.remove("cracked_value_enc")+ historical.append("cracked_value_enc")+ allowed_orders.add(tuple(historical))+ source_only = tuple(+ "cracked_value" if name == "cracked_value_enc" else name+ for name in expected_names+ )+ historical_source_only = tuple(+ "cracked_value" if name == "cracked_value_enc" else name+ for name in historical+ )+ allowed_orders.update({source_only, historical_source_only})+ if actual_names not in allowed_orders:+ return False++ by_name = {column[0]: column for column in actual}+ for expected_column in expected:+ name, expected_type, expected_nullable, default, primary_key = (+ expected_column+ )+ source_name = (+ "cracked_value"+ if table == "credentials"+ and name == "cracked_value_enc"+ and name not in by_name+ else name+ )+ current = by_name[source_name]+ current_type = current[1]+ if (+ table in {"module_runs", "findings"}+ and name in {"duration_ms", "confidence", "cvss_score"}+ ):+ type_matches = current_type in {"FLOAT", "REAL"}+ else:+ type_matches = current_type == expected_type+ if not type_matches or current[3:] != (default, primary_key):+ return False+ if current[2] != expected_nullable:+ if not (+ table == "findings"+ and name in {"cvss_score", "cvss_vector", "trace_id"}+ and current[2]+ and not expected_nullable+ ) and not (+ primary_key == 1+ and current[2]+ and not expected_nullable+ ):+ return False+ return True+++def _require_not_null_data(bind: Any, table: str) -> None:+ columns = [+ name+ for name, _kind, nullable, _default, _primary_key+ in _SQLITE_COLUMNS[table]+ if not nullable+ ]+ predicate = " OR ".join(f'"{name}" IS NULL' for name in columns)+ statement = ( # noqa: S608+ f'SELECT 1 FROM "{table}" WHERE {predicate} LIMIT 1' # noqa: S608+ )+ if predicate and bind.exec_driver_sql( # noqa: S608+ statement+ ).first():+ raise RuntimeError(_DATA_ERROR)+++def _require_no_orphans(bind: Any) -> None:+ checks = (+ ("module_runs", "campaign_id", "campaigns", "id", False),+ ("findings", "campaign_id", "campaigns", "id", False),+ ("hosts", "campaign_id", "campaigns", "id", False),+ ("credentials", "campaign_id", "campaigns", "id", False),+ ("credentials", "host_id", "hosts", "id", True),+ ("loot", "campaign_id", "campaigns", "id", False),+ ("loot", "host_id", "hosts", "id", True),+ ("audit_log", "campaign_id", "campaigns", "id", True),+ ("api_keys", "user_id", "users", "id", False),+ ("refresh_tokens", "user_id", "users", "id", False),+ (+ "websocket_tickets",+ "campaign_id",+ "campaigns",+ "id",+ False,+ ),+ ("websocket_tickets", "user_id", "users", "id", False),+ (+ "websocket_tickets",+ "api_key_id",+ "api_keys",+ "id",+ True,+ ),+ )+ tables = set(sa.inspect(bind).get_table_names())+ for child, local, parent, remote, nullable in checks:+ if child not in tables:+ continue+ nullable_guard = f'child."{local}" IS NOT NULL AND ' if nullable else ""+ statement = ( # noqa: S608+ f'SELECT 1 FROM "{child}" AS child ' # noqa: S608+ f'LEFT JOIN "{parent}" AS parent '+ f'ON child."{local}"=parent."{remote}" '+ f'WHERE {nullable_guard}parent."{remote}" IS NULL LIMIT 1'+ )+ if bind.exec_driver_sql(statement).first(): # noqa: S608+ raise RuntimeError(_DATA_ERROR)+++def _require_boolean_integer_data(+ bind: Any,+ tables: set[str],+) -> None:+ for table, column in _BOOLEAN_INTEGER_COLUMNS:+ if table not in tables:+ continue+ statement = ( # noqa: S608+ f'SELECT 1 FROM "{table}" ' # noqa: S608+ f'WHERE "{column}" NOT IN (0, 1) LIMIT 1'+ )+ if bind.exec_driver_sql(statement).first():+ raise RuntimeError(_DATA_ERROR)+++def _require_valid_sqlite_timestamps(+ bind: Any,+ tables: set[str],+) -> None:+ for table, columns in _SQLITE_TIMESTAMPS.items():+ if table not in tables:+ continue+ for column in columns:+ statement = ( # noqa: S608+ f'SELECT 1 FROM "{table}" ' # noqa: S608+ f'WHERE "{column}" IS NOT NULL '+ f'AND julianday("{column}") IS NULL LIMIT 1'+ )+ if bind.exec_driver_sql(statement).first():+ raise RuntimeError(_DATA_ERROR)+++def _require_valid_sqlite_ticket_data(+ bind: Any,+ tables: set[str],+) -> None:+ if "websocket_tickets" not in tables:+ return+ timestamp_format = "%Y-%m-%dT%H:%M:%fZ"+ statement = """+ SELECT 1+ FROM websocket_tickets+ WHERE COALESCE(+ (+ length(ticket_hash)=64+ AND ticket_hash NOT GLOB '*[^0-9a-f]*'+ AND credential_kind IN ('bearer', 'api_key')+ AND strftime(:timestamp_format, created_at) IS NOT NULL+ AND strftime(:timestamp_format, created_at)=created_at+ AND strftime(:timestamp_format, expires_at) IS NOT NULL+ AND strftime(:timestamp_format, expires_at)=expires_at+ AND (+ consumed_at IS NULL+ OR (+ strftime(+ :timestamp_format,+ consumed_at+ ) IS NOT NULL+ AND strftime(+ :timestamp_format,+ consumed_at+ )=consumed_at+ )+ )+ AND julianday(expires_at) > julianday(created_at)+ AND (+ consumed_at IS NULL+ OR julianday(consumed_at) < julianday(expires_at)+ )+ AND (+ (+ credential_kind='bearer'+ AND bearer_subject IS NOT NULL+ AND length(trim(bearer_subject)) > 0+ AND bearer_subject=trim(bearer_subject)+ AND bearer_jti IS NOT NULL+ AND length(trim(bearer_jti)) > 0+ AND bearer_jti=trim(bearer_jti)+ AND bearer_expires_at IS NOT NULL+ AND strftime(+ :timestamp_format,+ bearer_expires_at+ ) IS NOT NULL+ AND strftime(+ :timestamp_format,+ bearer_expires_at+ )=bearer_expires_at+ AND api_key_id IS NULL+ AND required_scope IS NULL+ )+ OR (+ credential_kind='api_key'+ AND bearer_subject IS NULL+ AND bearer_jti IS NULL+ AND bearer_expires_at IS NULL+ AND api_key_id IS NOT NULL+ AND length(trim(api_key_id)) > 0+ AND api_key_id=trim(api_key_id)+ AND required_scope='read'+ )+ )+ ),+ 0+ ) != 1+ LIMIT 1+ """+ if bind.execute(+ sa.text(statement),+ {"timestamp_format": timestamp_format},+ ).first():+ raise RuntimeError(_DATA_ERROR)+++def _require_no_external_references(+ bind: Any,+ tables: set[str],+) -> None:+ rebuilt = set(_REBUILD_ORDER)+ for child in tables - rebuilt:+ for row in bind.exec_driver_sql(+ f'PRAGMA foreign_key_list("{child}")' # noqa: S608+ ).fetchall():+ if str(row[2]) in rebuilt:+ raise RuntimeError(_CATALOG_ERROR)+++def _require_ticket_contract(bind: Any) -> None:+ if _sqlite_columns(bind, "websocket_tickets") != _SQLITE_COLUMNS[+ "websocket_tickets"+ ]:+ raise RuntimeError(_CATALOG_ERROR)+ foreign_key_rows = bind.exec_driver_sql(+ 'PRAGMA foreign_key_list("websocket_tickets")'+ ).fetchall()+ foreign_key_contracts = tuple(+ sorted(+ (+ str(row[3]),+ str(row[2]),+ str(row[4]),+ str(row[5]).upper(),+ str(row[6]).upper(),+ str(row[7]).upper(),+ )+ for row in foreign_key_rows+ )+ )+ expected_foreign_keys = tuple(+ sorted(+ (*contract, "NONE")+ for contract in _SQLITE_FOREIGN_KEYS["websocket_tickets"]+ )+ )+ if (+ len(foreign_key_rows) != len(expected_foreign_keys)+ or {int(row[0]) for row in foreign_key_rows}+ != set(range(len(expected_foreign_keys)))+ or any(int(row[1]) != 0 for row in foreign_key_rows)+ or foreign_key_contracts != expected_foreign_keys+ ):+ raise RuntimeError(_CATALOG_ERROR)+ if _sqlite_indexes(bind, "websocket_tickets") != _SQLITE_INDEXES[+ "websocket_tickets"+ ]:+ raise RuntimeError(_CATALOG_ERROR)+ raw_sql = _sqlite_raw_table_sql(bind, "websocket_tickets")+ if "--" in raw_sql or "/*" in raw_sql or "*/" in raw_sql:+ raise RuntimeError(_CATALOG_ERROR)+ sql = _sqlite_table_sql(bind, "websocket_tickets")+ required = (+ "constraintck_ws_ticket_hashcheck("+ "length(ticket_hash)=64andticket_hashnotglob'*[^0-9a-f]*')",+ "constraintck_ws_ticket_kindcheck("+ "credential_kindin('bearer','api_key'))",+ "constraintck_ws_ticket_created_atcheck("+ "strftime('%Y-%m-%dT%H:%M:%fZ',created_at)isnotnulland"+ "strftime('%Y-%m-%dT%H:%M:%fZ',created_at)=created_at)",+ "constraintck_ws_ticket_expires_atcheck("+ "strftime('%Y-%m-%dT%H:%M:%fZ',expires_at)isnotnulland"+ "strftime('%Y-%m-%dT%H:%M:%fZ',expires_at)=expires_at)",+ "constraintck_ws_ticket_consumed_atcheck("+ "consumed_atisnullor(strftime('%Y-%m-%dT%H:%M:%fZ',"+ "consumed_at)isnotnullandstrftime('%Y-%m-%dT%H:%M:%fZ',"+ "consumed_at)=consumed_at))",+ "constraintck_ws_ticket_time_ordercheck("+ "julianday(expires_at)>julianday(created_at)and("+ "consumed_atisnullorjulianday(consumed_at)<"+ "julianday(expires_at)))",+ "constraintck_ws_ticket_source_shapecheck("+ "(credential_kind='bearer'andbearer_subjectisnotnulland"+ "length(trim(bearer_subject))>0and"+ "bearer_subject=trim(bearer_subject)andbearer_jtiisnotnulland"+ "length(trim(bearer_jti))>0andbearer_jti=trim(bearer_jti)and"+ "bearer_expires_atisnotnulland"+ "strftime('%Y-%m-%dT%H:%M:%fZ',bearer_expires_at)isnotnulland"+ "strftime('%Y-%m-%dT%H:%M:%fZ',bearer_expires_at)="+ "bearer_expires_atandapi_key_idisnullandrequired_scopeisnull)"+ "or(credential_kind='api_key'andbearer_subjectisnulland"+ "bearer_jtiisnullandbearer_expires_atisnulland"+ "api_key_idisnotnullandlength(trim(api_key_id))>0and"+ "api_key_id=trim(api_key_id)andrequired_scope='read'))",+ )+ foreign_key_names = (+ "constraintfk_ws_ticket_campaign",+ "constraintfk_ws_ticket_user",+ "constraintfk_ws_ticket_api_key",+ )+ table_level_foreign_keys = (+ "constraintfk_ws_ticket_campaignforeignkey(campaign_id)"+ "referencescampaigns(id)ondeletecascade",+ "constraintfk_ws_ticket_userforeignkey(user_id)"+ "referencesusers(id)ondeletecascade",+ "constraintfk_ws_ticket_api_keyforeignkey(api_key_id)"+ "referencesapi_keys(id)ondeletecascade",+ )+ inline_foreign_keys = (+ "campaign_idtextnotnullconstraintfk_ws_ticket_campaign"+ "referencescampaigns(id)ondeletecascade",+ "user_idtextnotnullconstraintfk_ws_ticket_user"+ "referencesusers(id)ondeletecascade",+ "api_key_idtextconstraintfk_ws_ticket_api_key"+ "referencesapi_keys(id)ondeletecascade",+ )+ table_level = all(+ fragment in sql for fragment in table_level_foreign_keys+ )+ inline = all(fragment in sql for fragment in inline_foreign_keys)+ if (+ sql.count("check(") != 7+ or (table_level == inline)+ or sql.count("foreignkey(") != (3 if table_level else 0)+ or any(sql.count(name) != 1 for name in foreign_key_names)+ or any(+ forbidden in sql+ for forbidden in (+ "deferrable",+ "initiallydeferred",+ "initiallyimmediate",+ "match",+ )+ )+ or any(fragment not in sql for fragment in required)+ ):+ raise RuntimeError(_CATALOG_ERROR)+++def _sqlite_preflight(bind: Any) -> bool:+ _require_no_sqlite_temp_shadows(bind)+ _require_sqlite_managed_name_ownership(bind)+ _require_sqlite_alembic_version_relation(bind)+ tables = set(sa.inspect(bind).get_table_names())+ required = {+ "campaigns",+ "findings",+ "hosts",+ "credentials",+ "loot",+ "audit_log",+ "users",+ "api_keys",+ "refresh_tokens",+ "revoked_access_tokens",+ "websocket_tickets",+ }+ if not required.issubset(tables):+ raise RuntimeError(_CATALOG_ERROR)+ if any(table.startswith(_TEMP_PREFIX) for table in tables):+ raise RuntimeError(_CATALOG_ERROR)+ _require_sqlite_reserved_index_ownership(bind)+ triggers = bind.execute(+ sa.text(+ "SELECT 1 FROM sqlite_master WHERE type='trigger' "+ "AND tbl_name IN ("+ "'alembic_version','schema_version','campaigns','users',"+ "'revoked_access_tokens','hosts','module_runs','findings',"+ "'credentials','loot','audit_log','api_keys',"+ "'refresh_tokens','rate_limit_events',"+ "'websocket_tickets') LIMIT 1"+ )+ ).first()+ if triggers:+ raise RuntimeError(_CATALOG_ERROR)++ optional = {"schema_version", "module_runs", "rate_limit_events"}+ for table in required | (optional & tables):+ if not _columns_compatible(table, _sqlite_columns(bind, table)):+ raise RuntimeError(_CATALOG_ERROR)+ _require_sqlite_table_shape_metadata(bind, table)+ _require_sqlite_primary_key_index(bind, table)+ _require_not_null_data(bind, table)++ _require_ticket_contract(bind)+ _require_no_orphans(bind)+ _require_boolean_integer_data(bind, tables)+ _require_valid_sqlite_timestamps(bind, tables)+ _require_valid_sqlite_ticket_data(bind, tables)+ _require_no_external_references(bind, tables)++ expected_unique = {+ "hosts": {("campaign_id", "ip_address")},+ "users": {("username",)},+ }+ unique_exact = True+ managed = required | (optional & tables)+ for table in managed:+ expected = tuple(sorted(expected_unique.get(table, set())))+ unique = _sqlite_unique_contracts(bind, table)+ raw_table_sql = _sqlite_raw_table_sql(bind, table)+ unique_declarations = len(+ re.findall(r"\bUNIQUE\b", raw_table_sql, re.IGNORECASE)+ )+ if (+ unique_declarations != len(unique)+ or re.search(+ r"\bON\s+CONFLICT\b",+ raw_table_sql,+ re.IGNORECASE,+ )+ ):+ raise RuntimeError(_CATALOG_ERROR)+ if unique not in ((), expected):+ raise RuntimeError(_CATALOG_ERROR)+ if expected and not unique:+ columns = expected[0]+ grouped = ", ".join(f'"{column}"' for column in columns)+ statement = ( # noqa: S608+ f'SELECT 1 FROM "{table}" GROUP BY {grouped} ' # noqa: S608+ "HAVING count(*) > 1 LIMIT 1"+ )+ if bind.exec_driver_sql(statement).first():+ raise RuntimeError(_DATA_ERROR)+ unique_exact = False+ sql = _sqlite_table_sql(bind, table)+ if table not in {"rate_limit_events", "websocket_tickets"} and (+ "check(" in sql+ ):+ raise RuntimeError(_CATALOG_ERROR)++ exact = optional.issubset(tables) and unique_exact+ for table in _SQLITE_COLUMNS:+ if table not in tables:+ continue+ expected_columns = _SQLITE_COLUMNS[table]+ actual_columns = _sqlite_columns(bind, table)+ exact_columns = actual_columns == expected_columns+ exact = exact and exact_columns++ expected_fks = _SQLITE_FOREIGN_KEYS.get(table, frozenset())+ actual_fks = _sqlite_foreign_keys(bind, table)+ if (+ len(actual_fks) != len(set(actual_fks))+ or not set(actual_fks).issubset(expected_fks)+ ):+ raise RuntimeError(_CATALOG_ERROR)+ exact = exact and actual_fks == tuple(sorted(expected_fks))++ expected_indexes = _SQLITE_INDEXES.get(table, {})+ actual_indexes = _sqlite_indexes(bind, table)+ allowed_indexes = dict(expected_indexes)+ if table == "findings":+ allowed_indexes["idx_findings_validated"] = ("validated",)+ if any(+ name not in allowed_indexes+ or allowed_indexes[name] != columns+ for name, columns in actual_indexes.items()+ ):+ raise RuntimeError(_CATALOG_ERROR)+ exact = exact and actual_indexes == expected_indexes++ for table in ("audit_log", "rate_limit_events"):+ if table in tables:+ has_autoincrement = "autoincrement" in _sqlite_table_sql(+ bind, table+ )+ exact = exact and has_autoincrement+ if "rate_limit_events" in tables:+ sql = _sqlite_table_sql(bind, "rate_limit_events")+ has_check = (+ "constraintck_rate_limit_events_blocked_bool"+ "check(blockedin(0,1))"+ ) in sql+ if sql.count("check(") not in {0, 1} or (+ "check(" in sql and not has_check+ ):+ raise RuntimeError(_CATALOG_ERROR)+ exact = exact and has_check+ return exact+++def _create_sqlite_table(table: str) -> None:+ if table == "schema_version":+ op.create_table(+ table,+ sa.Column("version", sa.Integer(), primary_key=True),+ sa.Column(+ "applied_at",+ sa.Text(),+ nullable=False,+ server_default=sa.text("datetime('now')"),+ ),+ )+ elif table == "campaigns":+ op.create_table(+ table,+ sa.Column("id", sa.Text(), primary_key=True),+ sa.Column("name", sa.Text(), nullable=False),+ sa.Column(+ "client",+ sa.Text(),+ nullable=False,+ server_default="Internal",+ ),+ sa.Column(+ "operator",+ sa.Text(),+ nullable=False,+ server_default="unknown",+ ),+ sa.Column(+ "noise_profile",+ sa.Text(),+ nullable=False,+ server_default="stealth",+ ),+ sa.Column(+ "status",+ sa.Text(),+ nullable=False,+ server_default="created",+ ),+ sa.Column(+ "scope_json",+ sa.Text(),+ nullable=False,+ server_default="[]",+ ),+ sa.Column(+ "targets_json",+ sa.Text(),+ nullable=False,+ server_default="[]",+ ),+ sa.Column("notes", sa.Text(), server_default=""),+ sa.Column(+ "created_at",+ sa.Text(),+ nullable=False,+ server_default=sa.text("datetime('now')"),+ ),+ sa.Column(+ "updated_at",+ sa.Text(),+ nullable=False,+ server_default=sa.text("datetime('now')"),+ ),+ )+ elif table == "users":+ op.create_table(+ table,+ sa.Column("id", sa.Text(), primary_key=True),+ sa.Column("username", sa.Text(), nullable=False),+ sa.Column("hashed_password", sa.Text(), nullable=False),+ sa.Column(+ "role", sa.Text(), nullable=False, server_default="reporter"+ ),+ sa.Column(+ "is_active",+ sa.Integer(),+ nullable=False,+ server_default="1",+ ),+ sa.Column(+ "created_by",+ sa.Text(),+ nullable=False,+ server_default="system",+ ),+ sa.Column(+ "created_at",+ sa.Text(),+ nullable=False,+ server_default=sa.text("datetime('now')"),+ ),+ sa.Column("last_login", sa.Text()),+ sa.UniqueConstraint("username", name="uq_users_username"),+ )+ elif table == "revoked_access_tokens":+ op.create_table(+ table,+ sa.Column("jti", sa.Text(), primary_key=True),+ sa.Column("user_id", sa.Text(), nullable=False),+ sa.Column(+ "revoked_at",+ sa.Text(),+ nullable=False,+ server_default=sa.text("datetime('now')"),+ ),+ sa.Column("expires_at", sa.Text(), nullable=False),+ )+ elif table == "hosts":+ op.create_table(+ table,+ sa.Column("id", sa.Text(), primary_key=True),+ sa.Column(+ "campaign_id",+ sa.Text(),+ sa.ForeignKey(+ "campaigns.id",+ name="fk_hosts_campaign",+ ondelete="CASCADE",+ ),+ nullable=False,+ ),+ sa.Column("ip_address", sa.Text(), nullable=False),+ sa.Column("hostname", sa.Text()),+ sa.Column("fqdn", sa.Text()),+ sa.Column("os", sa.Text()),+ sa.Column("os_version", sa.Text()),+ sa.Column("domain", sa.Text()),+ sa.Column(+ "is_dc", sa.Integer(), nullable=False, server_default="0"+ ),+ sa.Column(+ "open_ports_json",+ sa.Text(),+ nullable=False,+ server_default="[]",+ ),+ sa.Column(+ "tags_json", sa.Text(), nullable=False, server_default="[]"+ ),+ sa.Column(+ "first_seen",+ sa.Text(),+ nullable=False,+ server_default=sa.text("datetime('now')"),+ ),+ sa.Column(+ "last_seen",+ sa.Text(),+ nullable=False,+ server_default=sa.text("datetime('now')"),+ ),+ sa.UniqueConstraint(+ "campaign_id", "ip_address", name="uq_hosts_campaign_ip"+ ),+ )+ elif table == "module_runs":+ op.create_table(+ table,+ sa.Column("id", sa.Text(), primary_key=True),+ sa.Column(+ "campaign_id",+ sa.Text(),+ sa.ForeignKey(+ "campaigns.id",+ name="fk_module_runs_campaign",+ ondelete="CASCADE",+ ),+ nullable=False,+ ),+ sa.Column("module_id", sa.Text(), nullable=False),+ sa.Column("outcome", sa.Text(), nullable=False),+ sa.Column(+ "success", sa.Integer(), nullable=False, server_default="0"+ ),+ sa.Column(+ "duration_ms",+ sa.Float(),+ nullable=False,+ server_default="0.0",+ ),+ sa.Column(+ "completed_at",+ sa.Text(),+ nullable=False,+ server_default=sa.text("datetime('now')"),+ ),+ )+ elif table == "findings":+ op.create_table(+ table,+ sa.Column("id", sa.Text(), primary_key=True),+ sa.Column(+ "campaign_id",+ sa.Text(),+ sa.ForeignKey(+ "campaigns.id",+ name="fk_findings_campaign",+ ondelete="CASCADE",+ ),+ nullable=False,+ ),+ sa.Column("module_id", sa.Text(), nullable=False),+ sa.Column("title", sa.Text(), nullable=False),+ sa.Column("description", sa.Text(), nullable=False),+ sa.Column("severity", sa.Text(), nullable=False),+ sa.Column(+ "confidence",+ sa.Float(),+ nullable=False,+ server_default="1.0",+ ),+ sa.Column("mitre_technique", sa.Text()),+ sa.Column("mitre_tactic", sa.Text()),+ sa.Column(+ "cvss_score",+ sa.Float(),+ nullable=False,+ server_default="0.0",+ ),+ sa.Column(+ "cvss_vector",+ sa.Text(),+ nullable=False,+ server_default="",+ ),+ sa.Column(+ "evidence_json",+ sa.Text(),+ nullable=False,+ server_default="{}",+ ),+ sa.Column("remediation", sa.Text(), server_default=""),+ sa.Column("host", sa.Text()),+ sa.Column(+ "validated",+ sa.Integer(),+ nullable=False,+ server_default="0",+ ),+ sa.Column(+ "false_positive",+ sa.Integer(),+ nullable=False,+ server_default="0",+ ),+ sa.Column(+ "discovered_at",+ sa.Text(),+ nullable=False,+ server_default=sa.text("datetime('now')"),+ ),+ sa.Column(+ "trace_id",+ sa.Text(),+ nullable=False,+ server_default="",+ ),+ )+ elif table == "credentials":+ op.create_table(+ table,+ sa.Column("id", sa.Text(), primary_key=True),+ sa.Column(+ "campaign_id",+ sa.Text(),+ sa.ForeignKey(+ "campaigns.id",+ name="fk_credentials_campaign",+ ondelete="CASCADE",+ ),+ nullable=False,+ ),+ sa.Column(+ "host_id",+ sa.Text(),+ sa.ForeignKey(+ "hosts.id",+ name="fk_credentials_host",+ ondelete="SET NULL",+ ),+ ),+ sa.Column("username", sa.Text(), nullable=False),+ sa.Column("secret_enc", sa.Text()),+ sa.Column("cred_type", sa.Text(), nullable=False),+ sa.Column("domain", sa.Text()),+ sa.Column("source_module", sa.Text()),+ sa.Column("notes", sa.Text(), server_default=""),+ sa.Column(+ "cracked", sa.Integer(), nullable=False, server_default="0"+ ),+ sa.Column("cracked_value_enc", sa.Text()),+ sa.Column(+ "captured_at",+ sa.Text(),+ nullable=False,+ server_default=sa.text("datetime('now')"),+ ),+ )+ elif table == "loot":+ op.create_table(+ table,+ sa.Column("id", sa.Text(), primary_key=True),+ sa.Column(+ "campaign_id",+ sa.Text(),+ sa.ForeignKey(+ "campaigns.id",+ name="fk_loot_campaign",+ ondelete="CASCADE",+ ),+ nullable=False,+ ),+ sa.Column(+ "host_id",+ sa.Text(),+ sa.ForeignKey(+ "hosts.id",+ name="fk_loot_host",+ ondelete="SET NULL",+ ),+ ),+ sa.Column("loot_type", sa.Text(), nullable=False),+ sa.Column("name", sa.Text(), nullable=False),+ sa.Column("description", sa.Text(), server_default=""),+ sa.Column("content_enc", sa.Text()),+ sa.Column("size_bytes", sa.Integer(), server_default="0"),+ sa.Column("path_on_target", sa.Text()),+ sa.Column("source_module", sa.Text()),+ sa.Column(+ "tags_json", sa.Text(), nullable=False, server_default="[]"+ ),+ sa.Column(+ "captured_at",+ sa.Text(),+ nullable=False,+ server_default=sa.text("datetime('now')"),+ ),+ )+ elif table == "audit_log":+ op.create_table(+ table,+ sa.Column(+ "id", sa.Integer(), primary_key=True, autoincrement=True+ ),+ sa.Column(+ "campaign_id",+ sa.Text(),+ sa.ForeignKey(+ "campaigns.id",+ name="fk_audit_campaign",+ ondelete="SET NULL",+ ),+ ),+ sa.Column(+ "actor", sa.Text(), nullable=False, server_default="system"+ ),+ sa.Column("action", sa.Text(), nullable=False),+ sa.Column("detail", sa.Text(), server_default=""),+ sa.Column("module_id", sa.Text()),+ sa.Column(+ "timestamp",+ sa.Text(),+ nullable=False,+ server_default=sa.text("datetime('now')"),+ ),+ sqlite_autoincrement=True,+ )+ elif table == "api_keys":+ op.create_table(+ table,+ sa.Column("id", sa.Text(), primary_key=True),+ sa.Column(+ "user_id",+ sa.Text(),+ sa.ForeignKey(+ "users.id",+ name="fk_api_keys_user",+ ondelete="CASCADE",+ ),+ nullable=False,+ ),+ sa.Column("name", sa.Text(), nullable=False),+ sa.Column("key_hash", sa.Text(), nullable=False),+ sa.Column("key_prefix", sa.Text(), nullable=False),+ sa.Column(+ "scopes", sa.Text(), nullable=False, server_default="read"+ ),+ sa.Column(+ "is_active",+ sa.Integer(),+ nullable=False,+ server_default="1",+ ),+ sa.Column("last_used", sa.Text()),+ sa.Column("expires_at", sa.Text()),+ sa.Column(+ "created_at",+ sa.Text(),+ nullable=False,+ server_default=sa.text("datetime('now')"),+ ),+ )+ elif table == "refresh_tokens":+ op.create_table(+ table,+ sa.Column("id", sa.Text(), primary_key=True),+ sa.Column(+ "user_id",+ sa.Text(),+ sa.ForeignKey(+ "users.id",+ name="fk_refresh_tokens_user",+ ondelete="CASCADE",+ ),+ nullable=False,+ ),+ sa.Column(+ "is_revoked",+ sa.Integer(),+ nullable=False,+ server_default="0",+ ),+ sa.Column("expires_at", sa.Text(), nullable=False),+ sa.Column(+ "created_at",+ sa.Text(),+ nullable=False,+ server_default=sa.text("datetime('now')"),+ ),+ sa.Column("used_at", sa.Text()),+ )+ elif table == "rate_limit_events":+ op.create_table(+ table,+ sa.Column(+ "id", sa.Integer(), primary_key=True, autoincrement=True+ ),+ sa.Column("ip_address", sa.Text(), nullable=False),+ sa.Column("bucket", sa.Text(), nullable=False),+ sa.Column("username", sa.Text()),+ sa.Column(+ "blocked", sa.Integer(), nullable=False, server_default="0"+ ),+ sa.Column(+ "timestamp",+ sa.Text(),+ nullable=False,+ server_default=sa.text("datetime('now')"),+ ),+ sa.CheckConstraint(+ "blocked IN (0, 1)",+ name="ck_rate_limit_events_blocked_bool",+ ),+ sqlite_autoincrement=True,+ )+ elif table == "websocket_tickets":+ _create_sqlite_websocket_tickets()+ else:+ raise RuntimeError(_CATALOG_ERROR)+++def _create_sqlite_websocket_tickets() -> None:+ timestamp_format = "%Y-%m-%dT%H:%M:%fZ"+ op.create_table(+ "websocket_tickets",+ sa.Column("ticket_hash", sa.Text(), primary_key=True, nullable=False),+ sa.Column(+ "campaign_id",+ sa.Text(),+ sa.ForeignKey(+ "campaigns.id",+ name="fk_ws_ticket_campaign",+ ondelete="CASCADE",+ ),+ nullable=False,+ ),+ sa.Column(+ "user_id",+ sa.Text(),+ sa.ForeignKey(+ "users.id",+ name="fk_ws_ticket_user",+ ondelete="CASCADE",+ ),+ nullable=False,+ ),+ sa.Column("credential_kind", sa.Text(), nullable=False),+ sa.Column("bearer_subject", sa.Text()),+ sa.Column("bearer_jti", sa.Text()),+ sa.Column("bearer_expires_at", sa.Text()),+ sa.Column(+ "api_key_id",+ sa.Text(),+ sa.ForeignKey(+ "api_keys.id",+ name="fk_ws_ticket_api_key",+ ondelete="CASCADE",+ ),+ ),+ sa.Column("required_scope", sa.Text()),+ sa.Column("created_at", sa.Text(), nullable=False),+ sa.Column("expires_at", sa.Text(), nullable=False),+ sa.Column("consumed_at", sa.Text()),+ sa.CheckConstraint(+ "length(ticket_hash)=64 "+ "AND ticket_hash NOT GLOB '*[^0-9a-f]*'",+ name="ck_ws_ticket_hash",+ ),+ sa.CheckConstraint(+ "credential_kind IN ('bearer', 'api_key')",+ name="ck_ws_ticket_kind",+ ),+ sa.CheckConstraint(+ f"strftime('{timestamp_format}', created_at) IS NOT NULL "+ f"AND strftime('{timestamp_format}', created_at)=created_at",+ name="ck_ws_ticket_created_at",+ ),+ sa.CheckConstraint(+ f"strftime('{timestamp_format}', expires_at) IS NOT NULL "+ f"AND strftime('{timestamp_format}', expires_at)=expires_at",+ name="ck_ws_ticket_expires_at",+ ),+ sa.CheckConstraint(+ "consumed_at IS NULL OR ("+ f"strftime('{timestamp_format}', consumed_at) IS NOT NULL "+ f"AND strftime('{timestamp_format}', consumed_at)=consumed_at)",+ name="ck_ws_ticket_consumed_at",+ ),+ sa.CheckConstraint(+ "julianday(expires_at) > julianday(created_at) "+ "AND (consumed_at IS NULL "+ "OR julianday(consumed_at) < julianday(expires_at))",+ name="ck_ws_ticket_time_order",+ ),+ sa.CheckConstraint(+ """+ (+ credential_kind='bearer'+ AND bearer_subject IS NOT NULL+ AND length(trim(bearer_subject)) > 0+ AND bearer_subject=trim(bearer_subject)+ AND bearer_jti IS NOT NULL+ AND length(trim(bearer_jti)) > 0+ AND bearer_jti=trim(bearer_jti)+ AND bearer_expires_at IS NOT NULL+ AND strftime(+ '%Y-%m-%dT%H:%M:%fZ', bearer_expires_at+ ) IS NOT NULL+ AND strftime(+ '%Y-%m-%dT%H:%M:%fZ', bearer_expires_at+ )=bearer_expires_at+ AND api_key_id IS NULL+ AND required_scope IS NULL+ )+ OR+ (+ credential_kind='api_key'+ AND bearer_subject IS NULL+ AND bearer_jti IS NULL+ AND bearer_expires_at IS NULL+ AND api_key_id IS NOT NULL+ AND length(trim(api_key_id)) > 0+ AND api_key_id=trim(api_key_id)+ AND required_scope='read'+ )+ """,+ name="ck_ws_ticket_source_shape",+ ),+ )+++def _create_sqlite_indexes(table: str) -> None:+ for name, columns in _SQLITE_INDEXES.get(table, {}).items():+ op.create_index(name, table, list(columns))+++def _copy_columns(bind: Any, table: str, source: str) -> None:+ names = [column[0] for column in _SQLITE_COLUMNS[table]]+ quoted = ", ".join(f'"{name}"' for name in names)+ selected = quoted+ if table == "credentials":+ source_columns = {+ str(row[1])+ for row in bind.exec_driver_sql(+ f'PRAGMA table_info("{source}")' # noqa: S608+ ).fetchall()+ }+ if (+ "cracked_value_enc" not in source_columns+ and "cracked_value" in source_columns+ ):+ selected = ", ".join(+ (+ '"cracked_value"'+ if name == "cracked_value_enc"+ else f'"{name}"'+ )+ for name in names+ )+ bind.exec_driver_sql( # noqa: S608+ f'INSERT INTO "{table}" ({quoted}) ' # noqa: S608+ f'SELECT {selected} FROM "{source}"'+ )+++def _sequence_values(bind: Any) -> dict[str, int]:+ exists = bind.execute(+ sa.text(+ "SELECT 1 FROM sqlite_master "+ "WHERE type='table' AND name='sqlite_sequence'"+ )+ ).first()+ if not exists:+ return {}+ rows = bind.execute(+ sa.text(+ "SELECT name, seq FROM sqlite_sequence "+ "WHERE name IN ('audit_log', 'rate_limit_events')"+ )+ ).fetchall()+ return {str(row[0]): int(row[1]) for row in rows}+++def _restore_sequences(bind: Any, sequences: dict[str, int]) -> None:+ for table, sequence in sequences.items():+ result = bind.execute(+ sa.text(+ "UPDATE sqlite_sequence SET seq=:sequence "+ "WHERE name=:name AND seq < :sequence"+ ),+ {"name": table, "sequence": sequence},+ )+ if result.rowcount == 0:+ current = bind.execute(+ sa.text(+ "SELECT seq FROM sqlite_sequence WHERE name=:name"+ ),+ {"name": table},+ ).scalar_one_or_none()+ if current is None:+ bind.execute(+ sa.text(+ "INSERT INTO sqlite_sequence(name, seq) "+ "VALUES(:name, :sequence)"+ ),+ {"name": table, "sequence": sequence},+ )+++def _sqlite_upgrade(bind: Any) -> None:+ # Alembic's SQLite implementation uses a logical per-revision+ # transaction, but SQLite does not emit BEGIN for DDL. An explicit+ # write transaction makes the reconciliation and Alembic's subsequent+ # version-row update one atomic unit. Alembic owns commit/rollback.+ bind.exec_driver_sql("BEGIN IMMEDIATE")+ exact = _sqlite_preflight(bind)+ if exact:+ return++ tables = set(sa.inspect(bind).get_table_names())+ ticket_before = _sqlite_ticket_snapshot(bind)+ sequences = _sequence_values(bind)+ row_counts = {+ table: int(+ bind.exec_driver_sql( # noqa: S608+ f'SELECT count(*) FROM "{table}"' # noqa: S608+ ).scalar_one()+ )+ for table in _REBUILD_ORDER+ if table in tables+ }++ bind.exec_driver_sql("PRAGMA defer_foreign_keys=ON")+ deferred = bind.exec_driver_sql(+ "PRAGMA defer_foreign_keys"+ ).scalar_one()+ if int(deferred) != 1:+ raise RuntimeError(_CATALOG_ERROR)++ existing = [table for table in _REBUILD_ORDER if table in tables]+ for table in existing:+ backup = f"{_TEMP_PREFIX}{table}"+ bind.exec_driver_sql( # noqa: S608+ f'CREATE TEMP TABLE "{backup}" AS SELECT * FROM "{table}"' # noqa: S608+ )+ for table in _DROP_ORDER:+ if table in existing:+ op.drop_table(table)++ for table in _REBUILD_ORDER:+ _create_sqlite_table(table)+ if table in existing:+ _copy_columns(bind, table, f"{_TEMP_PREFIX}{table}")+ _create_sqlite_indexes(table)++ _restore_sequences(bind, sequences)+ for table in existing:+ bind.exec_driver_sql(f'DROP TABLE "{_TEMP_PREFIX}{table}"')++ for table, expected_count in row_counts.items():+ current = int(+ bind.exec_driver_sql( # noqa: S608+ f'SELECT count(*) FROM "{table}"' # noqa: S608+ ).scalar_one()+ )+ if current != expected_count:+ raise RuntimeError(_DATA_ERROR)+ if _sqlite_ticket_snapshot(bind) != ticket_before:+ raise RuntimeError(_DATA_ERROR)+ if bind.exec_driver_sql("PRAGMA foreign_key_check").first():+ raise RuntimeError(_DATA_ERROR)+ if not _sqlite_preflight(bind):+ raise RuntimeError(_CATALOG_ERROR)+++_PG_FINITE_CHECKS: dict[str, dict[str, bool]] = {+ "campaigns": {"created_at": False, "updated_at": False},+ "module_runs": {"completed_at": False},+ "findings": {"discovered_at": False},+ "hosts": {"first_seen": False, "last_seen": False},+ "credentials": {"captured_at": False},+ "loot": {"captured_at": False},+ "audit_log": {"timestamp": False},+ "users": {"created_at": False, "last_login": True},+ "api_keys": {+ "last_used": True,+ "expires_at": True,+ "created_at": False,+ },+ "refresh_tokens": {+ "expires_at": False,+ "created_at": False,+ "used_at": True,+ },+ "rate_limit_events": {"timestamp": False},+ "revoked_access_tokens": {+ "revoked_at": False,+ "expires_at": False,+ },+}++_PG_FOREIGN_KEYS: dict[+ str,+ tuple[str, str, str, str, str],+] = {+ "fk_module_runs_campaign": (+ "module_runs",+ "campaign_id",+ "campaigns",+ "id",+ "CASCADE",+ ),+ "fk_findings_campaign": (+ "findings",+ "campaign_id",+ "campaigns",+ "id",+ "CASCADE",+ ),+ "fk_hosts_campaign": (+ "hosts",+ "campaign_id",+ "campaigns",+ "id",+ "CASCADE",+ ),+ "fk_credentials_campaign": (+ "credentials",+ "campaign_id",+ "campaigns",+ "id",+ "CASCADE",+ ),+ "fk_credentials_host": (+ "credentials",+ "host_id",+ "hosts",+ "id",+ "SET NULL",+ ),+ "fk_loot_campaign": (+ "loot",+ "campaign_id",+ "campaigns",+ "id",+ "CASCADE",+ ),+ "fk_loot_host": ("loot", "host_id", "hosts", "id", "SET NULL"),+ "fk_audit_campaign": (+ "audit_log",+ "campaign_id",+ "campaigns",+ "id",+ "SET NULL",+ ),+ "fk_api_keys_user": (+ "api_keys",+ "user_id",+ "users",+ "id",+ "CASCADE",+ ),+ "fk_refresh_tokens_user": (+ "refresh_tokens",+ "user_id",+ "users",+ "id",+ "CASCADE",+ ),+ "fk_ws_ticket_campaign": (+ "websocket_tickets",+ "campaign_id",+ "campaigns",+ "id",+ "CASCADE",+ ),+ "fk_ws_ticket_user": (+ "websocket_tickets",+ "user_id",+ "users",+ "id",+ "CASCADE",+ ),+ "fk_ws_ticket_api_key": (+ "websocket_tickets",+ "api_key_id",+ "api_keys",+ "id",+ "CASCADE",+ ),+}++_PG_UNIQUES: dict[str, tuple[str, tuple[str, ...]]] = {+ "uq_hosts_campaign_ip": ("hosts", ("campaign_id", "ip_address")),+ "uq_users_username": ("users", ("username",)),+}++_PG_PRIMARY_KEYS: dict[str, tuple[str, ...]] = {+ "campaigns": ("id",),+ "module_runs": ("id",),+ "findings": ("id",),+ "hosts": ("id",),+ "credentials": ("id",),+ "loot": ("id",),+ "audit_log": ("id",),+ "users": ("id",),+ "api_keys": ("id",),+ "refresh_tokens": ("id",),+ "rate_limit_events": ("id",),+ "revoked_access_tokens": ("jti",),+ "websocket_tickets": ("ticket_hash",),+}++_PG_RUNTIME_ALIASES: dict[str, tuple[str, str]] = {+ "idx_pg_module_runs_campaign": (+ "module_runs",+ "idx_module_runs_campaign",+ ),+ "idx_pg_module_runs_completed": (+ "module_runs",+ "idx_module_runs_completed",+ ),+ "idx_pg_findings_campaign": ("findings", "idx_findings_campaign"),+ "idx_pg_findings_severity": ("findings", "idx_findings_severity"),+ "idx_pg_findings_fp": ("findings", "idx_findings_fp"),+ "idx_pg_hosts_campaign": ("hosts", "idx_hosts_campaign"),+ "idx_pg_hosts_ip": ("hosts", "idx_hosts_ip"),+ "idx_pg_creds_campaign": ("credentials", "idx_creds_campaign"),+ "idx_pg_audit_campaign": ("audit_log", "idx_audit_campaign"),+ "idx_pg_users_username": ("users", "idx_users_username"),+ "idx_pg_apikeys_user": ("api_keys", "idx_apikeys_user"),+ "idx_pg_apikeys_prefix": ("api_keys", "idx_apikeys_prefix"),+ "idx_pg_refresh_user": ("refresh_tokens", "idx_refresh_user"),+ "idx_pg_refresh_exp": ("refresh_tokens", "idx_refresh_exp"),+ "idx_pg_rat_expires": (+ "revoked_access_tokens",+ "idx_rat_expires",+ ),+}++_PG_TICKET_CHECKS: dict[str, str] = {+ "ck_ws_ticket_bearer_expires_finite": (+ "CHECK (bearer_expires_at IS NULL "+ "OR isfinite(bearer_expires_at))"+ ),+ "ck_ws_ticket_consumed_at": (+ "CHECK (consumed_at IS NULL OR consumed_at < expires_at)"+ ),+ "ck_ws_ticket_consumed_finite": (+ "CHECK (consumed_at IS NULL OR isfinite(consumed_at))"+ ),+ "ck_ws_ticket_created_at": "CHECK (created_at < expires_at)",+ "ck_ws_ticket_created_finite": "CHECK (isfinite(created_at))",+ "ck_ws_ticket_expires_at": "CHECK (expires_at > created_at)",+ "ck_ws_ticket_expires_finite": "CHECK (isfinite(expires_at))",+ "ck_ws_ticket_hash": (+ "CHECK (ticket_hash ~ '^[0-9a-f]{64}$'::text)"+ ),+ "ck_ws_ticket_kind": (+ "CHECK (credential_kind = ANY "+ "(ARRAY['bearer'::text, 'api_key'::text]))"+ ),+ "ck_ws_ticket_source_shape": (+ "CHECK (credential_kind = 'bearer'::text "+ "AND bearer_subject IS NOT NULL "+ "AND length(btrim(bearer_subject)) > 0 "+ "AND bearer_subject = btrim(bearer_subject) "+ "AND bearer_jti IS NOT NULL "+ "AND length(btrim(bearer_jti)) > 0 "+ "AND bearer_jti = btrim(bearer_jti) "+ "AND bearer_expires_at IS NOT NULL "+ "AND api_key_id IS NULL "+ "AND required_scope IS NULL "+ "OR credential_kind = 'api_key'::text "+ "AND bearer_subject IS NULL "+ "AND bearer_jti IS NULL "+ "AND bearer_expires_at IS NULL "+ "AND api_key_id IS NOT NULL "+ "AND length(btrim(api_key_id)) > 0 "+ "AND api_key_id = btrim(api_key_id) "+ "AND required_scope = 'read'::text)"+ ),+ "ck_ws_ticket_time_order": (+ "CHECK (expires_at > created_at AND "+ "(consumed_at IS NULL OR consumed_at < expires_at))"+ ),+}++_PG_TICKET_TIMESTAMPS = frozenset(+ {+ "bearer_expires_at",+ "created_at",+ "expires_at",+ "consumed_at",+ }+)++_PG_FINDINGS_RUNTIME_ORDER = (+ "id",+ "campaign_id",+ "module_id",+ "title",+ "description",+ "severity",+ "confidence",+ "mitre_technique",+ "mitre_tactic",+ "cvss_score",+ "cvss_vector",+ "trace_id",+ "evidence_json",+ "remediation",+ "host",+ "validated",+ "false_positive",+ "discovered_at",+)++_PG_SERIAL_DEFAULTS = {+ ("audit_log", "id"): "nextval('audit_log_id_seq'::regclass)",+ (+ "rate_limit_events",+ "id",+ ): "nextval('rate_limit_events_id_seq'::regclass)",+}++_PG_AUDITED_FAST_DEFAULTS = {+ ("findings", "cvss_score"): "{0}",+ ("findings", "cvss_vector"): '{""}',+ ("findings", "trace_id"): '{""}',+}++_PG_REQUIRED_TABLES = frozenset(+ {+ "campaigns",+ "findings",+ "hosts",+ "credentials",+ "loot",+ "audit_log",+ "users",+ "api_keys",+ "refresh_tokens",+ "revoked_access_tokens",+ "websocket_tickets",+ }+)++_PG_OPTIONAL_TABLES = frozenset({"module_runs", "rate_limit_events"})+++def _pg_check_name(table: str, column: str) -> str:+ if table == "rate_limit_events":+ return "ck_rate_limit_events_timestamp_finite"+ if table == "revoked_access_tokens":+ return f"ck_revoked_access_tokens_{column}_finite"+ if table == "audit_log":+ return "ck_audit_log_timestamp_finite"+ if table == "module_runs":+ return "ck_module_runs_completed_at_finite"+ return f"ck_{table}_{column}_finite"+++def _pg_validate_alembic_version_relation(bind: Any) -> None:+ relation_rows = list(+ bind.execute(+ sa.text(+ """+ SELECT+ relation.oid::bigint AS relation_oid,+ namespace.nspname AS relation_schema,+ relation_type.oid::bigint AS type_oid,+ type_namespace.nspname AS type_schema,+ relation_type.typname AS type_name,+ relation_type.typtype,+ relation_type.typrelid::bigint AS type_relation_oid,+ relation.relkind,+ relation.relpersistence,+ relation.relispartition,+ relation.relrowsecurity,+ relation.relforcerowsecurity,+ (+ SELECT count(*)+ FROM pg_inherits+ WHERE inhrelid=relation.oid+ ) AS parent_count,+ (+ SELECT count(*)+ FROM pg_inherits+ WHERE inhparent=relation.oid+ ) AS child_count,+ (+ SELECT count(*)+ FROM pg_policy+ WHERE polrelid=relation.oid+ ) AS policy_count,+ (+ SELECT count(*)+ FROM pg_trigger+ WHERE tgrelid=relation.oid+ AND NOT tgisinternal+ ) AS user_trigger_count,+ (+ SELECT count(*)+ FROM pg_rewrite+ WHERE ev_class=relation.oid+ ) AS user_rule_count+ FROM pg_class AS relation+ JOIN pg_namespace AS namespace+ ON namespace.oid=relation.relnamespace+ LEFT JOIN pg_type AS relation_type+ ON relation_type.oid=relation.reltype+ LEFT JOIN pg_namespace AS type_namespace+ ON type_namespace.oid=relation_type.typnamespace+ WHERE namespace.nspname=current_schema()+ AND relation.relname='alembic_version'+ """+ )+ ).mappings()+ )+ if len(relation_rows) != 1:+ raise RuntimeError(_CATALOG_ERROR)+ relation = relation_rows[0]+ try:+ relation_oid = int(relation["relation_oid"])+ type_oid = int(relation["type_oid"])+ schema = relation["relation_schema"]+ type_contract = (+ relation["type_schema"],+ relation["type_name"],+ str(relation["typtype"]),+ int(relation["type_relation_oid"]),+ )+ relation_contract = (+ str(relation["relkind"]),+ str(relation["relpersistence"]),+ bool(relation["relispartition"]),+ bool(relation["relrowsecurity"]),+ bool(relation["relforcerowsecurity"]),+ int(relation["parent_count"]),+ int(relation["child_count"]),+ int(relation["policy_count"]),+ int(relation["user_trigger_count"]),+ int(relation["user_rule_count"]),+ )+ except (KeyError, TypeError, ValueError):+ raise RuntimeError(_CATALOG_ERROR) from None+ if (+ relation_oid <= 0+ or type_oid <= 0+ or not isinstance(schema, str)+ or not schema+ or type_contract != (schema, "alembic_version", "c", relation_oid)+ or relation_contract+ != ("r", "p", False, False, False, 0, 0, 0, 0, 0)+ ):+ raise RuntimeError(_CATALOG_ERROR)++ column_rows = list(+ bind.execute(+ sa.text(+ """+ SELECT+ attribute.attnum,+ attribute.attname AS column_name,+ pg_catalog.format_type(+ attribute.atttypid,+ attribute.atttypmod+ ) AS data_type,+ attribute.attnotnull,+ attribute.attidentity,+ attribute.attgenerated,+ attribute.attisdropped,+ attribute.attinhcount,+ attribute.attislocal,+ attribute.atthasmissing,+ attribute.attmissingval::text AS missing_value,+ attribute.attcollation=type_record.typcollation+ AS collation_is_default,+ pg_get_expr(+ default_record.adbin,+ default_record.adrelid+ ) AS column_default+ FROM pg_attribute AS attribute+ LEFT JOIN pg_type AS type_record+ ON type_record.oid=attribute.atttypid+ LEFT JOIN pg_attrdef AS default_record+ ON default_record.adrelid=attribute.attrelid+ AND default_record.adnum=attribute.attnum+ WHERE attribute.attrelid=:relation_oid+ AND attribute.attnum > 0+ ORDER BY attribute.attnum+ """+ ),+ {"relation_oid": relation_oid},+ ).mappings()+ )+ try:+ column_contract = tuple(+ (+ int(row["attnum"]),+ str(row["column_name"]),+ str(row["data_type"]),+ bool(row["attnotnull"]),+ str(row["attidentity"]),+ str(row["attgenerated"]),+ bool(row["attisdropped"]),+ int(row["attinhcount"]),+ bool(row["attislocal"]),+ bool(row["atthasmissing"]),+ row["missing_value"],+ bool(row["collation_is_default"]),+ row["column_default"],+ )+ for row in column_rows+ )+ except (KeyError, TypeError, ValueError):+ raise RuntimeError(_CATALOG_ERROR) from None+ if column_contract != (+ (+ 1,+ "version_num",+ "character varying(32)",+ True,+ "",+ "",+ False,+ 0,+ True,+ False,+ None,+ True,+ None,+ ),+ ):+ raise RuntimeError(_CATALOG_ERROR)++ constraint_rows = list(+ bind.execute(+ sa.text(+ """+ SELECT+ constraint_record.oid::bigint AS constraint_oid,+ constraint_record.conname AS constraint_name,+ constraint_record.contype,+ constraint_record.convalidated,+ constraint_record.condeferrable,+ constraint_record.condeferred,+ constraint_record.conindid::bigint AS index_oid,+ ARRAY(+ SELECT attribute.attname+ FROM unnest(constraint_record.conkey)+ WITH ORDINALITY AS key(attnum, position)+ JOIN pg_attribute AS attribute+ ON attribute.attrelid=constraint_record.conrelid+ AND attribute.attnum=key.attnum+ ORDER BY key.position+ ) AS columns+ FROM pg_constraint AS constraint_record+ WHERE constraint_record.conrelid=:relation_oid+ ORDER BY constraint_record.conname+ """+ ),+ {"relation_oid": relation_oid},+ ).mappings()+ )+ try:+ constraint_contract = tuple(+ (+ int(row["constraint_oid"]),+ str(row["constraint_name"]),+ str(row["contype"]),+ bool(row["convalidated"]),+ bool(row["condeferrable"]),+ bool(row["condeferred"]),+ int(row["index_oid"]),+ tuple(str(column) for column in row["columns"]),+ )+ for row in constraint_rows+ )+ except (KeyError, TypeError, ValueError):+ raise RuntimeError(_CATALOG_ERROR) from None+ if (+ len(constraint_contract) != 1+ or constraint_contract[0][0] <= 0+ or constraint_contract[0][6] <= 0+ or constraint_contract[0][1:]+ != (+ "alembic_version_pkc",+ "p",+ True,+ False,+ False,+ constraint_contract[0][6],+ ("version_num",),+ )+ ):+ raise RuntimeError(_CATALOG_ERROR)+ primary_constraint_oid = constraint_contract[0][0]+ primary_index_oid = constraint_contract[0][6]++ index_rows = list(+ bind.execute(+ sa.text(+ """+ SELECT+ index_record.oid::bigint AS index_oid,+ index_record.relname AS index_name,+ index_namespace.nspname AS index_schema,+ index_record.relkind AS index_relkind,+ index_record.relpersistence AS index_relpersistence,+ index_record.relispartition AS index_is_partition,+ access_method.amname AS access_method,+ index_definition.indrelid::bigint AS table_oid,+ index_definition.indisunique,+ index_definition.indisprimary,+ index_definition.indisvalid,+ index_definition.indisready,+ index_definition.indislive,+ index_definition.indnkeyatts,+ index_definition.indnatts,+ constraint_record.oid::bigint AS constraint_oid,+ constraint_record.conname AS constraint_name,+ constraint_record.contype,+ ARRAY(+ SELECT attribute.attname+ FROM unnest(index_definition.indkey)+ WITH ORDINALITY AS key(attnum, position)+ LEFT JOIN pg_attribute AS attribute+ ON attribute.attrelid=index_definition.indrelid+ AND attribute.attnum=key.attnum+ ORDER BY key.position+ ) AS columns,+ ARRAY(+ SELECT option+ FROM unnest(index_definition.indoption)+ WITH ORDINALITY AS item(option, position)+ ORDER BY item.position+ ) AS column_options,+ ARRAY(+ SELECT operator_class.opcname+ FROM unnest(index_definition.indclass)+ WITH ORDINALITY AS item(opclass, position)+ JOIN pg_opclass AS operator_class+ ON operator_class.oid=item.opclass+ ORDER BY item.position+ ) AS operator_classes,+ ARRAY(+ SELECT operator_namespace.nspname+ FROM unnest(index_definition.indclass)+ WITH ORDINALITY AS item(opclass, position)+ JOIN pg_opclass AS operator_class+ ON operator_class.oid=item.opclass+ JOIN pg_namespace AS operator_namespace+ ON operator_namespace.oid=+ operator_class.opcnamespace+ ORDER BY item.position+ ) AS operator_class_namespaces,+ ARRAY(+ SELECT item.collation=attribute.attcollation+ FROM unnest(index_definition.indcollation)+ WITH ORDINALITY AS item(collation, position)+ JOIN unnest(index_definition.indkey)+ WITH ORDINALITY AS key(attnum, position)+ ON key.position=item.position+ LEFT JOIN pg_attribute AS attribute+ ON attribute.attrelid=index_definition.indrelid+ AND attribute.attnum=key.attnum+ ORDER BY item.position+ ) AS column_collations_match,+ pg_get_expr(+ index_definition.indexprs,+ index_definition.indrelid+ ) AS expressions,+ pg_get_expr(+ index_definition.indpred,+ index_definition.indrelid+ ) AS predicate+ FROM pg_index AS index_definition+ JOIN pg_class AS index_record+ ON index_record.oid=index_definition.indexrelid+ JOIN pg_namespace AS index_namespace+ ON index_namespace.oid=index_record.relnamespace+ JOIN pg_am AS access_method+ ON access_method.oid=index_record.relam+ LEFT JOIN pg_constraint AS constraint_record+ ON constraint_record.conindid=index_definition.indexrelid+ AND constraint_record.conrelid=index_definition.indrelid+ WHERE index_definition.indrelid=:relation_oid+ ORDER BY index_record.relname+ """+ ),+ {"relation_oid": relation_oid},+ ).mappings()+ )+ try:+ index_contract = tuple(+ (+ int(row["index_oid"]),+ str(row["index_name"]),+ row["index_schema"],+ str(row["index_relkind"]),+ str(row["index_relpersistence"]),+ bool(row["index_is_partition"]),+ str(row["access_method"]),+ int(row["table_oid"]),+ bool(row["indisunique"]),+ bool(row["indisprimary"]),+ bool(row["indisvalid"]),+ bool(row["indisready"]),+ bool(row["indislive"]),+ int(row["indnkeyatts"]),+ int(row["indnatts"]),+ int(row["constraint_oid"]),+ row["constraint_name"],+ row["contype"],+ tuple(str(column) for column in row["columns"]),+ tuple(int(option) for option in row["column_options"]),+ tuple(str(value) for value in row["operator_classes"]),+ tuple(+ str(value)+ for value in row["operator_class_namespaces"]+ ),+ tuple(+ bool(value)+ for value in row["column_collations_match"]+ ),+ row["expressions"],+ row["predicate"],+ )+ for row in index_rows+ )+ except (KeyError, TypeError, ValueError):+ raise RuntimeError(_CATALOG_ERROR) from None+ if index_contract != (+ (+ primary_index_oid,+ "alembic_version_pkc",+ schema,+ "i",+ "p",+ False,+ "btree",+ relation_oid,+ True,+ True,+ True,+ True,+ True,+ 1,+ 1,+ primary_constraint_oid,+ "alembic_version_pkc",+ "p",+ ("version_num",),+ (0,),+ ("text_ops",),+ ("pg_catalog",),+ (True,),+ None,+ None,+ ),+ ):+ raise RuntimeError(_CATALOG_ERROR)+ quoted_schema = '"' + schema.replace('"', '""') + '"'+ values = tuple(+ str(row[0])+ for row in bind.exec_driver_sql(+ f'SELECT version_num FROM {quoted_schema}."alembic_version"' # noqa: S608+ ).fetchall()+ )+ if values != ("0007",):+ raise RuntimeError(_CATALOG_ERROR)+++def _pg_relation_rows(bind: Any) -> list[dict[str, object]]:+ return list(+ bind.execute(+ sa.text(+ """+ SELECT+ relation.oid::bigint AS relation_oid,+ relation.relname AS table_name,+ relation.relkind,+ relation.relpersistence,+ relation.relispartition,+ relation.relrowsecurity,+ relation.relforcerowsecurity,+ (+ SELECT count(*)+ FROM pg_inherits+ WHERE inhrelid=relation.oid+ ) AS parent_count,+ (+ SELECT count(*)+ FROM pg_inherits+ WHERE inhparent=relation.oid+ ) AS child_count,+ (+ SELECT count(*)+ FROM pg_policy+ WHERE polrelid=relation.oid+ ) AS policy_count,+ (+ SELECT count(*)+ FROM pg_trigger+ WHERE tgrelid=relation.oid+ AND NOT tgisinternal+ ) AS user_trigger_count,+ (+ SELECT count(*)+ FROM pg_rewrite+ WHERE ev_class=relation.oid+ ) AS user_rule_count+ FROM pg_class AS relation+ JOIN pg_namespace AS namespace+ ON namespace.oid=relation.relnamespace+ WHERE namespace.nspname=current_schema()+ AND relation.relname IN (+ 'campaigns',+ 'module_runs',+ 'findings',+ 'hosts',+ 'credentials',+ 'loot',+ 'audit_log',+ 'users',+ 'api_keys',+ 'refresh_tokens',+ 'rate_limit_events',+ 'revoked_access_tokens',+ 'websocket_tickets'+ )+ """+ )+ ).mappings()+ )+++def _pg_validate_relation_shapes(bind: Any) -> set[str]:+ rows = _pg_relation_rows(bind)+ relations = {+ str(row["table_name"]): row+ for row in rows+ }+ if len(relations) != len(rows):+ raise RuntimeError(_CATALOG_ERROR)+ tables = set(relations)+ if not _PG_REQUIRED_TABLES.issubset(tables):+ raise RuntimeError(_CATALOG_ERROR)+ if not tables.issubset(_PG_REQUIRED_TABLES | _PG_OPTIONAL_TABLES):+ raise RuntimeError(_CATALOG_ERROR)+ expected = ("r", "p", False, False, False, 0, 0, 0, 0, 0)+ for row in relations.values():+ actual = (+ str(row["relkind"]),+ str(row["relpersistence"]),+ bool(row["relispartition"]),+ bool(row["relrowsecurity"]),+ bool(row["relforcerowsecurity"]),+ int(row["parent_count"]),+ int(row["child_count"]),+ int(row["policy_count"]),+ int(row["user_trigger_count"]),+ int(row["user_rule_count"]),+ )+ if actual != expected:+ raise RuntimeError(_CATALOG_ERROR)++ type_rows = list(+ bind.execute(+ sa.text(+ """+ SELECT+ type_record.typname AS type_name,+ type_record.typtype,+ type_record.typrelid::bigint AS type_relation_oid,+ namespace.nspname AS type_schema+ FROM pg_type AS type_record+ JOIN pg_namespace AS namespace+ ON namespace.oid=type_record.typnamespace+ WHERE namespace.nspname=current_schema()+ AND type_record.typname IN (+ 'campaigns',+ 'module_runs',+ 'findings',+ 'hosts',+ 'credentials',+ 'loot',+ 'audit_log',+ 'users',+ 'api_keys',+ 'refresh_tokens',+ 'rate_limit_events',+ 'revoked_access_tokens',+ 'websocket_tickets'+ )+ ORDER BY type_record.typname+ """+ )+ ).mappings()+ )+ type_contracts = {+ str(row["type_name"]): row+ for row in type_rows+ }+ if len(type_contracts) != len(type_rows) or set(type_contracts) != tables:+ raise RuntimeError(_CATALOG_ERROR)+ for table, relation in relations.items():+ type_row = type_contracts[table]+ if (+ str(type_row["typtype"]) != "c"+ or int(type_row["type_relation_oid"])+ != int(relation["relation_oid"])+ or not isinstance(type_row["type_schema"], str)+ or not type_row["type_schema"]+ ):+ raise RuntimeError(_CATALOG_ERROR)+ return tables+++def _pg_column_rows(bind: Any) -> list[dict[str, object]]:+ return list(+ bind.execute(+ sa.text(+ """+ SELECT+ relation.relname AS table_name,+ attribute.attnum,+ attribute.attname AS column_name,+ format_type(+ attribute.atttypid,+ attribute.atttypmod+ ) AS data_type,+ attribute.attnotnull,+ attribute.attidentity,+ attribute.attgenerated,+ attribute.attisdropped,+ attribute.attinhcount,+ attribute.attislocal,+ attribute.atthasmissing,+ attribute.attmissingval::text AS missing_value,+ (+ attribute.attcollation=+ type_record.typcollation+ ) AS collation_is_default,+ pg_get_expr(+ default_record.adbin,+ default_record.adrelid+ ) AS column_default+ FROM pg_class AS relation+ JOIN pg_namespace AS namespace+ ON namespace.oid=relation.relnamespace+ JOIN pg_attribute AS attribute+ ON attribute.attrelid=relation.oid+ JOIN pg_type AS type_record+ ON type_record.oid=attribute.atttypid+ LEFT JOIN pg_attrdef AS default_record+ ON default_record.adrelid=relation.oid+ AND default_record.adnum=attribute.attnum+ WHERE namespace.nspname=current_schema()+ AND relation.relname IN (+ 'campaigns',+ 'module_runs',+ 'findings',+ 'hosts',+ 'credentials',+ 'loot',+ 'audit_log',+ 'users',+ 'api_keys',+ 'refresh_tokens',+ 'rate_limit_events',+ 'revoked_access_tokens',+ 'websocket_tickets'+ )+ AND attribute.attnum > 0+ ORDER BY relation.relname, attribute.attnum+ """+ )+ ).mappings()+ )+++def _pg_column_type(table: str, column: _Column) -> str:+ name, kind, _nullable, _default, _primary_key = column+ if (+ name in _PG_FINITE_CHECKS.get(table, {})+ or (+ table == "websocket_tickets"+ and name in _PG_TICKET_TIMESTAMPS+ )+ ):+ return "timestamp with time zone"+ if kind == "TEXT":+ return "text"+ if kind == "INTEGER":+ return "integer"+ if kind == "FLOAT":+ return "double precision"+ raise RuntimeError(_CATALOG_ERROR)+++def _pg_column_default(+ table: str,+ column: _Column,+) -> str | None:+ name, _kind, _nullable, default, _primary_key = column+ serial_default = _PG_SERIAL_DEFAULTS.get((table, name))+ if serial_default is not None:+ return serial_default+ if default == "datetime('now')":+ return "now()"+ return default+++def _pg_expected_columns(+ table: str,+ *,+ source_credentials: bool = False,+) -> tuple[_Column, ...]:+ columns = _SQLITE_COLUMNS[table]+ if not source_credentials:+ return columns+ return tuple(+ (+ "cracked_value" if column[0] == "cracked_value_enc" else column[0],+ *column[1:],+ )+ for column in columns+ )+++def _pg_validate_column_metadata(+ table: str,+ rows: list[dict[str, object]],+ expected: tuple[_Column, ...],+) -> list[tuple[str, sa.types.TypeEngine, str]]:+ if len(rows) != len(expected):+ raise RuntimeError(_CATALOG_ERROR)+ alterations: list[tuple[str, sa.types.TypeEngine, str]] = []+ for position, (row, column) in enumerate(+ zip(rows, expected, strict=True),+ start=1,+ ):+ name, _kind, nullable, _default, _primary_key = column+ actual_nullable = not bool(row["attnotnull"])+ nullable_matches = actual_nullable == nullable+ if (+ table == "findings"+ and name in {"cvss_score", "cvss_vector", "trace_id"}+ and actual_nullable+ and not nullable+ ):+ nullable_matches = True+ kind: sa.types.TypeEngine+ default: str+ if name == "cvss_score":+ kind = sa.Float()+ default = "0.0"+ else:+ kind = sa.Text()+ default = ""+ alterations.append((name, kind, default))+ actual_default = _normalize_default(row["column_default"])+ expected_default = _normalize_default(+ _pg_column_default(table, column)+ )+ has_missing = bool(row["atthasmissing"])+ missing_value = row["missing_value"]+ expected_missing = _PG_AUDITED_FAST_DEFAULTS.get((table, name))+ missing_metadata_matches = (+ (+ has_missing+ and expected_missing is not None+ and str(missing_value) == expected_missing+ )+ or (not has_missing and missing_value is None)+ )+ if (+ int(row["attnum"]) != position+ or str(row["column_name"]) != name+ or str(row["data_type"]).lower()+ != _pg_column_type(table, column)+ or not nullable_matches+ or actual_default != expected_default+ or str(row["attidentity"])+ or str(row["attgenerated"])+ or bool(row["attisdropped"])+ or int(row["attinhcount"]) != 0+ or not bool(row["attislocal"])+ or not missing_metadata_matches+ or not bool(row["collation_is_default"])+ ):+ raise RuntimeError(_CATALOG_ERROR)+ return alterations+++def _pg_validate_columns(+ bind: Any,+ tables: set[str],+) -> tuple[+ list[tuple[str, sa.types.TypeEngine, str]],+ bool,+]:+ by_table: dict[str, list[dict[str, object]]] = {}+ for row in _pg_column_rows(bind):+ by_table.setdefault(str(row["table_name"]), []).append(row)+ if set(by_table) != tables:+ raise RuntimeError(_CATALOG_ERROR)++ findings_alterations: list[+ tuple[str, sa.types.TypeEngine, str]+ ] = []+ rename_credentials = False+ for table in tables:+ rows = by_table[table]+ names = tuple(str(row["column_name"]) for row in rows)+ expected = _pg_expected_columns(table)+ expected_names = tuple(column[0] for column in expected)+ if table == "findings":+ if names not in {+ expected_names,+ _PG_FINDINGS_RUNTIME_ORDER,+ }:+ raise RuntimeError(_CATALOG_ERROR)+ by_name = {column[0]: column for column in expected}+ expected = tuple(by_name[name] for name in names)+ elif table == "credentials":+ source_expected = _pg_expected_columns(+ table,+ source_credentials=True,+ )+ source_names = tuple(column[0] for column in source_expected)+ if names == source_names:+ expected = source_expected+ rename_credentials = True+ elif names != expected_names:+ raise RuntimeError(_CATALOG_ERROR)+ elif names != expected_names:+ raise RuntimeError(_CATALOG_ERROR)++ alterations = _pg_validate_column_metadata(+ table,+ rows,+ expected,+ )+ if table == "findings":+ findings_alterations = alterations+ elif alterations:+ raise RuntimeError(_CATALOG_ERROR)+ return findings_alterations, rename_credentials+++def _pg_validate_serial_sequences(+ bind: Any,+ tables: set[str],+) -> None:+ rows = list(+ bind.execute(+ sa.text(+ """+ SELECT+ namespace.nspname AS sequence_schema,+ sequence_record.relname AS sequence_name,+ sequence_record.relkind,+ sequence_record.relpersistence,+ format_type(+ sequence_definition.seqtypid,+ NULL+ ) AS data_type,+ sequence_definition.seqstart,+ sequence_definition.seqincrement,+ sequence_definition.seqmax,+ sequence_definition.seqmin,+ sequence_definition.seqcache,+ sequence_definition.seqcycle,+ owner_namespace.nspname AS owner_schema,+ owner_table.relname AS owner_table,+ owner_column.attname AS owner_column,+ dependency.deptype+ FROM pg_class AS sequence_record+ JOIN pg_namespace AS namespace+ ON namespace.oid=sequence_record.relnamespace+ JOIN pg_sequence AS sequence_definition+ ON sequence_definition.seqrelid=sequence_record.oid+ LEFT JOIN pg_depend AS dependency+ ON dependency.classid='pg_class'::regclass+ AND dependency.objid=sequence_record.oid+ AND dependency.objsubid=0+ AND dependency.refclassid='pg_class'::regclass+ AND dependency.deptype IN ('a', 'i')+ LEFT JOIN pg_class AS owner_table+ ON owner_table.oid=dependency.refobjid+ LEFT JOIN pg_namespace AS owner_namespace+ ON owner_namespace.oid=owner_table.relnamespace+ LEFT JOIN pg_attribute AS owner_column+ ON owner_column.attrelid=dependency.refobjid+ AND owner_column.attnum=dependency.refobjsubid+ WHERE namespace.nspname=current_schema()+ AND sequence_record.relname IN (+ 'audit_log_id_seq',+ 'rate_limit_events_id_seq'+ )+ ORDER BY sequence_record.relname+ """+ )+ ).mappings()+ )+ expected = {+ "audit_log_id_seq": ("audit_log", "id"),+ }+ if "rate_limit_events" in tables:+ expected["rate_limit_events_id_seq"] = (+ "rate_limit_events",+ "id",+ )+ if len(rows) != len(expected):+ raise RuntimeError(_CATALOG_ERROR)+ seen: set[str] = set()+ for row in rows:+ name = str(row["sequence_name"])+ owner = expected.get(name)+ if (+ owner is None+ or name in seen+ or (+ str(row["relkind"]),+ str(row["relpersistence"]),+ str(row["data_type"]),+ int(row["seqstart"]),+ int(row["seqincrement"]),+ int(row["seqmax"]),+ int(row["seqmin"]),+ int(row["seqcache"]),+ bool(row["seqcycle"]),+ str(row["owner_schema"]),+ str(row["owner_table"]),+ str(row["owner_column"]),+ str(row["deptype"]),+ )+ != (+ "S",+ "p",+ "integer",+ 1,+ 1,+ 2147483647,+ 1,+ 1,+ False,+ str(row["sequence_schema"]),+ owner[0],+ owner[1],+ "a",+ )+ ):+ raise RuntimeError(_CATALOG_ERROR)+ seen.add(name)+++def _pg_constraint_rows(bind: Any) -> list[dict[str, object]]:+ return list(+ bind.execute(+ sa.text(+ """+ SELECT+ relation.relname AS table_name,+ constraint_record.conname AS constraint_name,+ constraint_record.contype AS constraint_type,+ constraint_record.convalidated AS is_validated,+ constraint_record.condeferrable AS is_deferrable,+ constraint_record.condeferred AS is_deferred,+ pg_get_constraintdef(+ constraint_record.oid,+ true+ ) AS definition+ FROM pg_constraint AS constraint_record+ JOIN pg_class AS relation+ ON relation.oid=constraint_record.conrelid+ JOIN pg_namespace AS namespace+ ON namespace.oid=relation.relnamespace+ WHERE namespace.nspname=current_schema()+ """+ )+ ).mappings()+ )+++def _pg_index_rows(bind: Any) -> list[dict[str, object]]:+ return list(+ bind.execute(+ sa.text(+ """+ SELECT+ table_record.relname AS table_name,+ index_record.relname AS index_name,+ index_record.relkind AS index_relkind,+ index_record.relpersistence AS index_relpersistence,+ index_record.relispartition AS index_is_partition,+ access_method.amname AS access_method,+ index_definition.indisunique AS is_unique,+ index_definition.indisprimary AS is_primary,+ index_definition.indisvalid AS is_valid,+ index_definition.indisready AS is_ready,+ index_definition.indislive AS is_live,+ index_definition.indnkeyatts,+ index_definition.indnatts,+ ARRAY(+ SELECT attribute.attname+ FROM unnest(index_definition.indkey)+ WITH ORDINALITY AS key(attnum, position)+ LEFT JOIN pg_attribute AS attribute+ ON attribute.attrelid=index_definition.indrelid+ AND attribute.attnum=key.attnum+ ORDER BY key.position+ ) AS columns,+ ARRAY(+ SELECT option+ FROM unnest(index_definition.indoption)+ WITH ORDINALITY AS item(option, position)+ ORDER BY item.position+ ) AS column_options,+ ARRAY(+ SELECT operator_class.opcname+ FROM unnest(index_definition.indclass)+ WITH ORDINALITY AS item(opclass, position)+ JOIN pg_opclass AS operator_class+ ON operator_class.oid=item.opclass+ ORDER BY item.position+ ) AS operator_classes,+ ARRAY(+ SELECT namespace_record.nspname+ FROM unnest(index_definition.indclass)+ WITH ORDINALITY AS item(opclass, position)+ JOIN pg_opclass AS operator_class+ ON operator_class.oid=item.opclass+ JOIN pg_namespace AS namespace_record+ ON namespace_record.oid=+ operator_class.opcnamespace+ ORDER BY item.position+ ) AS operator_class_namespaces,+ ARRAY(+ SELECT item.collation=attribute.attcollation+ FROM unnest(index_definition.indcollation)+ WITH ORDINALITY AS item(collation, position)+ JOIN unnest(index_definition.indkey)+ WITH ORDINALITY AS key(attnum, position)+ ON key.position=item.position+ LEFT JOIN pg_attribute AS attribute+ ON attribute.attrelid=index_definition.indrelid+ AND attribute.attnum=key.attnum+ ORDER BY item.position+ ) AS column_collations_match,+ pg_get_expr(+ index_definition.indexprs,+ index_definition.indrelid+ ) AS expressions,+ pg_get_expr(+ index_definition.indpred,+ index_definition.indrelid+ ) AS predicate+ FROM pg_index AS index_definition+ JOIN pg_class AS table_record+ ON table_record.oid=index_definition.indrelid+ JOIN pg_class AS index_record+ ON index_record.oid=index_definition.indexrelid+ JOIN pg_namespace AS namespace+ ON namespace.oid=table_record.relnamespace+ JOIN pg_am AS access_method+ ON access_method.oid=index_record.relam+ LEFT JOIN pg_constraint AS constraint_record+ ON constraint_record.conindid=index_definition.indexrelid+ WHERE namespace.nspname=current_schema()+ AND constraint_record.oid IS NULL+ """+ )+ ).mappings()+ )+++def _pg_reject_reserved_index_collisions(+ bind: Any,+ tables: set[str],+) -> None:+ rows = list(+ bind.execute(+ sa.text(+ """+ SELECT+ named_record.relname AS reserved_name,+ namespace.nspname AS reserved_schema,+ named_record.relkind,+ index_definition.indexrelid IS NOT NULL AS is_index,+ table_namespace.nspname AS table_schema,+ table_record.relname AS table_name,+ ARRAY(+ SELECT constraint_record.contype::text+ FROM pg_constraint AS constraint_record+ WHERE constraint_record.conindid=named_record.oid+ AND constraint_record.conrelid=table_record.oid+ ORDER BY constraint_record.oid+ ) AS owner_constraint_types+ FROM pg_class AS named_record+ JOIN pg_namespace AS namespace+ ON namespace.oid=named_record.relnamespace+ LEFT JOIN pg_index AS index_definition+ ON index_definition.indexrelid=named_record.oid+ LEFT JOIN pg_class AS table_record+ ON table_record.oid=index_definition.indrelid+ LEFT JOIN pg_namespace AS table_namespace+ ON table_namespace.oid=table_record.relnamespace+ WHERE namespace.nspname=current_schema()+ ORDER BY named_record.relname+ """+ )+ ).mappings()+ )+ canonical = {+ name: table+ for table, indexes in _SQLITE_INDEXES.items()+ if table != "schema_version"+ for name in indexes+ }+ aliases = {+ alias: table+ for alias, (table, _canonical) in _PG_RUNTIME_ALIASES.items()+ }+ plain_indexes = canonical | aliases+ plain_indexes["idx_findings_validated"] = "findings"+ primary_indexes = {+ f"{table}_pkey": table+ for table in _PG_PRIMARY_KEYS+ }+ unique_indexes = {+ name: table+ for name, (table, _columns) in _PG_UNIQUES.items()+ }+ sequences = {+ "audit_log_id_seq": "audit_log",+ "rate_limit_events_id_seq": "rate_limit_events",+ }+ for row in rows:+ name = str(row["reserved_name"])+ relation_contract = (+ str(row["relkind"]),+ bool(row["is_index"]),+ row["table_schema"],+ row["table_name"],+ tuple(+ str(value)+ for value in (row["owner_constraint_types"] or ())+ ),+ )+ if name in plain_indexes:+ expected_table = plain_indexes[name]+ if relation_contract != (+ "i",+ True,+ str(row["reserved_schema"]),+ expected_table,+ (),+ ):+ raise RuntimeError(_CATALOG_ERROR)+ elif name in primary_indexes:+ expected_table = primary_indexes[name]+ if expected_table not in tables or relation_contract != (+ "i",+ True,+ str(row["reserved_schema"]),+ expected_table,+ ("p",),+ ):+ raise RuntimeError(_CATALOG_ERROR)+ elif name in unique_indexes:+ expected_table = unique_indexes[name]+ if expected_table not in tables or relation_contract != (+ "i",+ True,+ str(row["reserved_schema"]),+ expected_table,+ ("u",),+ ):+ raise RuntimeError(_CATALOG_ERROR)+ elif name in sequences:+ expected_table = sequences[name]+ if expected_table not in tables or relation_contract != (+ "S",+ False,+ None,+ None,+ (),+ ):+ raise RuntimeError(_CATALOG_ERROR)+++def _pg_index_opclass(table: str, column: str) -> str:+ if (table, column) in {+ ("findings", "cvss_score"),+ }:+ return "float8_ops"+ if (table, column) in {+ ("findings", "false_positive"),+ ("rate_limit_events", "blocked"),+ }:+ return "int4_ops"+ if (table, column) in {+ ("module_runs", "completed_at"),+ ("rate_limit_events", "timestamp"),+ ("refresh_tokens", "expires_at"),+ ("revoked_access_tokens", "expires_at"),+ ("websocket_tickets", "expires_at"),+ }:+ return "timestamptz_ops"+ return "text_ops"+++def _pg_index_contract(+ row: dict[str, object],+) -> tuple[object, ...]:+ columns = tuple(str(value) for value in (row["columns"] or ()))+ return (+ str(row["index_relkind"]),+ str(row["index_relpersistence"]),+ bool(row["index_is_partition"]),+ str(row["access_method"]),+ bool(row["is_unique"]),+ bool(row["is_primary"]),+ bool(row["is_valid"]),+ bool(row["is_ready"]),+ bool(row["is_live"]),+ int(row["indnkeyatts"]),+ int(row["indnatts"]),+ columns,+ tuple(int(value) for value in (row["column_options"] or ())),+ tuple(str(value) for value in (row["operator_classes"] or ())),+ tuple(+ str(value)+ for value in (row["operator_class_namespaces"] or ())+ ),+ tuple(+ bool(value)+ for value in (row["column_collations_match"] or ())+ ),+ row["expressions"],+ row["predicate"],+ )+++def _expected_pg_index(+ table: str,+ columns: tuple[str, ...],+) -> tuple[object, ...]:+ count = len(columns)+ return (+ "i",+ "p",+ False,+ "btree",+ False,+ False,+ True,+ True,+ True,+ count,+ count,+ columns,+ (0,) * count,+ tuple(_pg_index_opclass(table, column) for column in columns),+ ("pg_catalog",) * count,+ (True,) * count,+ None,+ None,+ )+++def _pg_require_safe_data(bind: Any, tables: set[str]) -> None:+ for table, columns in _PG_FINITE_CHECKS.items():+ if table not in tables:+ continue+ for column, nullable in columns.items():+ invalid_statement = ( # noqa: S608+ f'SELECT 1 FROM "{table}" ' # noqa: S608+ f'WHERE "{column}" IS NOT NULL '+ f'AND NOT isfinite("{column}") LIMIT 1'+ )+ invalid = bind.exec_driver_sql( # noqa: S608+ invalid_statement+ ).first()+ if invalid:+ raise RuntimeError(_DATA_ERROR)+ null_statement = ( # noqa: S608+ f'SELECT 1 FROM "{table}" ' # noqa: S608+ f'WHERE "{column}" IS NULL LIMIT 1'+ )+ if not nullable and bind.exec_driver_sql( # noqa: S608+ null_statement+ ).first():+ raise RuntimeError(_DATA_ERROR)+ for column in ("cvss_score", "cvss_vector", "trace_id"):+ statement = ( # noqa: S608+ f'SELECT 1 FROM findings ' # noqa: S608+ f'WHERE "{column}" IS NULL LIMIT 1'+ )+ if bind.exec_driver_sql(statement).first(): # noqa: S608+ raise RuntimeError(_DATA_ERROR)+ _require_no_orphans(bind)+ _require_boolean_integer_data(bind, tables)+ duplicate_checks = (+ ("hosts", ("campaign_id", "ip_address")),+ ("users", ("username",)),+ )+ for table, columns in duplicate_checks:+ grouped = ", ".join(f'"{column}"' for column in columns)+ statement = ( # noqa: S608+ f'SELECT 1 FROM "{table}" GROUP BY {grouped} ' # noqa: S608+ "HAVING count(*) > 1 LIMIT 1"+ )+ if bind.exec_driver_sql(statement).first():+ raise RuntimeError(_DATA_ERROR)+++def _normalize_pg_definition(value: object) -> str:+ return _normalize_sql_syntax(+ value,+ strip_postgres_casts=True,+ )+++def _expected_pg_fk(+ local: str,+ parent: str,+ remote: str,+ on_delete: str,+) -> str:+ return _normalize_pg_definition(+ f"FOREIGN KEY ({local}) REFERENCES {parent}({remote}) "+ f"ON DELETE {on_delete}"+ )+++def _expected_pg_unique(columns: tuple[str, ...]) -> str:+ return _normalize_pg_definition(+ f"UNIQUE ({', '.join(columns)})"+ )+++def _expected_pg_primary(columns: tuple[str, ...]) -> str:+ return _normalize_pg_definition(+ f"PRIMARY KEY ({', '.join(columns)})"+ )+++def _pg_constraint_plan(+ bind: Any,+ tables: set[str],+) -> tuple[+ list[tuple[str, str, str]],+ list[tuple[str, str, str, str, str]],+ list[tuple[str, str, str]],+ list[tuple[str, str, tuple[str, ...]]],+ list[tuple[str, str, str]],+]:+ rows = _pg_constraint_rows(bind)+ drop: list[tuple[str, str, str]] = []+ add_fks: list[tuple[str, str, str, str, str]] = []+ add_checks: list[tuple[str, str, str]] = []+ add_uniques: list[tuple[str, str, tuple[str, ...]]] = []+ rename_uniques: list[tuple[str, str, str]] = []++ by_table_type: dict[tuple[str, str], list[dict[str, object]]] = {}+ for row in rows:+ table = str(row["table_name"])+ kind = str(row["constraint_type"])+ by_table_type.setdefault((table, kind), []).append(row)+ if table in _PG_PRIMARY_KEYS and (+ not bool(row["is_validated"])+ or bool(row["is_deferrable"])+ or bool(row["is_deferred"])+ ):+ raise RuntimeError(_CATALOG_ERROR)++ for table, columns in _PG_PRIMARY_KEYS.items():+ if table not in tables:+ continue+ rows_for_table = by_table_type.get((table, "p"), [])+ expected_name = f"{table}_pkey"+ expected = _expected_pg_primary(columns)+ if len(rows_for_table) != 1:+ raise RuntimeError(_CATALOG_ERROR)+ row = rows_for_table[0]+ if (+ str(row["constraint_name"]) != expected_name+ or _normalize_pg_definition(row["definition"]) != expected+ ):+ raise RuntimeError(_CATALOG_ERROR)++ expected_fks_by_table: dict[str, set[str]] = {+ table: set()+ for table in (set(_PG_PRIMARY_KEYS) & tables)+ }+ for (+ _canonical,+ (table, local, parent, remote, on_delete),+ ) in _PG_FOREIGN_KEYS.items():+ if table in tables:+ expected_fks_by_table[table].add(+ _expected_pg_fk(local, parent, remote, on_delete)+ )+ for table, expected_definitions in expected_fks_by_table.items():+ foreign_rows = by_table_type.get((table, "f"), [])+ actual_definitions = tuple(+ _normalize_pg_definition(row["definition"])+ for row in foreign_rows+ )+ if (+ len(actual_definitions) != len(set(actual_definitions))+ or not set(actual_definitions).issubset(expected_definitions)+ ):+ raise RuntimeError(_CATALOG_ERROR)++ for canonical, (+ table,+ local,+ parent,+ remote,+ on_delete,+ ) in _PG_FOREIGN_KEYS.items():+ if table not in tables:+ continue+ expected = _expected_pg_fk(local, parent, remote, on_delete)+ candidates = [+ row+ for row in by_table_type.get((table, "f"), [])+ if _normalize_pg_definition(row["definition"]) == expected+ ]+ if len(candidates) > 1:+ raise RuntimeError(_CATALOG_ERROR)+ canonical_row = next(+ (+ row+ for row in by_table_type.get((table, "f"), [])+ if str(row["constraint_name"]) == canonical+ ),+ None,+ )+ if canonical_row is not None and _normalize_pg_definition(+ canonical_row["definition"]+ ) != expected:+ raise RuntimeError(_CATALOG_ERROR)+ if not candidates:+ if table == "websocket_tickets":+ raise RuntimeError(_CATALOG_ERROR)+ add_fks.append((canonical, table, local, parent, remote))+ elif str(candidates[0]["constraint_name"]) != canonical:+ if table == "websocket_tickets":+ raise RuntimeError(_CATALOG_ERROR)+ drop.append(+ (table, str(candidates[0]["constraint_name"]), "foreignkey")+ )+ add_fks.append((canonical, table, local, parent, remote))++ for canonical, (table, columns) in _PG_UNIQUES.items():+ expected = _expected_pg_unique(columns)+ candidates = [+ row+ for row in by_table_type.get((table, "u"), [])+ if _normalize_pg_definition(row["definition"]) == expected+ ]+ if any(+ _normalize_pg_definition(row["definition"]) != expected+ for row in by_table_type.get((table, "u"), [])+ ) or len(candidates) > 1:+ raise RuntimeError(_CATALOG_ERROR)+ canonical_row = next(+ (+ row+ for row in by_table_type.get((table, "u"), [])+ if str(row["constraint_name"]) == canonical+ ),+ None,+ )+ if canonical_row is not None and _normalize_pg_definition(+ canonical_row["definition"]+ ) != expected:+ raise RuntimeError(_CATALOG_ERROR)+ if not candidates:+ add_uniques.append((canonical, table, columns))+ elif str(candidates[0]["constraint_name"]) != canonical:+ drop.append(+ (table, str(candidates[0]["constraint_name"]), "unique")+ )+ add_uniques.append((canonical, table, columns))++ expected_checks: dict[tuple[str, str], str] = {}+ for table, columns in _PG_FINITE_CHECKS.items():+ if table not in tables:+ continue+ for column, nullable in columns.items():+ name = _pg_check_name(table, column)+ expression = (+ f"{column} IS NULL OR isfinite({column})"+ if nullable+ else f"isfinite({column})"+ )+ expected_checks[(table, name)] = _normalize_pg_definition(+ f"CHECK ({expression})"+ )+ if "rate_limit_events" in tables:+ expected_checks[+ ("rate_limit_events", "ck_rate_limit_events_blocked_bool")+ ] = _normalize_pg_definition(+ "CHECK (blocked = ANY (ARRAY[0, 1]))"+ )+ for name, definition in _PG_TICKET_CHECKS.items():+ expected_checks[("websocket_tickets", name)] = (+ _normalize_pg_definition(definition)+ )++ for (table, name), expected in expected_checks.items():+ row = next(+ (+ item+ for item in by_table_type.get((table, "c"), [])+ if str(item["constraint_name"]) == name+ ),+ None,+ )+ if row is None:+ if table == "websocket_tickets":+ raise RuntimeError(_CATALOG_ERROR)+ expression = expected+ if name == "ck_rate_limit_events_blocked_bool":+ expression = "blocked IN (0, 1)"+ else:+ column = next(+ column_name+ for column_name in _PG_FINITE_CHECKS[table]+ if _pg_check_name(table, column_name) == name+ )+ nullable = _PG_FINITE_CHECKS[table][column]+ expression = (+ f"{column} IS NULL OR isfinite({column})"+ if nullable+ else f"isfinite({column})"+ )+ add_checks.append((name, table, expression))+ elif _normalize_pg_definition(row["definition"]) != expected:+ raise RuntimeError(_CATALOG_ERROR)++ expected_check_names: dict[str, set[str]] = {}+ for table, name in expected_checks:+ expected_check_names.setdefault(table, set()).add(name)+ expected_unique_tables = {+ table for table, _columns in _PG_UNIQUES.values()+ }+ managed_tables = set(_PG_PRIMARY_KEYS) & tables+ for (table, kind), constraint_rows in by_table_type.items():+ if table not in managed_tables:+ continue+ if kind == "c" and any(+ str(row["constraint_name"])+ not in expected_check_names.get(table, set())+ for row in constraint_rows+ ):+ raise RuntimeError(_CATALOG_ERROR)+ if kind == "u" and table not in expected_unique_tables:+ raise RuntimeError(_CATALOG_ERROR)+ if kind == "f":+ actual_definitions = tuple(+ _normalize_pg_definition(row["definition"])+ for row in constraint_rows+ )+ if (+ len(actual_definitions) != len(set(actual_definitions))+ or not set(actual_definitions).issubset(+ expected_fks_by_table.get(table, set())+ )+ ):+ raise RuntimeError(_CATALOG_ERROR)+ if kind not in {"p", "f", "u", "c"}:+ raise RuntimeError(_CATALOG_ERROR)++ return drop, add_fks, add_checks, add_uniques, rename_uniques+++def _postgresql_upgrade(bind: Any) -> None:+ _pg_validate_alembic_version_relation(bind)+ tables = _pg_validate_relation_shapes(bind)+ create_module_runs = "module_runs" not in tables+ create_rate_limit = "rate_limit_events" not in tables++ # The complete plan is read-only through this point. An unsafe value,+ # conflicting constraint, or non-equivalent alias therefore fails before+ # any application DDL.+ findings_alterations, rename_credentials = _pg_validate_columns(+ bind,+ tables,+ )+ _pg_validate_serial_sequences(bind, tables)+ _pg_require_safe_data(bind, tables)+ (+ drop_constraints,+ add_fks,+ add_checks,+ add_uniques,+ rename_uniques,+ ) = _pg_constraint_plan(bind, tables)++ canonical_indexes = {+ table: indexes+ for table, indexes in _SQLITE_INDEXES.items()+ if table != "schema_version"+ }+ _pg_reject_reserved_index_collisions(bind, tables)+ index_rows = _pg_index_rows(bind)+ indexes = {+ (str(row["table_name"]), str(row["index_name"])): row+ for row in index_rows+ }+ known_indexes = {+ (table, name)+ for table, values in canonical_indexes.items()+ for name in values+ }+ known_indexes.update(+ (table, alias)+ for alias, (table, _canonical) in _PG_RUNTIME_ALIASES.items()+ )+ known_indexes.add(("findings", "idx_findings_validated"))+ managed_tables = _PG_REQUIRED_TABLES | _PG_OPTIONAL_TABLES+ if any(+ key[0] in managed_tables and key not in known_indexes+ for key in indexes+ ):+ raise RuntimeError(_CATALOG_ERROR)++ create_indexes: list[tuple[str, str, tuple[str, ...]]] = []+ drop_indexes: list[tuple[str, str]] = []+ for table, expected_indexes in canonical_indexes.items():+ if table not in tables:+ continue+ for name, expected_columns in expected_indexes.items():+ row = indexes.get((table, name))+ if row is None:+ if table == "websocket_tickets":+ raise RuntimeError(_CATALOG_ERROR)+ create_indexes.append((name, table, expected_columns))+ elif _pg_index_contract(row) != _expected_pg_index(+ table, expected_columns+ ):+ raise RuntimeError(_CATALOG_ERROR)++ for alias, (table, canonical) in _PG_RUNTIME_ALIASES.items():+ row = indexes.get((table, alias))+ if row is None:+ continue+ expected_columns = canonical_indexes[table][canonical]+ if _pg_index_contract(row) != _expected_pg_index(+ table, expected_columns+ ):+ raise RuntimeError(_CATALOG_ERROR)+ drop_indexes.append((alias, table))++ obsolete = indexes.get(("findings", "idx_findings_validated"))+ if obsolete is not None:+ if _pg_index_contract(obsolete) != _expected_pg_index(+ "findings", ("validated",)+ ):+ raise RuntimeError(_CATALOG_ERROR)+ drop_indexes.append(("idx_findings_validated", "findings"))++ if rename_credentials:+ op.alter_column(+ "credentials",+ "cracked_value",+ new_column_name="cracked_value_enc",+ existing_type=sa.Text(),+ existing_nullable=True,+ )+ if create_module_runs:+ timestamp = sa.DateTime(timezone=True)+ op.create_table(+ "module_runs",+ sa.Column("id", sa.Text(), primary_key=True),+ sa.Column(+ "campaign_id",+ sa.Text(),+ sa.ForeignKey(+ "campaigns.id",+ name="fk_module_runs_campaign",+ ondelete="CASCADE",+ ),+ nullable=False,+ ),+ sa.Column("module_id", sa.Text(), nullable=False),+ sa.Column("outcome", sa.Text(), nullable=False),+ sa.Column(+ "success", sa.Integer(), nullable=False, server_default="0"+ ),+ sa.Column(+ "duration_ms",+ sa.Float(),+ nullable=False,+ server_default="0.0",+ ),+ sa.Column(+ "completed_at",+ timestamp,+ nullable=False,+ server_default=sa.text("now()"),+ ),+ sa.CheckConstraint(+ "isfinite(completed_at)",+ name="ck_module_runs_completed_at_finite",+ ),+ )+ op.create_index(+ "idx_module_runs_campaign", "module_runs", ["campaign_id"]+ )+ op.create_index(+ "idx_module_runs_completed", "module_runs", ["completed_at"]+ )+ if create_rate_limit:+ op.create_table(+ "rate_limit_events",+ sa.Column(+ "id", sa.Integer(), primary_key=True, autoincrement=True+ ),+ sa.Column("ip_address", sa.Text(), nullable=False),+ sa.Column("bucket", sa.Text(), nullable=False),+ sa.Column("username", sa.Text()),+ sa.Column(+ "blocked", sa.Integer(), nullable=False, server_default="0"+ ),+ sa.Column(+ "timestamp",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.text("now()"),+ ),+ sa.CheckConstraint(+ "blocked IN (0, 1)",+ name="ck_rate_limit_events_blocked_bool",+ ),+ sa.CheckConstraint(+ "isfinite(timestamp)",+ name="ck_rate_limit_events_timestamp_finite",+ ),+ )+ op.create_index("idx_rle_ip", "rate_limit_events", ["ip_address"])+ op.create_index(+ "idx_rle_timestamp", "rate_limit_events", ["timestamp"]+ )+ op.create_index(+ "idx_rle_blocked", "rate_limit_events", ["blocked"]+ )++ for table, name, constraint_type in drop_constraints:+ op.drop_constraint(name, table, type_=constraint_type)+ if rename_uniques:+ raise RuntimeError(_CATALOG_ERROR)+ for name, table, columns in add_uniques:+ op.create_unique_constraint(name, table, list(columns))+ for name, table, local, parent, remote in add_fks:+ on_delete = _PG_FOREIGN_KEYS[name][4]+ op.create_foreign_key(+ name,+ table,+ parent,+ [local],+ [remote],+ ondelete=on_delete,+ )+ for name, table, expression in add_checks:+ op.create_check_constraint(name, table, expression)+ for name, kind, default in findings_alterations:+ op.alter_column(+ "findings",+ name,+ existing_type=kind,+ nullable=False,+ server_default=default,+ )+ for name, table, columns in create_indexes:+ op.create_index(name, table, list(columns))+ for name, table in drop_indexes:+ op.drop_index(name, table_name=table)+++def upgrade() -> None:+ bind = op.get_bind()+ dialect = bind.dialect.name+ if dialect == "sqlite":+ _sqlite_upgrade(bind)+ return+ if dialect == "postgresql":+ _postgresql_upgrade(bind)+ return+ raise RuntimeError(_DIALECT_ERROR)+++def downgrade() -> None:+ raise RuntimeError(_DOWNGRADE_ERROR)diff --git a/tests/integration/test_postgres_schema_reconciliation.py b/tests/integration/test_postgres_schema_reconciliation.pynew file mode 100644index 0000000..c34142d--- /dev/null+++ b/tests/integration/test_postgres_schema_reconciliation.py@@ -0,0 +1,3880 @@+"""PostgreSQL runtime ownership checks for the reconciled Alembic schema."""+from __future__ import annotations++import importlib+import os+import sys+from copy import deepcopy+from datetime import datetime, timezone+from types import SimpleNamespace+from typing import Any+from unittest.mock import patch++import pytest++from ares.db.postgres import PostgresDatabase, _classify_postgres_revision++_POSTGRES_ENV = (+ "ARES_TEST_POSTGRES_HOST",+ "ARES_TEST_POSTGRES_PORT",+ "ARES_TEST_POSTGRES_USER",+ "ARES_TEST_POSTGRES_DB",+)+_MIGRATION_REQUIRED = "PostgreSQL schema migration required"+_INCOMPATIBLE_SCHEMA = "Incompatible managed PostgreSQL schema"+_VALIDATION_FAILED = "PostgreSQL schema validation failed"++_EXPECTED_TABLES = (+ "api_keys",+ "audit_log",+ "campaigns",+ "credentials",+ "findings",+ "hosts",+ "loot",+ "module_runs",+ "rate_limit_events",+ "refresh_tokens",+ "revoked_access_tokens",+ "users",+ "websocket_tickets",+)+_EXPECTED_INDEXES = (+ ("api_keys", "idx_apikeys_prefix", ("key_prefix",), "text_ops"),+ ("api_keys", "idx_apikeys_user", ("user_id",), "text_ops"),+ ("audit_log", "idx_audit_action", ("action",), "text_ops"),+ ("audit_log", "idx_audit_actor", ("actor",), "text_ops"),+ ("audit_log", "idx_audit_campaign", ("campaign_id",), "text_ops"),+ ("credentials", "idx_creds_campaign", ("campaign_id",), "text_ops"),+ ("credentials", "idx_creds_type", ("cred_type",), "text_ops"),+ ("credentials", "idx_creds_username", ("username",), "text_ops"),+ ("findings", "idx_findings_campaign", ("campaign_id",), "text_ops"),+ ("findings", "idx_findings_cvss", ("cvss_score",), "float8_ops"),+ (+ "findings",+ "idx_findings_fp",+ ("false_positive",),+ "int4_ops",+ ),+ ("findings", "idx_findings_mitre", ("mitre_technique",), "text_ops"),+ ("findings", "idx_findings_severity", ("severity",), "text_ops"),+ ("hosts", "idx_hosts_campaign", ("campaign_id",), "text_ops"),+ ("hosts", "idx_hosts_domain", ("domain",), "text_ops"),+ ("hosts", "idx_hosts_ip", ("ip_address",), "text_ops"),+ ("loot", "idx_loot_campaign", ("campaign_id",), "text_ops"),+ ("loot", "idx_loot_type", ("loot_type",), "text_ops"),+ (+ "module_runs",+ "idx_module_runs_campaign",+ ("campaign_id",),+ "text_ops",+ ),+ (+ "module_runs",+ "idx_module_runs_completed",+ ("completed_at",),+ "timestamptz_ops",+ ),+ (+ "rate_limit_events",+ "idx_rle_blocked",+ ("blocked",),+ "int4_ops",+ ),+ (+ "rate_limit_events",+ "idx_rle_ip",+ ("ip_address",),+ "text_ops",+ ),+ (+ "rate_limit_events",+ "idx_rle_timestamp",+ ("timestamp",),+ "timestamptz_ops",+ ),+ (+ "refresh_tokens",+ "idx_refresh_exp",+ ("expires_at",),+ "timestamptz_ops",+ ),+ ("refresh_tokens", "idx_refresh_user", ("user_id",), "text_ops"),+ (+ "revoked_access_tokens",+ "idx_rat_expires",+ ("expires_at",),+ "timestamptz_ops",+ ),+ ("users", "idx_users_role", ("role",), "text_ops"),+ ("users", "idx_users_username", ("username",), "text_ops"),+)+_EXPECTED_PRIMARY_KEYS = (+ ("api_keys", "api_keys_pkey", ("id",)),+ ("audit_log", "audit_log_pkey", ("id",)),+ ("campaigns", "campaigns_pkey", ("id",)),+ ("credentials", "credentials_pkey", ("id",)),+ ("findings", "findings_pkey", ("id",)),+ ("hosts", "hosts_pkey", ("id",)),+ ("loot", "loot_pkey", ("id",)),+ ("module_runs", "module_runs_pkey", ("id",)),+ ("rate_limit_events", "rate_limit_events_pkey", ("id",)),+ ("refresh_tokens", "refresh_tokens_pkey", ("id",)),+ (+ "revoked_access_tokens",+ "revoked_access_tokens_pkey",+ ("jti",),+ ),+ ("users", "users_pkey", ("id",)),+)++_EXPECTED_FOREIGN_KEYS = (+ (+ "api_keys",+ "fk_api_keys_user",+ ("user_id",),+ "users",+ ("id",),+ "CASCADE",+ "c",+ ),+ (+ "audit_log",+ "fk_audit_campaign",+ ("campaign_id",),+ "campaigns",+ ("id",),+ "SET NULL",+ "n",+ ),+ (+ "credentials",+ "fk_credentials_campaign",+ ("campaign_id",),+ "campaigns",+ ("id",),+ "CASCADE",+ "c",+ ),+ (+ "credentials",+ "fk_credentials_host",+ ("host_id",),+ "hosts",+ ("id",),+ "SET NULL",+ "n",+ ),+ (+ "findings",+ "fk_findings_campaign",+ ("campaign_id",),+ "campaigns",+ ("id",),+ "CASCADE",+ "c",+ ),+ (+ "hosts",+ "fk_hosts_campaign",+ ("campaign_id",),+ "campaigns",+ ("id",),+ "CASCADE",+ "c",+ ),+ (+ "loot",+ "fk_loot_campaign",+ ("campaign_id",),+ "campaigns",+ ("id",),+ "CASCADE",+ "c",+ ),+ (+ "loot",+ "fk_loot_host",+ ("host_id",),+ "hosts",+ ("id",),+ "SET NULL",+ "n",+ ),+ (+ "module_runs",+ "fk_module_runs_campaign",+ ("campaign_id",),+ "campaigns",+ ("id",),+ "CASCADE",+ "c",+ ),+ (+ "refresh_tokens",+ "fk_refresh_tokens_user",+ ("user_id",),+ "users",+ ("id",),+ "CASCADE",+ "c",+ ),+)++_EXPECTED_UNIQUES = (+ ("hosts", "uq_hosts_campaign_ip", ("campaign_id", "ip_address")),+ ("users", "uq_users_username", ("username",)),+)++_EXPECTED_FINITE_CHECKS = (+ ("api_keys", "created_at", False),+ ("api_keys", "expires_at", True),+ ("api_keys", "last_used", True),+ ("audit_log", "timestamp", False),+ ("campaigns", "created_at", False),+ ("campaigns", "updated_at", False),+ ("credentials", "captured_at", False),+ ("findings", "discovered_at", False),+ ("hosts", "first_seen", False),+ ("hosts", "last_seen", False),+ ("loot", "captured_at", False),+ ("module_runs", "completed_at", False),+ ("rate_limit_events", "timestamp", False),+ ("refresh_tokens", "created_at", False),+ ("refresh_tokens", "expires_at", False),+ ("refresh_tokens", "used_at", True),+ ("revoked_access_tokens", "expires_at", False),+ ("revoked_access_tokens", "revoked_at", False),+ ("users", "created_at", False),+ ("users", "last_login", True),+)+++def _finite_check_name(table: str, column: str) -> str:+ if table == "module_runs":+ return "ck_module_runs_completed_at_finite"+ if table == "audit_log":+ return "ck_audit_log_timestamp_finite"+ if table == "rate_limit_events":+ return "ck_rate_limit_events_timestamp_finite"+ return f"ck_{table}_{column}_finite"+++def _require_fixed(condition: bool, message: str) -> None:+ if not condition:+ pytest.fail(message, pytrace=False)+++def _postgres_test_config() -> tuple[str, int, str, str]:+ present = {name for name in _POSTGRES_ENV if name in os.environ}+ if not present:+ pytest.skip("real PostgreSQL test environment is not configured")+ if present != set(_POSTGRES_ENV):+ pytest.fail("Incomplete PostgreSQL test environment", pytrace=False)+ values = {name: os.environ[name] for name in _POSTGRES_ENV}+ if any(not value or value != value.strip() for value in values.values()):+ pytest.fail("Invalid PostgreSQL test environment", pytrace=False)+ raw_port = values["ARES_TEST_POSTGRES_PORT"]+ if (+ not raw_port.isascii()+ or not raw_port.isdecimal()+ or str(int(raw_port)) != raw_port+ ):+ pytest.fail("PostgreSQL test port is invalid", pytrace=False)+ port = int(raw_port)+ if not 1 <= port <= 65535:+ pytest.fail(+ "PostgreSQL test port is outside its valid range",+ pytrace=False,+ )+ return (+ values["ARES_TEST_POSTGRES_HOST"],+ port,+ values["ARES_TEST_POSTGRES_USER"],+ values["ARES_TEST_POSTGRES_DB"],+ )+++class _AsyncBoundary:+ async def __aenter__(self) -> _AsyncBoundary:+ return self++ async def __aexit__(self, *_exc_info: object) -> None:+ return None+++class _AcquireBoundary:+ def __init__(self, connection: _PureManagedConnection) -> None:+ self._connection = connection++ async def __aenter__(self) -> _PureManagedConnection:+ return self._connection++ async def __aexit__(self, *_exc_info: object) -> None:+ return None+++def _table_rows() -> list[dict[str, object]]:+ return [+ {+ "table_oid": position + 100,+ "table_name": table,+ "table_schema": "public",+ "type_oid": position + 500,+ "type_schema": "public",+ "type_name": table,+ "typtype": "c",+ "type_relation_oid": position + 100,+ "relkind": "r",+ "relpersistence": "p",+ "relispartition": False,+ "relrowsecurity": False,+ "relforcerowsecurity": False,+ "parent_count": 0,+ "child_count": 0,+ "policy_count": 0,+ "user_trigger_count": 0,+ "user_rule_count": 0,+ }+ for position, table in enumerate(_EXPECTED_TABLES)+ ]+++def _index_rows() -> list[dict[str, object]]:+ return [+ {+ "table_name": table,+ "index_name": name,+ "index_relkind": "i",+ "index_relpersistence": "p",+ "index_is_partition": False,+ "access_method": "btree",+ "indisunique": False,+ "indisprimary": False,+ "indisvalid": True,+ "indisready": True,+ "indislive": True,+ "indnkeyatts": len(columns),+ "indnatts": len(columns),+ "columns": list(columns),+ "column_options": [0] * len(columns),+ "operator_classes": [opclass] * len(columns),+ "operator_class_namespaces": ["pg_catalog"] * len(columns),+ "column_collations_match": [True] * len(columns),+ "expressions": None,+ "predicate": None,+ }+ for table, name, columns, opclass in _EXPECTED_INDEXES+ ]+++def _primary_rows() -> list[dict[str, object]]:+ return [+ {+ "table_name": table,+ "conname": name,+ "contype": "p",+ "convalidated": True,+ "condeferrable": False,+ "condeferred": False,+ "constraint_index_oid": position + 1000,+ "local_columns": list(columns),+ "index_relkind": "i",+ "index_relpersistence": "p",+ "index_is_partition": False,+ "indisunique": True,+ "indisprimary": True,+ "indisvalid": True,+ "indisready": True,+ "indislive": True,+ }+ for position, (table, name, columns) in enumerate(+ _EXPECTED_PRIMARY_KEYS+ )+ ]+++def _managed_constraint_rows() -> list[dict[str, object]]:+ rows: list[dict[str, object]] = []+ for position, (+ table,+ name,+ local,+ parent,+ remote,+ on_delete,+ delete_code,+ ) in enumerate(_EXPECTED_FOREIGN_KEYS, start=1):+ rows.append(+ {+ "source_schema": "public",+ "table_name": table,+ "conname": name,+ "contype": "f",+ "convalidated": True,+ "condeferrable": False,+ "condeferred": False,+ "constraint_index_oid": 2000 + position,+ "definition": (+ f"FOREIGN KEY ({', '.join(local)}) "+ f"REFERENCES {parent}({', '.join(remote)}) "+ f"ON DELETE {on_delete}"+ ),+ "referenced_schema": "public",+ "referenced_table": parent,+ "confupdtype": "a",+ "confdeltype": delete_code,+ "local_columns": list(local),+ "remote_columns": list(remote),+ "index_schema": "public",+ "index_name": f"{parent}_pkey",+ "index_relkind": "i",+ "index_relpersistence": "p",+ "index_is_partition": False,+ "access_method": "btree",+ "indisunique": True,+ "indisprimary": True,+ "indisvalid": True,+ "indisready": True,+ "indislive": True,+ "indnkeyatts": len(remote),+ "indnatts": len(remote),+ "index_columns": list(remote),+ "column_options": [0] * len(remote),+ "operator_classes": ["text_ops"] * len(remote),+ "operator_class_namespaces": ["pg_catalog"] * len(remote),+ "column_collations_match": [True] * len(remote),+ "expressions": None,+ "predicate": None,+ }+ )+ for position, (table, name, columns) in enumerate(+ _EXPECTED_UNIQUES,+ start=1,+ ):+ rows.append(+ {+ "source_schema": "public",+ "table_name": table,+ "conname": name,+ "contype": "u",+ "convalidated": True,+ "condeferrable": False,+ "condeferred": False,+ "constraint_index_oid": 3000 + position,+ "definition": f"UNIQUE ({', '.join(columns)})",+ "referenced_schema": None,+ "referenced_table": None,+ "confupdtype": " ",+ "confdeltype": " ",+ "local_columns": list(columns),+ "remote_columns": [],+ "index_schema": "public",+ "index_name": name,+ "index_relkind": "i",+ "index_relpersistence": "p",+ "index_is_partition": False,+ "access_method": "btree",+ "indisunique": True,+ "indisprimary": False,+ "indisvalid": True,+ "indisready": True,+ "indislive": True,+ "indnkeyatts": len(columns),+ "indnatts": len(columns),+ "index_columns": list(columns),+ "column_options": [0] * len(columns),+ "operator_classes": ["text_ops"] * len(columns),+ "operator_class_namespaces": ["pg_catalog"] * len(columns),+ "column_collations_match": [True] * len(columns),+ "expressions": None,+ "predicate": None,+ }+ )+ for table, column, nullable in _EXPECTED_FINITE_CHECKS:+ name = _finite_check_name(table, column)+ expression = (+ f"{column} IS NULL OR isfinite({column})"+ if nullable+ else f"isfinite({column})"+ )+ rows.append(+ {+ "source_schema": "public",+ "table_name": table,+ "conname": name,+ "contype": "c",+ "convalidated": True,+ "condeferrable": False,+ "condeferred": False,+ "constraint_index_oid": 0,+ "definition": f"CHECK ({expression})",+ "referenced_schema": None,+ "referenced_table": None,+ "confupdtype": " ",+ "confdeltype": " ",+ "local_columns": [column],+ "remote_columns": [],+ "index_schema": None,+ "index_name": None,+ "index_relkind": None,+ "index_relpersistence": None,+ "index_is_partition": None,+ "access_method": None,+ "indisunique": None,+ "indisprimary": None,+ "indisvalid": None,+ "indisready": None,+ "indislive": None,+ "indnkeyatts": None,+ "indnatts": None,+ "index_columns": [],+ "column_options": [],+ "operator_classes": [],+ "operator_class_namespaces": [],+ "column_collations_match": [],+ "expressions": None,+ "predicate": None,+ }+ )+ blocked = deepcopy(rows[-1])+ blocked.update(+ {+ "table_name": "rate_limit_events",+ "conname": "ck_rate_limit_events_blocked_bool",+ "definition": "CHECK (blocked = ANY (ARRAY[0, 1]))",+ "local_columns": ["blocked"],+ }+ )+ rows.append(blocked)+ return rows+++def _managed_sequence_rows() -> list[dict[str, object]]:+ return [+ {+ "sequence_schema": "public",+ "sequence_name": name,+ "relkind": "S",+ "relpersistence": "p",+ "data_type": "integer",+ "seqstart": 1,+ "seqincrement": 1,+ "seqmax": 2147483647,+ "seqmin": 1,+ "seqcache": 1,+ "seqcycle": False,+ "owner_schema": "public",+ "owner_table": table,+ "owner_column": "id",+ "deptype": "a",+ "owner_data_type": "integer",+ "attnotnull": True,+ "attidentity": "",+ "attgenerated": "",+ "collation_is_default": True,+ "column_default": f"nextval('{name}'::regclass)",+ }+ for name, table in (+ ("audit_log_id_seq", "audit_log"),+ ("rate_limit_events_id_seq", "rate_limit_events"),+ )+ ]+++class _PureManagedConnection:+ def __init__(+ self,+ *,+ revision_present: bool = True,+ revision_values: tuple[object, ...] = ("0008",),+ ) -> None:+ self.revision_present = revision_present+ self.revision_values = revision_values+ self.version_relation = {+ "table_oid": 42,+ "schema_name": "public",+ "type_oid": 84,+ "type_schema": "public",+ "type_name": "alembic_version",+ "typtype": "c",+ "type_relation_oid": 42,+ "relkind": "r",+ "relpersistence": "p",+ "relispartition": False,+ "relrowsecurity": False,+ "relforcerowsecurity": False,+ "parent_count": 0,+ "child_count": 0,+ "policy_count": 0,+ "user_trigger_count": 0,+ "user_rule_count": 0,+ }+ self.version_columns = [+ {+ "attnum": 1,+ "column_name": "version_num",+ "data_type": "character varying(32)",+ "attnotnull": True,+ "attidentity": "",+ "attgenerated": "",+ "attisdropped": False,+ "attinhcount": 0,+ "attislocal": True,+ "atthasmissing": False,+ "missing_value": None,+ "collation_is_default": True,+ "column_default": None,+ }+ ]+ self.version_primary = [+ {+ "conname": "alembic_version_pkc",+ "contype": "p",+ "convalidated": True,+ "condeferrable": False,+ "condeferred": False,+ "columns": ["version_num"],+ }+ ]+ self.version_indexes = [+ {+ "index_name": "alembic_version_pkc",+ "index_relkind": "i",+ "index_relpersistence": "p",+ "index_is_partition": False,+ "access_method": "btree",+ "indisunique": True,+ "indisprimary": True,+ "indisvalid": True,+ "indisready": True,+ "indislive": True,+ "indnkeyatts": 1,+ "indnatts": 1,+ "constraint_name": "alembic_version_pkc",+ "columns": ["version_num"],+ "column_options": [0],+ "operator_classes": ["text_ops"],+ "operator_class_namespaces": ["pg_catalog"],+ "column_collations_match": [True],+ "expressions": None,+ "predicate": None,+ }+ ]+ self.tables = _table_rows()+ self.legacy_indexes: list[dict[str, object]] = []+ self.indexes = _index_rows()+ self.primary_keys = _primary_rows()+ self.constraints = _managed_constraint_rows()+ self.sequences = _managed_sequence_rows()+ self.fallback_count = 0+ self.raise_during_revision: Exception | None = None++ def transaction(self) -> _AsyncBoundary:+ return _AsyncBoundary()++ async def fetch(self, query: str, *_args: object) -> list[dict[str, object]]:+ normalized = " ".join(query.split())+ if (+ "rel.relname='alembic_version'" in normalized+ and "FROM pg_class AS rel" in normalized+ ):+ if self.raise_during_revision is not None:+ raise self.raise_during_revision+ return [deepcopy(self.version_relation)] if self.revision_present else []+ if "WHERE att.attrelid=$1::oid" in normalized:+ return deepcopy(self.version_columns)+ if "WHERE con.conrelid=$1::oid" in normalized:+ return deepcopy(self.version_primary)+ if normalized.startswith("SELECT version_num FROM"):+ return [+ {"version_num": value}+ for value in self.revision_values+ ]+ if (+ "FROM pg_index AS ind" in normalized+ and "WHERE ind.indrelid=$1::oid" in normalized+ ):+ return deepcopy(self.version_indexes)+ if (+ "rel.relname=ANY($1::text[])" in normalized+ and "FROM pg_class AS rel" in normalized+ ):+ return deepcopy(self.tables)+ if (+ "FROM pg_index AS ind" in normalized+ and "left(index_rel.relname, 7)='idx_pg_'" in normalized+ ):+ return deepcopy(self.legacy_indexes)+ if "FROM pg_index AS ind" in normalized:+ return deepcopy(self.indexes)+ if (+ "FROM pg_constraint AS con" in normalized+ and "source.relname=ANY($1::text[])" in normalized+ and "con.contype='p'" in normalized+ ):+ return deepcopy(self.primary_keys)+ if (+ "FROM pg_constraint AS con" in normalized+ and "con.contype <> 'p'" in normalized+ ):+ return deepcopy(self.constraints)+ if "pg_sequence AS sequence_def" in normalized:+ return deepcopy(self.sequences)+ raise AssertionError("unexpected managed-schema catalog operation")++ async def fetchval(self, query: str, *_args: object) -> object:+ normalized = " ".join(query.split())+ if "SELECT EXISTS(" in normalized:+ return False+ raise AssertionError("unexpected managed-schema scalar operation")++ async def execute(self, query: str, *_args: object) -> str:+ if "CREATE TABLE IF NOT EXISTS campaigns" not in query:+ raise AssertionError("unexpected managed-schema mutation")+ self.fallback_count += 1+ return "OK"+++class _PurePool:+ def __init__(self, connection: _PureManagedConnection) -> None:+ self.connection = connection+ self.close_count = 0++ def acquire(self) -> _AcquireBoundary:+ return _AcquireBoundary(self.connection)++ async def close(self) -> None:+ self.close_count += 1+++class _RealConnectionAudit:+ def __init__(self, connection: Any, pool: _RealPoolAudit) -> None:+ self._connection = connection+ self._pool = pool++ def transaction(self) -> Any:+ return self._connection.transaction()++ async def execute(self, query: str, *args: object) -> object:+ if "CREATE TABLE IF NOT EXISTS campaigns" in query:+ self._pool.fallback_count += 1+ return await self._connection.execute(query, *args)++ async def fetch(self, query: str, *args: object) -> object:+ return await self._connection.fetch(query, *args)++ async def fetchrow(self, query: str, *args: object) -> object:+ return await self._connection.fetchrow(query, *args)++ async def fetchval(self, query: str, *args: object) -> object:+ return await self._connection.fetchval(query, *args)+++class _RealAcquireAudit:+ def __init__(self, pool: _RealPoolAudit) -> None:+ self._pool = pool+ self._connection: Any = None++ async def __aenter__(self) -> _RealConnectionAudit:+ self._connection = await self._pool._pool.acquire()+ return _RealConnectionAudit(self._connection, self._pool)++ async def __aexit__(self, *_exc_info: object) -> None:+ if self._connection is not None:+ await self._pool._pool.release(self._connection)+ self._connection = None+++class _RealPoolAudit:+ def __init__(self, pool: Any) -> None:+ self._pool = pool+ self.fallback_count = 0+ self.close_count = 0++ def acquire(self) -> _RealAcquireAudit:+ return _RealAcquireAudit(self)++ async def close(self) -> None:+ self.close_count += 1+ await self._pool.close()+++def _audit_runtime_pools(+ monkeypatch: pytest.MonkeyPatch,+) -> list[_RealPoolAudit]:+ try:+ import asyncpg+ except ImportError:+ pytest.fail(+ "asyncpg is required for configured PostgreSQL tests",+ pytrace=False,+ )+ original_create_pool = asyncpg.create_pool+ pools: list[_RealPoolAudit] = []++ async def _create_pool(*args: object, **kwargs: object) -> _RealPoolAudit:+ real_pool = await original_create_pool(*args, **kwargs)+ audited_pool = _RealPoolAudit(real_pool)+ pools.append(audited_pool)+ return audited_pool++ monkeypatch.setattr(asyncpg, "create_pool", _create_pool)+ return pools+++def _runtime_database(harness: Any) -> PostgresDatabase:+ from tests.integration import test_postgres_migration_portability as support++ return PostgresDatabase(+ support._migration_url(harness.config, harness.database_name),+ pool_min=1,+ pool_max=2,+ )+++async def _fixed_connect_result(database: PostgresDatabase) -> str:+ try:+ await database.connect()+ except RuntimeError as exc:+ message = str(exc)+ if message in {+ _MIGRATION_REQUIRED,+ _INCOMPATIBLE_SCHEMA,+ _VALIDATION_FAILED,+ }:+ return message+ return "unexpected"+ return "connected"+++async def _run_init(+ monkeypatch: pytest.MonkeyPatch,+ connection: _PureManagedConnection,+) -> int:+ validated = 0++ async def _validate_ticket(+ _database: object,+ _connection: object,+ ) -> None:+ nonlocal validated+ validated += 1++ monkeypatch.setattr(+ PostgresDatabase,+ "_validate_websocket_ticket_schema",+ _validate_ticket,+ )+ database = PostgresDatabase("synthetic")+ database._pool = _PurePool(connection)+ with patch("ares.db.postgres.logger.info", return_value=None):+ await database._init_schema()+ return validated++[email protected]("revision", ["0001", "0004", "0007"])+def test_revision_classifier_requires_migration_for_known_older_heads(+ revision: str,+) -> None:+ observed = ""+ try:+ _classify_postgres_revision((revision,))+ except RuntimeError as exc:+ observed = str(exc)+ _require_fixed(+ observed == _MIGRATION_REQUIRED,+ "known older PostgreSQL revision was not migration-gated",+ )+++ "values",+ [+ (),+ (None,),+ ("",),+ ("0008", "0008"),+ ("0008", "0007"),+ ("9999",),+ (" 0008",),+ ],+)+def test_revision_classifier_rejects_malformed_or_unknown_state(+ values: tuple[object, ...],+) -> None:+ observed = ""+ try:+ _classify_postgres_revision(values)+ except RuntimeError as exc:+ observed = str(exc)+ _require_fixed(+ observed == _INCOMPATIBLE_SCHEMA,+ "malformed PostgreSQL revision state was accepted",+ )+++def test_revision_classifier_accepts_only_exact_managed_head() -> None:+ accepted = _classify_postgres_revision(("0008",)) == "0008"+ _require_fixed(accepted, "managed PostgreSQL revision was rejected")+++def test_postgres_constraint_normalization_preserves_literal_case() -> None:+ migration = importlib.import_module(+ "migrations.versions.0008_reconcile_schema_parity"+ )+ scope_expected = migration._normalize_pg_definition(+ "CHECK (required_scope = 'read'::text)"+ )+ scope_changed = migration._normalize_pg_definition(+ "check (required_scope = 'READ'::TEXT)"+ )+ hash_expected = migration._normalize_pg_definition(+ "CHECK (ticket_hash ~ '^[0-9a-f]{64}$'::text)"+ )+ hash_changed = migration._normalize_pg_definition(+ "check (ticket_hash ~ '^[0-9A-F]{64}$'::TEXT)"+ )+ _require_fixed(+ scope_expected != scope_changed and hash_expected != hash_changed,+ "PostgreSQL constraint literal drift was normalized away",+ )+++async def test_unversioned_database_retains_runtime_fallback(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ connection = _PureManagedConnection(revision_present=False)+ validated = await _run_init(monkeypatch, connection)+ _require_fixed(+ connection.fallback_count == 1 and validated == 1,+ "unversioned PostgreSQL fallback behavior changed",+ )+++async def test_managed_database_validates_without_fallback(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ connection = _PureManagedConnection()+ validated = await _run_init(monkeypatch, connection)+ _require_fixed(+ connection.fallback_count == 0 and validated == 1,+ "managed PostgreSQL schema entered runtime fallback",+ )+++ "mutation",+ [+ "extra-index",+ "invalid-index",+ "wrong-opclass",+ "wrong-collation",+ "wrong-constraint",+ "wrong-column",+ ],+)+async def test_version_relation_index_metadata_is_exact(+ monkeypatch: pytest.MonkeyPatch,+ mutation: str,+) -> None:+ connection = _PureManagedConnection()+ if mutation == "extra-index":+ extra = deepcopy(connection.version_indexes[0])+ extra["index_name"] = "unexpected_version_index"+ extra["constraint_name"] = None+ extra["indisunique"] = False+ extra["indisprimary"] = False+ connection.version_indexes.append(extra)+ elif mutation == "invalid-index":+ connection.version_indexes[0]["indisvalid"] = False+ elif mutation == "wrong-opclass":+ connection.version_indexes[0]["operator_classes"] = ["varchar_ops"]+ elif mutation == "wrong-collation":+ connection.version_indexes[0]["column_collations_match"] = [False]+ elif mutation == "wrong-constraint":+ connection.version_indexes[0]["constraint_name"] = None+ elif mutation == "wrong-column":+ connection.version_indexes[0]["columns"] = ["other"]+ else:+ raise AssertionError("unknown version-index mutation")++ observed = ""+ try:+ await _run_init(monkeypatch, connection)+ except RuntimeError as exc:+ observed = str(exc)+ _require_fixed(+ observed == _INCOMPATIBLE_SCHEMA+ and connection.fallback_count == 0,+ "PostgreSQL version index metadata drift was accepted",+ )+++ "field",+ [+ "parent_count",+ "child_count",+ "policy_count",+ "user_trigger_count",+ "user_rule_count",+ "type_relation_oid",+ "missing-type-binding",+ ],+)+async def test_version_relation_rejects_attached_metadata(+ monkeypatch: pytest.MonkeyPatch,+ field: str,+) -> None:+ connection = _PureManagedConnection()+ if field == "missing-type-binding":+ connection.version_relation["type_oid"] = None+ connection.version_relation["type_schema"] = None+ connection.version_relation["type_name"] = None+ connection.version_relation["typtype"] = None+ connection.version_relation["type_relation_oid"] = None+ else:+ connection.version_relation[field] = 1+ observed = ""+ try:+ await _run_init(monkeypatch, connection)+ except RuntimeError as exc:+ observed = str(exc)+ _require_fixed(+ observed == _INCOMPATIBLE_SCHEMA+ and connection.fallback_count == 0,+ "PostgreSQL version relation metadata drift was accepted",+ )+++ "mutation",+ [+ "wrong-attnum",+ "dropped-column",+ "inherited-column",+ "nonlocal-column",+ "missing-value",+ "custom-collation",+ ],+)+async def test_version_column_physical_metadata_is_exact(+ monkeypatch: pytest.MonkeyPatch,+ mutation: str,+) -> None:+ connection = _PureManagedConnection()+ column = connection.version_columns[0]+ if mutation == "wrong-attnum":+ column["attnum"] = 2+ elif mutation == "dropped-column":+ dropped = deepcopy(column)+ dropped.update(+ {+ "attnum": 2,+ "column_name": "........pg.dropped.2........",+ "data_type": "-",+ "attnotnull": False,+ "attisdropped": True,+ "collation_is_default": False,+ }+ )+ connection.version_columns.append(dropped)+ elif mutation == "inherited-column":+ column["attinhcount"] = 1+ elif mutation == "nonlocal-column":+ column["attislocal"] = False+ elif mutation == "missing-value":+ column["atthasmissing"] = True+ column["missing_value"] = "{}"+ elif mutation == "custom-collation":+ column["collation_is_default"] = False+ else:+ raise AssertionError("unknown version-column mutation")+ observed = ""+ try:+ await _run_init(monkeypatch, connection)+ except RuntimeError as exc:+ observed = str(exc)+ _require_fixed(+ observed == _INCOMPATIBLE_SCHEMA+ and connection.fallback_count == 0,+ "PostgreSQL version column metadata drift was accepted",+ )+++ "mutation",+ [+ "missing-table",+ "wrong-table-kind",+ "wrong-table-type-binding",+ "missing-index",+ "extra-legacy-index",+ "wrong-index-column",+ "unique-index",+ "partial-index",+ "wrong-opclass",+ "wrong-opclass-namespace",+ "wrong-collation",+ "descending-index",+ "missing-primary-key",+ "wrong-primary-key",+ "invalid-primary-index",+ "relation-rls",+ "relation-forced-rls",+ "relation-inheritance",+ "relation-policy",+ "relation-trigger",+ "relation-rule",+ "missing-foreign-key",+ "wrong-foreign-key-target",+ "wrong-foreign-index",+ "duplicate-foreign-key",+ "extra-root-foreign-key",+ "extra-exclusion-constraint",+ "missing-check",+ "wrong-check-definition",+ "missing-unique",+ "wrong-unique-index",+ "missing-sequence",+ "wrong-sequence-owner",+ "wrong-sequence-owner-schema",+ "wrong-sequence-default",+ "wrong-sequence-options",+ "identity-serial",+ "generated-serial",+ ],+)+async def test_managed_inventory_rejects_catalog_drift(+ monkeypatch: pytest.MonkeyPatch,+ mutation: str,+) -> None:+ connection = _PureManagedConnection()+ if mutation == "missing-table":+ connection.tables.pop()+ elif mutation == "wrong-table-kind":+ connection.tables[0]["relkind"] = "v"+ elif mutation == "wrong-table-type-binding":+ connection.tables[0]["type_relation_oid"] = 9999+ elif mutation == "missing-index":+ connection.indexes.pop()+ elif mutation == "extra-legacy-index":+ connection.legacy_indexes.append(+ {+ "table_name": "users",+ "index_name": "idx_pg_unexpected",+ }+ )+ elif mutation == "wrong-index-column":+ connection.indexes[0]["columns"] = ["id"]+ elif mutation == "unique-index":+ connection.indexes[0]["indisunique"] = True+ elif mutation == "partial-index":+ connection.indexes[0]["predicate"] = "true"+ elif mutation == "wrong-opclass":+ connection.indexes[0]["operator_classes"] = ["text_pattern_ops"]+ elif mutation == "wrong-opclass-namespace":+ connection.indexes[0]["operator_class_namespaces"] = ["public"]+ elif mutation == "wrong-collation":+ connection.indexes[0]["column_collations_match"] = [False]+ elif mutation == "descending-index":+ connection.indexes[0]["column_options"] = [1]+ elif mutation == "missing-primary-key":+ connection.primary_keys.pop()+ elif mutation == "wrong-primary-key":+ connection.primary_keys[0]["local_columns"] = ["user_id"]+ elif mutation == "invalid-primary-index":+ connection.primary_keys[0]["indisvalid"] = False+ elif mutation == "relation-rls":+ connection.tables[0]["relrowsecurity"] = True+ elif mutation == "relation-forced-rls":+ connection.tables[0]["relforcerowsecurity"] = True+ elif mutation == "relation-inheritance":+ connection.tables[0]["child_count"] = 1+ elif mutation == "relation-policy":+ connection.tables[0]["policy_count"] = 1+ elif mutation == "relation-trigger":+ connection.tables[0]["user_trigger_count"] = 1+ elif mutation == "relation-rule":+ connection.tables[0]["user_rule_count"] = 1+ elif mutation == "missing-foreign-key":+ connection.constraints = [+ row+ for row in connection.constraints+ if row["contype"] != "f"+ or row["conname"] != "fk_api_keys_user"+ ]+ elif mutation == "wrong-foreign-key-target":+ foreign_key = next(+ row+ for row in connection.constraints+ if row["conname"] == "fk_api_keys_user"+ )+ foreign_key["referenced_table"] = "campaigns"+ elif mutation == "wrong-foreign-index":+ foreign_key = next(+ row+ for row in connection.constraints+ if row["conname"] == "fk_api_keys_user"+ )+ foreign_key["index_name"] = "campaigns_pkey"+ elif mutation == "duplicate-foreign-key":+ extra = deepcopy(+ next(+ row+ for row in connection.constraints+ if row["conname"] == "fk_api_keys_user"+ )+ )+ extra["conname"] = "duplicate_api_keys_user"+ connection.constraints.append(extra)+ elif mutation == "extra-root-foreign-key":+ extra = deepcopy(+ next(+ row+ for row in connection.constraints+ if row["conname"] == "fk_api_keys_user"+ )+ )+ extra.update(+ {+ "table_name": "campaigns",+ "conname": "unexpected_campaign_self_fk",+ "definition": (+ "FOREIGN KEY (id) REFERENCES campaigns(id) "+ "ON DELETE CASCADE"+ ),+ "referenced_table": "campaigns",+ "local_columns": ["id"],+ }+ )+ connection.constraints.append(extra)+ elif mutation == "extra-exclusion-constraint":+ extra = deepcopy(connection.constraints[-1])+ extra.update(+ {+ "table_name": "campaigns",+ "conname": "unexpected_campaign_exclusion",+ "contype": "x",+ "definition": "EXCLUDE USING btree (id WITH =)",+ "local_columns": ["id"],+ }+ )+ connection.constraints.append(extra)+ elif mutation == "missing-check":+ connection.constraints = [+ row+ for row in connection.constraints+ if row["contype"] != "c"+ or row["conname"] != "ck_users_created_at_finite"+ ]+ elif mutation == "wrong-check-definition":+ check = next(+ row+ for row in connection.constraints+ if row["conname"] == "ck_rate_limit_events_blocked_bool"+ )+ check["definition"] = "CHECK ((blocked = 0) OR (blocked = 1))"+ elif mutation == "missing-unique":+ connection.constraints = [+ row+ for row in connection.constraints+ if row["contype"] != "u"+ or row["conname"] != "uq_users_username"+ ]+ elif mutation == "wrong-unique-index":+ unique = next(+ row+ for row in connection.constraints+ if row["conname"] == "uq_users_username"+ )+ unique["column_collations_match"] = [False]+ elif mutation == "missing-sequence":+ connection.sequences.pop()+ elif mutation == "wrong-sequence-owner":+ connection.sequences[0]["owner_table"] = "campaigns"+ elif mutation == "wrong-sequence-owner-schema":+ connection.sequences[0]["owner_schema"] = "other"+ elif mutation == "wrong-sequence-default":+ connection.sequences[0]["column_default"] = "7"+ elif mutation == "wrong-sequence-options":+ connection.sequences[0]["seqincrement"] = 2+ elif mutation == "identity-serial":+ connection.sequences[0]["attidentity"] = "d"+ elif mutation == "generated-serial":+ connection.sequences[0]["attgenerated"] = "s"+ else:+ raise AssertionError("unknown managed-schema mutation")++ observed = ""+ try:+ await _run_init(monkeypatch, connection)+ except RuntimeError as exc:+ observed = str(exc)+ _require_fixed(+ observed == _INCOMPATIBLE_SCHEMA+ and connection.fallback_count == 0,+ "managed PostgreSQL catalog drift was not rejected",+ )+++ "revision_values",+ [("0003",), (), ("unknown",), ("0008", "0007")],+)+async def test_versioned_failure_never_enters_runtime_fallback(+ monkeypatch: pytest.MonkeyPatch,+ revision_values: tuple[object, ...],+) -> None:+ connection = _PureManagedConnection(revision_values=revision_values)+ observed = ""+ try:+ await _run_init(monkeypatch, connection)+ except RuntimeError as exc:+ observed = str(exc)+ expected = (+ _MIGRATION_REQUIRED+ if revision_values == ("0003",)+ else _INCOMPATIBLE_SCHEMA+ )+ _require_fixed(+ observed == expected and connection.fallback_count == 0,+ "versioned PostgreSQL failure entered runtime fallback",+ )+++async def test_catalog_operation_failure_is_sanitized(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ connection = _PureManagedConnection()+ connection.raise_during_revision = RuntimeError()+ observed = ""+ context_suppressed = False+ try:+ await _run_init(monkeypatch, connection)+ except RuntimeError as exc:+ observed = str(exc)+ context_suppressed = (+ exc.__cause__ is None and exc.__suppress_context__+ )+ _require_fixed(+ observed == _VALIDATION_FAILED+ and context_suppressed+ and connection.fallback_count == 0,+ "PostgreSQL catalog failure was not sanitized",+ )+++async def test_connect_closes_pool_after_migration_gate(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ connection = _PureManagedConnection(revision_values=("0007",))+ pool = _PurePool(connection)++ async def _create_pool(*_args: object, **_kwargs: object) -> _PurePool:+ return pool++ monkeypatch.setitem(+ sys.modules,+ "asyncpg",+ SimpleNamespace(create_pool=_create_pool),+ )+ database = PostgresDatabase("synthetic")+ observed = ""+ with patch("ares.db.postgres.logger.info", return_value=None):+ try:+ await database.connect()+ except RuntimeError as exc:+ observed = str(exc)+ _require_fixed(+ observed == _MIGRATION_REQUIRED+ and pool.close_count == 1+ and database._pool is None+ and connection.fallback_count == 0,+ "PostgreSQL migration gate leaked its startup pool",+ )+++def test_postgres_config_ignores_noncanonical_fallbacks(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ for name in _POSTGRES_ENV:+ monkeypatch.delenv(name, raising=False)+ monkeypatch.setenv("ARES_TEST_POSTGRES_DATABASE", "ignored")+ monkeypatch.setenv("ARES_DATABASE_URL", "ignored")+ skipped = False+ try:+ _postgres_test_config()+ except pytest.skip.Exception:+ skipped = True+ _require_fixed(+ skipped,+ "noncanonical PostgreSQL configuration prevented a clean skip",+ )+++def test_postgres_config_rejects_partial_values(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ for name in _POSTGRES_ENV:+ monkeypatch.delenv(name, raising=False)+ monkeypatch.setenv("ARES_TEST_POSTGRES_HOST", "127.0.0.1")+ failed = False+ try:+ _postgres_test_config()+ except pytest.fail.Exception:+ failed = True+ _require_fixed(failed, "partial PostgreSQL configuration was accepted")+++ "raw_port",+ ["", " 5432", "05432", "65536"],+ ids=[+ "empty-port",+ "whitespace-port",+ "noncanonical-port",+ "out-of-range-port",+ ],+)+def test_postgres_config_rejects_invalid_port(+ monkeypatch: pytest.MonkeyPatch,+ raw_port: str,+) -> None:+ monkeypatch.setenv("ARES_TEST_POSTGRES_HOST", "127.0.0.1")+ monkeypatch.setenv("ARES_TEST_POSTGRES_PORT", raw_port)+ monkeypatch.setenv("ARES_TEST_POSTGRES_USER", "synthetic")+ monkeypatch.setenv("ARES_TEST_POSTGRES_DB", "synthetic")+ failed = False+ try:+ _postgres_test_config()+ except pytest.fail.Exception:+ failed = True+ _require_fixed(failed, "invalid PostgreSQL port was accepted")+++async def test_real_postgres_managed_startup_preserves_unrelated_objects(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _postgres_test_config()+ from tests.integration import test_postgres_migration_portability as harness++ async with harness._postgres_harness() as target:+ connection = await harness._connect(target)+ try:+ empty_before = await connection.fetchrow(+ """+ SELECT+ to_regclass('alembic_version') IS NULL AS no_version,+ count(*) FILTER (+ WHERE table_name=ANY($1::text[])+ )=0 AS no_application_tables+ FROM information_schema.tables+ WHERE table_schema=current_schema()+ """,+ list(_EXPECTED_TABLES),+ )+ initially_empty = (+ empty_before is not None+ and bool(empty_before["no_version"])+ and bool(empty_before["no_application_tables"])+ )+ finally:+ await connection.close()+ await harness._alembic(target, "upgrade", "0008")+ connection = await harness._connect(target)+ try:+ await connection.execute(+ "CREATE TABLE operator_owned_probe(id INTEGER PRIMARY KEY)"+ )+ await connection.execute(+ "CREATE INDEX operator_owned_probe_idx "+ "ON operator_owned_probe(id)"+ )+ finally:+ await connection.close()++ pools = _audit_runtime_pools(monkeypatch)+ database = _runtime_database(target)+ try:+ await database.connect()+ async with database._pool.acquire() as runtime_connection:+ state = await runtime_connection.fetchrow(+ """+ SELECT+ (+ SELECT version_num='0008'+ FROM alembic_version+ ) AS managed,+ (+ SELECT count(*)=0+ FROM pg_indexes+ WHERE schemaname=current_schema()+ AND indexname LIKE 'idx_pg_%'+ ) AS no_legacy_indexes,+ to_regclass('operator_owned_probe') IS NOT NULL+ AS unrelated_preserved+ """+ )+ valid = (+ state is not None+ and bool(state["managed"])+ and bool(state["no_legacy_indexes"])+ and bool(state["unrelated_preserved"])+ )+ finally:+ await database.close()+ no_fallback = (+ len(pools) == 1+ and pools[0].fallback_count == 0+ and pools[0].close_count == 1+ )+ _require_fixed(+ initially_empty and valid and no_fallback,+ "managed PostgreSQL startup contract failed",+ )+++async def test_real_postgres_older_revision_requires_migration_and_recovers(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _postgres_test_config()+ from tests.integration import test_postgres_migration_portability as harness++ async with harness._postgres_harness() as target:+ await harness._alembic(target, "upgrade", "0007")+ pools = _audit_runtime_pools(monkeypatch)+ database = _runtime_database(target)+ observed = await _fixed_connect_result(database)+ gated = (+ observed == _MIGRATION_REQUIRED+ and database._pool is None+ and len(pools) == 1+ and pools[0].fallback_count == 0+ and pools[0].close_count == 1+ )++ await harness._alembic(target, "upgrade", "0008")+ try:+ recovered_state = (+ await _fixed_connect_result(database) == "connected"+ )+ finally:+ await database.close()+ _require_fixed(+ gated+ and recovered_state+ and len(pools) == 2+ and pools[1].fallback_count == 0+ and pools[1].close_count == 1,+ "PostgreSQL migration gate did not recover after upgrade",+ )+++ "revision_state",+ [+ pytest.param("empty", id="empty-revision"),+ pytest.param("multiple", id="multiple-revisions"),+ pytest.param("malformed", id="malformed-revision"),+ pytest.param("unknown", id="unknown-revision"),+ ],+)+async def test_real_postgres_invalid_revision_state_closes_and_recovers(+ monkeypatch: pytest.MonkeyPatch,+ revision_state: str,+) -> None:+ _postgres_test_config()+ from tests.integration import test_postgres_migration_portability as harness++ operations = {+ "empty": (+ "DELETE FROM alembic_version",+ "INSERT INTO alembic_version(version_num) VALUES('0008')",+ ),+ "multiple": (+ "INSERT INTO alembic_version(version_num) VALUES('0007')",+ "DELETE FROM alembic_version WHERE version_num='0007'",+ ),+ "malformed": (+ "UPDATE alembic_version SET version_num=' 0008'",+ "UPDATE alembic_version SET version_num='0008'",+ ),+ "unknown": (+ "UPDATE alembic_version SET version_num='9999'",+ "UPDATE alembic_version SET version_num='0008'",+ ),+ }+ mutation, repair = operations[revision_state]+ async with harness._postgres_harness() as target:+ await harness._alembic(target, "upgrade", "0008")+ connection = await harness._connect(target)+ try:+ await connection.execute(mutation)+ finally:+ await connection.close()++ pools = _audit_runtime_pools(monkeypatch)+ database = _runtime_database(target)+ rejected = await _fixed_connect_result(database)+ first_pool_closed = (+ rejected == _INCOMPATIBLE_SCHEMA+ and database._pool is None+ and len(pools) == 1+ and pools[0].fallback_count == 0+ and pools[0].close_count == 1+ )++ connection = await harness._connect(target)+ try:+ await connection.execute(repair)+ finally:+ await connection.close()+ try:+ recovered = await _fixed_connect_result(database) == "connected"+ finally:+ await database.close()+ _require_fixed(+ bool(revision_state)+ and first_pool_closed+ and recovered+ and len(pools) == 2+ and pools[1].fallback_count == 0+ and pools[1].close_count == 1,+ "invalid PostgreSQL revision state did not fail closed",+ )+++ "drift",+ [+ pytest.param("missing-table", id="missing-table"),+ pytest.param("missing-index", id="missing-index"),+ pytest.param("plain-idx-pg", id="plain-legacy-index"),+ pytest.param(+ "constraint-owned-idx-pg",+ id="constraint-owned-legacy-index",+ ),+ pytest.param("extra-version-index", id="extra-version-index"),+ pytest.param(+ "version-relation-policy",+ id="version-relation-policy",+ ),+ pytest.param(+ "version-index-relation",+ id="version-index-relation",+ ),+ pytest.param(+ "version-dropped-column",+ id="version-dropped-column",+ ),+ pytest.param(+ "version-custom-collation",+ id="version-custom-collation",+ ),+ pytest.param("relation-rls", id="relation-rls"),+ pytest.param("relation-forced-rls", id="relation-forced-rls"),+ pytest.param("relation-inheritance", id="relation-inheritance"),+ pytest.param("relation-policy", id="relation-policy"),+ pytest.param("relation-trigger", id="relation-trigger"),+ pytest.param("relation-rule", id="relation-rule"),+ pytest.param("missing-foreign-key", id="missing-foreign-key"),+ pytest.param("wrong-foreign-key", id="wrong-foreign-key"),+ pytest.param("duplicate-foreign-key", id="duplicate-foreign-key"),+ pytest.param("extra-root-foreign-key", id="extra-root-foreign-key"),+ pytest.param(+ "extra-exclusion-constraint",+ id="extra-exclusion-constraint",+ ),+ pytest.param("missing-check", id="missing-check"),+ pytest.param("wrong-check", id="wrong-check"),+ pytest.param("missing-unique", id="missing-unique"),+ pytest.param("wrong-unique", id="wrong-unique"),+ pytest.param("missing-sequence", id="missing-sequence"),+ pytest.param("wrong-sequence-owner", id="wrong-sequence-owner"),+ pytest.param(+ "wrong-sequence-owner-schema",+ id="wrong-sequence-owner-schema",+ ),+ pytest.param("wrong-sequence-options", id="wrong-sequence-options"),+ pytest.param("wrong-sequence-default", id="wrong-sequence-default"),+ ],+)+async def test_real_postgres_managed_catalog_drift_never_falls_back(+ monkeypatch: pytest.MonkeyPatch,+ drift: str,+) -> None:+ _postgres_test_config()+ from tests.integration import test_postgres_migration_portability as harness++ statements = {+ "missing-table": "DROP TABLE rate_limit_events",+ "missing-index": "DROP INDEX idx_users_role",+ "plain-idx-pg": "CREATE INDEX idx_pg_unexpected ON users(role)",+ "constraint-owned-idx-pg": (+ "ALTER TABLE users ADD CONSTRAINT idx_pg_users_role UNIQUE(role)"+ ),+ "extra-version-index": (+ "CREATE INDEX unexpected_version_index "+ "ON alembic_version(version_num)"+ ),+ "version-relation-policy": (+ "CREATE POLICY ares_runtime_version_policy "+ "ON alembic_version USING (true)"+ ),+ "version-index-relation": (+ "DROP TABLE alembic_version; "+ "CREATE INDEX alembic_version ON campaigns(status)"+ ),+ "version-dropped-column": (+ "ALTER TABLE alembic_version "+ "ADD COLUMN unexpected_version_column INTEGER; "+ "ALTER TABLE alembic_version "+ "DROP COLUMN unexpected_version_column"+ ),+ "version-custom-collation": (+ 'CREATE COLLATION ares_runtime_version_collation FROM "C"; '+ "ALTER TABLE alembic_version "+ "ALTER COLUMN version_num TYPE VARCHAR(32) "+ "COLLATE ares_runtime_version_collation"+ ),+ "relation-rls": (+ "ALTER TABLE campaigns ENABLE ROW LEVEL SECURITY"+ ),+ "relation-forced-rls": (+ "ALTER TABLE campaigns ENABLE ROW LEVEL SECURITY; "+ "ALTER TABLE campaigns FORCE ROW LEVEL SECURITY"+ ),+ "relation-inheritance": (+ "CREATE TABLE ares_runtime_campaign_child() "+ "INHERITS (campaigns)"+ ),+ "relation-policy": (+ "CREATE POLICY ares_runtime_policy "+ "ON campaigns USING (true)"+ ),+ "relation-trigger": (+ "CREATE FUNCTION ares_runtime_trigger() "+ "RETURNS trigger LANGUAGE plpgsql "+ "AS $$ BEGIN RETURN NEW; END $$; "+ "CREATE TRIGGER ares_runtime_trigger "+ "BEFORE UPDATE ON campaigns FOR EACH ROW "+ "EXECUTE FUNCTION ares_runtime_trigger()"+ ),+ "relation-rule": (+ "CREATE RULE ares_runtime_rule AS "+ "ON UPDATE TO campaigns DO ALSO NOTHING"+ ),+ "missing-foreign-key": (+ "ALTER TABLE api_keys "+ "DROP CONSTRAINT fk_api_keys_user"+ ),+ "wrong-foreign-key": (+ "ALTER TABLE api_keys "+ "DROP CONSTRAINT fk_api_keys_user; "+ "ALTER TABLE api_keys "+ "ADD CONSTRAINT fk_api_keys_user "+ "FOREIGN KEY(user_id) REFERENCES campaigns(id) "+ "ON DELETE CASCADE"+ ),+ "duplicate-foreign-key": (+ "ALTER TABLE api_keys "+ "ADD CONSTRAINT duplicate_api_keys_user "+ "FOREIGN KEY(user_id) REFERENCES users(id) "+ "ON DELETE CASCADE"+ ),+ "extra-root-foreign-key": (+ "ALTER TABLE campaigns "+ "ADD CONSTRAINT unexpected_campaign_self_fk "+ "FOREIGN KEY(id) REFERENCES campaigns(id)"+ ),+ "extra-exclusion-constraint": (+ "ALTER TABLE campaigns "+ "ADD CONSTRAINT unexpected_campaign_exclusion "+ "EXCLUDE USING btree (id WITH =)"+ ),+ "missing-check": (+ "ALTER TABLE users "+ "DROP CONSTRAINT ck_users_created_at_finite"+ ),+ "wrong-check": (+ "ALTER TABLE rate_limit_events "+ "DROP CONSTRAINT ck_rate_limit_events_blocked_bool; "+ "ALTER TABLE rate_limit_events "+ "ADD CONSTRAINT ck_rate_limit_events_blocked_bool "+ "CHECK ((blocked=0) OR (blocked=1))"+ ),+ "missing-unique": (+ "ALTER TABLE users DROP CONSTRAINT uq_users_username"+ ),+ "wrong-unique": (+ "ALTER TABLE users DROP CONSTRAINT uq_users_username; "+ "ALTER TABLE users "+ "ADD CONSTRAINT uq_users_username UNIQUE(role)"+ ),+ "missing-sequence": "DROP SEQUENCE audit_log_id_seq CASCADE",+ "wrong-sequence-owner": (+ "ALTER SEQUENCE audit_log_id_seq OWNED BY NONE"+ ),+ "wrong-sequence-owner-schema": (+ "CREATE SCHEMA ares_runtime_shadow; "+ "CREATE TABLE ares_runtime_shadow.audit_log(id INTEGER NOT NULL); "+ "ALTER SEQUENCE audit_log_id_seq "+ "OWNED BY ares_runtime_shadow.audit_log.id"+ ),+ "wrong-sequence-options": (+ "ALTER SEQUENCE audit_log_id_seq INCREMENT BY 2"+ ),+ "wrong-sequence-default": (+ "ALTER TABLE audit_log ALTER COLUMN id SET DEFAULT 7"+ ),+ }+ statement = statements[drift]+ async with harness._postgres_harness() as target:+ await harness._alembic(target, "upgrade", "0008")+ connection = await harness._connect(target)+ try:+ await connection.execute(statement)+ finally:+ await connection.close()+ pools = _audit_runtime_pools(monkeypatch)+ database = _runtime_database(target)+ rejected = await _fixed_connect_result(database)+ _require_fixed(+ bool(drift)+ and rejected == _INCOMPATIBLE_SCHEMA+ and database._pool is None+ and len(pools) == 1+ and pools[0].fallback_count == 0+ and pools[0].close_count == 1,+ "managed PostgreSQL catalog drift entered fallback",+ )+++async def test_real_postgres_unversioned_startup_uses_runtime_fallback(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _postgres_test_config()+ from tests.integration import test_postgres_migration_portability as harness++ async with harness._postgres_harness() as target:+ pools = _audit_runtime_pools(monkeypatch)+ database = _runtime_database(target)+ try:+ connected = await _fixed_connect_result(database) == "connected"+ async with database._pool.acquire() as connection:+ state = await connection.fetchrow(+ """+ SELECT+ to_regclass('alembic_version') IS NULL AS unversioned,+ to_regclass('campaigns') IS NOT NULL AS runtime_created,+ to_regclass('websocket_tickets') IS NOT NULL+ AS tickets_created+ """+ )+ created = (+ state is not None+ and bool(state["unversioned"])+ and bool(state["runtime_created"])+ and bool(state["tickets_created"])+ )+ finally:+ await database.close()+ _require_fixed(+ connected+ and created+ and len(pools) == 1+ and pools[0].fallback_count == 1+ and pools[0].close_count == 1,+ "unversioned PostgreSQL runtime fallback changed",+ )+++async def _stamp_runtime_origin_0007(target: Any) -> None:+ database = _runtime_database(target)+ try:+ await database.connect()+ finally:+ await database.close()+ connection = await target_support_connect(target)+ try:+ await connection.execute(+ """+ CREATE TABLE alembic_version(+ version_num VARCHAR(32) NOT NULL,+ CONSTRAINT alembic_version_pkc PRIMARY KEY(version_num)+ )+ """+ )+ await connection.execute(+ "INSERT INTO alembic_version(version_num) VALUES('0007')"+ )+ finally:+ await connection.close()+++async def target_support_connect(target: Any) -> Any:+ from tests.integration import test_postgres_migration_portability as support++ return await support._connect(target)+++async def _application_data_digest(+ connection: Any,+ *,+ excluded_tables: frozenset[str] = frozenset(),+) -> tuple[object, ...]:+ values: list[object] = []+ try:+ for table in _EXPECTED_TABLES:+ if table in excluded_tables:+ continue+ table_exists = await connection.fetchval(+ "SELECT to_regclass($1) IS NOT NULL",+ table,+ )+ if not table_exists:+ values.append(None)+ continue+ row = await connection.fetchrow(+ f"""+ SELECT count(*)::bigint AS row_count,+ md5(+ coalesce(+ string_agg(+ row_to_json(value)::text,+ '' ORDER BY row_to_json(value)::text+ ),+ ''+ )+ ) AS row_digest+ FROM {table} AS value+ """ # noqa: S608+ )+ values.append(+ (+ int(row["row_count"]),+ str(row["row_digest"]),+ )+ )+ except Exception:+ raise RuntimeError("PostgreSQL data fingerprint failed") from None+ return tuple(values)+++async def _managed_object_identity_fingerprint(+ connection: Any,+) -> tuple[tuple[object, ...], tuple[object, ...]]:+ try:+ relations = tuple(+ (+ int(row["relation_oid"]),+ str(row["relation_name"]),+ str(row["relation_kind"]),+ int(row["relation_file"]),+ )+ for row in await connection.fetch(+ """+ SELECT+ relation.oid::bigint AS relation_oid,+ relation.relname AS relation_name,+ relation.relkind AS relation_kind,+ relation.relfilenode::bigint AS relation_file+ FROM pg_class AS relation+ JOIN pg_namespace AS namespace+ ON namespace.oid=relation.relnamespace+ WHERE namespace.nspname=current_schema()+ AND relation.relkind IN ('r', 'p', 'i', 'S')+ ORDER BY relation.relname, relation.oid+ """+ )+ )+ constraints = tuple(+ (+ int(row["constraint_oid"]),+ str(row["constraint_name"]),+ int(row["relation_oid"]),+ int(row["referenced_relation_oid"]),+ int(row["backing_index_oid"]),+ )+ for row in await connection.fetch(+ """+ SELECT+ constraint_record.oid::bigint AS constraint_oid,+ constraint_record.conname AS constraint_name,+ constraint_record.conrelid::bigint AS relation_oid,+ constraint_record.confrelid::bigint+ AS referenced_relation_oid,+ constraint_record.conindid::bigint AS backing_index_oid+ FROM pg_constraint AS constraint_record+ JOIN pg_class AS relation+ ON relation.oid=constraint_record.conrelid+ JOIN pg_namespace AS namespace+ ON namespace.oid=relation.relnamespace+ WHERE namespace.nspname=current_schema()+ ORDER BY relation.relname, constraint_record.conname+ """+ )+ )+ except Exception:+ raise RuntimeError(+ "PostgreSQL identity fingerprint failed"+ ) from None+ return relations, constraints+++def _same_catalog_without_revision(before: Any, after: Any) -> bool:+ return (+ before.schemas == after.schemas+ and before.relations == after.relations+ and before.columns == after.columns+ and before.constraints == after.constraints+ and before.indexes == after.indexes+ and before.sequences == after.sequences+ )+++async def test_real_postgres_correct_0007_is_data_preserving_noop() -> None:+ _postgres_test_config()+ from tests.integration import test_postgres_migration_portability as harness++ async with harness._postgres_harness() as target:+ await harness._alembic(target, "upgrade", "0007")+ connection = await harness._connect(target)+ try:+ await harness._seed_postgres_contract(connection)+ fast_default_rows = await connection.fetch(+ """+ SELECT attribute.attname,+ attribute.atthasmissing,+ attribute.attmissingval::text AS missing_value+ FROM pg_attribute AS attribute+ WHERE attribute.attrelid='findings'::regclass+ AND attribute.attname=ANY($1::text[])+ ORDER BY attribute.attname+ """,+ ["cvss_score", "cvss_vector", "trace_id"],+ )+ audited_fast_defaults = tuple(+ (+ str(row["attname"]),+ bool(row["atthasmissing"]),+ (+ str(row["missing_value"])+ if row["missing_value"] is not None+ else None+ ),+ )+ for row in fast_default_rows+ ) == (+ ("cvss_score", False, None),+ ("cvss_vector", False, None),+ ("trace_id", True, '{""}'),+ )+ before_catalog = await harness._postgres_isolation_fingerprint(+ connection+ )+ before_data = await _application_data_digest(connection)+ before_identity = await _managed_object_identity_fingerprint(+ connection+ )+ finally:+ await connection.close()+ await harness._alembic(target, "upgrade", "0008")+ connection = await harness._connect(target)+ try:+ after_catalog = await harness._postgres_isolation_fingerprint(+ connection+ )+ after_data = await _application_data_digest(connection)+ after_identity = await _managed_object_identity_fingerprint(+ connection+ )+ revision_current = await connection.fetchval(+ "SELECT version_num='0008' FROM alembic_version"+ )+ after_fast_default_rows = await connection.fetch(+ """+ SELECT attribute.attname,+ attribute.atthasmissing,+ attribute.attmissingval::text AS missing_value+ FROM pg_attribute AS attribute+ WHERE attribute.attrelid='findings'::regclass+ AND attribute.attname=ANY($1::text[])+ ORDER BY attribute.attname+ """,+ ["cvss_score", "cvss_vector", "trace_id"],+ )+ fast_defaults_preserved = tuple(+ (+ str(row["attname"]),+ bool(row["atthasmissing"]),+ (+ str(row["missing_value"])+ if row["missing_value"] is not None+ else None+ ),+ )+ for row in after_fast_default_rows+ ) == (+ ("cvss_score", False, None),+ ("cvss_vector", False, None),+ ("trace_id", True, '{""}'),+ )+ finally:+ await connection.close()+ identity_preserved = before_identity == after_identity+ _require_fixed(+ audited_fast_defaults+ and _same_catalog_without_revision(before_catalog, after_catalog)+ and before_data == after_data+ and identity_preserved+ and bool(revision_current)+ and bool(fast_defaults_preserved),+ "revision 0008 changed an exact revision 0007 database",+ )+++async def test_real_postgres_version_trigger_cannot_mutate_application_data(+) -> None:+ _postgres_test_config()+ from tests.integration import test_postgres_migration_portability as harness++ async with harness._postgres_harness() as target:+ await harness._alembic(target, "upgrade", "0007")+ connection = await harness._connect(target)+ try:+ await harness._seed_postgres_contract(connection)+ await connection.execute(+ """+ INSERT INTO campaigns(id, name, status)+ VALUES(+ 'version-trigger-campaign',+ 'synthetic',+ 'created'+ )+ """+ )+ await connection.execute(+ """+ CREATE FUNCTION ares_m0008_version_trigger()+ RETURNS trigger+ LANGUAGE plpgsql+ AS $$+ BEGIN+ UPDATE campaigns+ SET status='trigger-fired'+ WHERE id='version-trigger-campaign';+ RETURN NEW;+ END+ $$;+ CREATE TRIGGER ares_m0008_version_trigger+ AFTER UPDATE ON alembic_version+ FOR EACH ROW+ EXECUTE FUNCTION ares_m0008_version_trigger()+ """+ )+ transaction = connection.transaction()+ await transaction.start()+ try:+ await connection.execute(+ "UPDATE alembic_version SET version_num=version_num"+ )+ replay_capable = bool(+ await connection.fetchval(+ """+ SELECT status='trigger-fired'+ FROM campaigns+ WHERE id='version-trigger-campaign'+ """+ )+ )+ finally:+ await transaction.rollback()+ before_catalog = await harness._postgres_isolation_fingerprint(+ connection+ )+ before_data = await _application_data_digest(connection)+ finally:+ await connection.close()++ failed = False+ try:+ await harness._alembic(target, "upgrade", "0008")+ except RuntimeError:+ failed = True++ connection = await harness._connect(target)+ try:+ after_catalog = await harness._postgres_isolation_fingerprint(+ connection+ )+ after_data = await _application_data_digest(connection)+ state = await connection.fetchrow(+ """+ SELECT+ (+ SELECT version_num='0007'+ FROM alembic_version+ ) AS revision_unchanged,+ (+ SELECT status='created'+ FROM campaigns+ WHERE id='version-trigger-campaign'+ ) AS canary_unchanged,+ EXISTS(+ SELECT 1+ FROM pg_trigger AS trigger_record+ WHERE trigger_record.tgrelid='alembic_version'::regclass+ AND trigger_record.tgname=+ 'ares_m0008_version_trigger'+ AND NOT trigger_record.tgisinternal+ ) AS trigger_preserved+ """+ )+ unchanged = (+ state is not None+ and bool(state["revision_unchanged"])+ and bool(state["canary_unchanged"])+ and bool(state["trigger_preserved"])+ and before_catalog == after_catalog+ and before_data == after_data+ )+ if failed and unchanged:+ await connection.execute(+ """+ DROP TRIGGER ares_m0008_version_trigger+ ON alembic_version;+ DROP FUNCTION ares_m0008_version_trigger()+ """+ )+ finally:+ await connection.close()++ recovered = False+ if failed and unchanged:+ await harness._alembic(target, "upgrade", "0008")+ connection = await harness._connect(target)+ try:+ recovered = bool(+ await connection.fetchval(+ "SELECT version_num='0008' FROM alembic_version"+ )+ )+ finally:+ await connection.close()+ _require_fixed(+ replay_capable and failed and unchanged and recovered,+ "PostgreSQL version trigger bypassed migration preflight",+ )++[email protected]("attachment", ["policy", "rule"])+async def test_real_postgres_version_relation_attachment_is_atomic(+ attachment: str,+) -> None:+ _postgres_test_config()+ from tests.integration import test_postgres_migration_portability as harness++ mutation = {+ "policy": (+ "CREATE POLICY ares_m0008_version_policy "+ "ON alembic_version USING (true)"+ ),+ "rule": (+ "CREATE RULE ares_m0008_version_rule AS "+ "ON UPDATE TO alembic_version DO ALSO NOTHING"+ ),+ }[attachment]+ repair = {+ "policy": (+ "DROP POLICY ares_m0008_version_policy ON alembic_version"+ ),+ "rule": "DROP RULE ares_m0008_version_rule ON alembic_version",+ }[attachment]++ async with harness._postgres_harness() as target:+ await harness._alembic(target, "upgrade", "0007")+ connection = await harness._connect(target)+ try:+ await harness._seed_postgres_contract(connection)+ await connection.execute(mutation)+ before_catalog = await harness._postgres_isolation_fingerprint(+ connection+ )+ before_data = await _application_data_digest(connection)+ finally:+ await connection.close()++ failed = False+ try:+ await harness._alembic(target, "upgrade", "0008")+ except RuntimeError:+ failed = True++ connection = await harness._connect(target)+ try:+ after_catalog = await harness._postgres_isolation_fingerprint(+ connection+ )+ after_data = await _application_data_digest(connection)+ relation_oid = await connection.fetchval(+ "SELECT 'alembic_version'::regclass::oid"+ )+ attachment_count = (+ await connection.fetchval(+ """+ SELECT count(*)+ FROM pg_policy+ WHERE polrelid=$1::oid+ """,+ relation_oid,+ )+ if attachment == "policy"+ else await connection.fetchval(+ """+ SELECT count(*)+ FROM pg_rewrite+ WHERE ev_class=$1::oid+ """,+ relation_oid,+ )+ )+ revision_unchanged = await connection.fetchval(+ "SELECT version_num='0007' FROM alembic_version"+ )+ unchanged = (+ bool(revision_unchanged)+ and int(attachment_count) == 1+ and before_catalog == after_catalog+ and before_data == after_data+ )+ if failed and unchanged:+ await connection.execute(repair)+ finally:+ await connection.close()++ recovered = False+ if failed and unchanged:+ await harness._alembic(target, "upgrade", "0008")+ connection = await harness._connect(target)+ try:+ recovered = bool(+ await connection.fetchval(+ "SELECT version_num='0008' FROM alembic_version"+ )+ )+ finally:+ await connection.close()+ _require_fixed(+ failed and unchanged and recovered,+ "PostgreSQL version attachment bypassed migration preflight",+ )+++async def test_real_postgres_post_ddl_failure_rolls_back_completely() -> None:+ _postgres_test_config()+ from tests.integration import test_postgres_migration_portability as harness++ async with harness._postgres_harness() as target:+ await harness._alembic(target, "upgrade", "0007")+ connection = await harness._connect(target)+ try:+ await harness._seed_postgres_contract(connection)+ await connection.execute(+ """+ ALTER TABLE findings+ ALTER COLUMN trace_id DROP NOT NULL+ """+ )+ before_catalog = await harness._postgres_isolation_fingerprint(+ connection+ )+ before_data = await _application_data_digest(connection)+ finally:+ await connection.close()++ failed = False+ try:+ await harness._alembic(+ target,+ "upgrade",+ "0008",+ fault="0005-after-alter",+ )+ except RuntimeError:+ failed = True++ connection = await harness._connect(target)+ try:+ after_catalog = await harness._postgres_isolation_fingerprint(+ connection+ )+ after_data = await _application_data_digest(connection)+ state = await connection.fetchrow(+ """+ SELECT+ (+ SELECT version_num='0007'+ FROM alembic_version+ ) AS revision_unchanged,+ NOT (+ SELECT attnotnull+ FROM pg_attribute+ WHERE attrelid='findings'::regclass+ AND attname='trace_id'+ AND attnum > 0+ AND NOT attisdropped+ ) AS alteration_rolled_back,+ (SELECT 1)=1 AS connection_reusable+ """+ )+ rolled_back = (+ state is not None+ and bool(state["revision_unchanged"])+ and bool(state["alteration_rolled_back"])+ and bool(state["connection_reusable"])+ and before_catalog == after_catalog+ and before_data == after_data+ )+ finally:+ await connection.close()++ recovered = False+ if failed and rolled_back:+ await harness._alembic(target, "upgrade", "0008")+ connection = await harness._connect(target)+ try:+ state = await connection.fetchrow(+ """+ SELECT+ (+ SELECT version_num='0008'+ FROM alembic_version+ ) AS revision_current,+ (+ SELECT attnotnull+ FROM pg_attribute+ WHERE attrelid='findings'::regclass+ AND attname='trace_id'+ AND attnum > 0+ AND NOT attisdropped+ ) AS column_hardened+ """+ )+ recovered = (+ state is not None+ and bool(state["revision_current"])+ and bool(state["column_hardened"])+ )+ finally:+ await connection.close()+ _require_fixed(+ failed and rolled_back and recovered,+ "PostgreSQL migration failure did not roll back real DDL",+ )+++async def test_real_postgres_runtime_origin_converges_without_data_loss(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _postgres_test_config()+ from tests.integration import test_postgres_migration_portability as harness++ async with harness._postgres_harness() as target:+ await _stamp_runtime_origin_0007(target)+ connection = await harness._connect(target)+ try:+ await connection.execute(+ """+ ALTER TABLE findings+ ALTER COLUMN cvss_score DROP NOT NULL;+ ALTER TABLE findings+ ALTER COLUMN cvss_vector DROP NOT NULL;+ ALTER TABLE findings+ ALTER COLUMN trace_id DROP NOT NULL+ """+ )+ await connection.execute(+ """+ INSERT INTO campaigns(id, name)+ VALUES('runtime-campaign', 'synthetic')+ """+ )+ await connection.execute(+ """+ INSERT INTO module_runs(+ id, campaign_id, module_id, outcome+ )+ VALUES(+ 'runtime-run',+ 'runtime-campaign',+ 'synthetic-module',+ 'synthetic'+ )+ """+ )+ finally:+ await connection.close()+ await harness._alembic(target, "upgrade", "0008")+ connection = await harness._connect(target)+ try:+ state = await connection.fetchrow(+ """+ SELECT+ (+ SELECT version_num='0008'+ FROM alembic_version+ ) AS revision_current,+ to_regclass('rate_limit_events') IS NOT NULL+ AS missing_table_reconciled,+ (+ SELECT count(*)=0+ FROM pg_indexes+ WHERE schemaname=current_schema()+ AND indexname LIKE 'idx_pg_%'+ ) AS legacy_indexes_removed,+ (+ SELECT count(*)=$1+ FROM pg_indexes+ WHERE schemaname=current_schema()+ AND indexname=ANY($2::text[])+ ) AS canonical_indexes_present,+ (+ SELECT count(*)=1+ FROM campaigns+ WHERE id='runtime-campaign'+ ) AS campaign_preserved,+ (+ SELECT count(*)=1+ FROM module_runs+ WHERE id='runtime-run'+ ) AS run_preserved,+ (+ SELECT bool_and(attribute.attnotnull)+ FROM pg_attribute AS attribute+ WHERE attribute.attrelid='findings'::regclass+ AND attribute.attname=ANY($3::text[])+ ) AS findings_hardened,+ (+ SELECT array_agg(+ attribute.attname::text+ ORDER BY attribute.attnum+ )=$4::text[]+ FROM pg_attribute AS attribute+ WHERE attribute.attrelid='findings'::regclass+ AND attribute.attnum > 0+ AND NOT attribute.attisdropped+ ) AS audited_order_preserved+ """,+ len(_EXPECTED_INDEXES),+ [name for _, name, _, _ in _EXPECTED_INDEXES],+ ["cvss_score", "cvss_vector", "trace_id"],+ [+ "id",+ "campaign_id",+ "module_id",+ "title",+ "description",+ "severity",+ "confidence",+ "mitre_technique",+ "mitre_tactic",+ "cvss_score",+ "cvss_vector",+ "trace_id",+ "evidence_json",+ "remediation",+ "host",+ "validated",+ "false_positive",+ "discovered_at",+ ],+ )+ converged = (+ state is not None+ and all(bool(value) for value in state.values())+ )+ finally:+ await connection.close()+ pools = _audit_runtime_pools(monkeypatch)+ database = _runtime_database(target)+ try:+ guard_accepted = (+ await _fixed_connect_result(database) == "connected"+ )+ finally:+ await database.close()+ _require_fixed(+ converged+ and guard_accepted+ and len(pools) == 1+ and pools[0].fallback_count == 0,+ "revision 0008 did not reconcile runtime-origin drift",+ )+++async def test_real_postgres_supported_legacy_objects_converge(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _postgres_test_config()+ from tests.integration import test_postgres_migration_portability as harness++ async with harness._postgres_harness() as target:+ await harness._alembic(target, "upgrade", "0007")+ connection = await harness._connect(target)+ try:+ await harness._seed_postgres_contract(connection)+ await connection.execute(+ """+ DROP TABLE module_runs;+ CREATE INDEX idx_findings_validated+ ON findings(validated);+ CREATE TABLE ares_m0008_unrelated_probe(+ id INTEGER PRIMARY KEY,+ marker TEXT NOT NULL+ );+ INSERT INTO ares_m0008_unrelated_probe(id, marker)+ VALUES(1, 'preserved')+ """+ )+ before_data = await _application_data_digest(+ connection,+ excluded_tables=frozenset({"module_runs"}),+ )+ finally:+ await connection.close()++ await harness._alembic(target, "upgrade", "0008")+ pools = _audit_runtime_pools(monkeypatch)+ database = _runtime_database(target)+ connected = await _fixed_connect_result(database) == "connected"+ try:+ async with database._pool.acquire() as connection:+ after_data = await _application_data_digest(+ connection,+ excluded_tables=frozenset({"module_runs"}),+ )+ state = await connection.fetchrow(+ """+ SELECT+ (+ SELECT version_num='0008'+ FROM alembic_version+ ) AS revision_current,+ to_regclass('module_runs') IS NOT NULL+ AS module_table_present,+ EXISTS(+ SELECT 1+ FROM pg_constraint+ WHERE conrelid='module_runs'::regclass+ AND conname='fk_module_runs_campaign'+ AND contype='f'+ ) AS module_fk_present,+ EXISTS(+ SELECT 1+ FROM pg_constraint+ WHERE conrelid='module_runs'::regclass+ AND conname=+ 'ck_module_runs_completed_at_finite'+ AND contype='c'+ ) AS module_check_present,+ (+ SELECT array_agg(indexname ORDER BY indexname)+ FROM pg_indexes+ WHERE schemaname=current_schema()+ AND tablename='module_runs'+ ) = ARRAY[+ 'idx_module_runs_campaign',+ 'idx_module_runs_completed',+ 'module_runs_pkey'+ ]::name[] AS module_indexes_exact,+ to_regclass('idx_findings_validated') IS NULL+ AS obsolete_index_removed,+ (+ SELECT marker='preserved'+ FROM ares_m0008_unrelated_probe+ WHERE id=1+ ) AS unrelated_preserved+ """+ )+ converged = (+ state is not None+ and bool(state["revision_current"])+ and bool(state["module_table_present"])+ and bool(state["module_fk_present"])+ and bool(state["module_check_present"])+ and bool(state["module_indexes_exact"])+ and bool(state["obsolete_index_removed"])+ and bool(state["unrelated_preserved"])+ and before_data == after_data+ )+ finally:+ await database.close()+ _require_fixed(+ connected+ and converged+ and len(pools) == 1+ and pools[0].fallback_count == 0+ and pools[0].close_count == 1,+ "supported PostgreSQL legacy objects did not converge safely",+ )+++async def test_real_postgres_non_equivalent_legacy_index_rolls_back() -> None:+ _postgres_test_config()+ from tests.integration import test_postgres_migration_portability as harness++ async with harness._postgres_harness() as target:+ await harness._alembic(target, "upgrade", "0007")+ connection = await harness._connect(target)+ try:+ await connection.execute(+ """+ CREATE INDEX idx_pg_findings_mitre+ ON findings(severity)+ """+ )+ before = await harness._postgres_isolation_fingerprint(connection)+ finally:+ await connection.close()+ failed = False+ try:+ await harness._alembic(target, "upgrade", "0008")+ except RuntimeError:+ failed = True+ connection = await harness._connect(target)+ try:+ after = await harness._postgres_isolation_fingerprint(connection)+ revision_unchanged = await connection.fetchval(+ "SELECT version_num='0007' FROM alembic_version"+ )+ finally:+ await connection.close()+ _require_fixed(+ failed and before == after and bool(revision_unchanged),+ "non-equivalent PostgreSQL legacy index was mutated",+ )+++_COLUMN_AND_RELATION_MUTATIONS = (+ pytest.param("missing-column", id="missing-column"),+ pytest.param("extra-column", id="extra-column"),+ pytest.param("wrong-order", id="wrong-order"),+ pytest.param("wrong-type", id="wrong-type"),+ pytest.param("wrong-nullability", id="wrong-nullability"),+ pytest.param("wrong-default", id="wrong-default"),+ pytest.param("identity-column", id="identity-column"),+ pytest.param("generated-column", id="generated-column"),+ pytest.param("custom-collation", id="custom-collation"),+ pytest.param("sequence-default", id="sequence-default"),+ pytest.param("sequence-ownership", id="sequence-ownership"),+ pytest.param("sequence-owner-schema", id="sequence-owner-schema"),+ pytest.param("sequence-options", id="sequence-options"),+ pytest.param(+ "planned-primary-relation",+ id="planned-primary-relation",+ ),+ pytest.param(+ "planned-unique-relation",+ id="planned-unique-relation",+ ),+ pytest.param(+ "planned-sequence-relation",+ id="planned-sequence-relation",+ ),+ pytest.param("optional-type-collision", id="optional-type-collision"),+ pytest.param("root-foreign-key", id="root-foreign-key"),+ pytest.param("duplicate-foreign-key", id="duplicate-foreign-key"),+ pytest.param(+ "extra-exclusion-constraint",+ id="extra-exclusion-constraint",+ ),+ pytest.param("regrouped-check", id="regrouped-check"),+ pytest.param(+ "ticket-scope-literal-case",+ id="ticket-scope-literal-case",+ ),+ pytest.param(+ "ticket-hash-literal-case",+ id="ticket-hash-literal-case",+ ),+ pytest.param(+ "canonical-index-unrelated",+ id="canonical-index-unrelated",+ ),+ pytest.param("alias-index-unrelated", id="alias-index-unrelated"),+ pytest.param(+ "obsolete-index-unrelated",+ id="obsolete-index-unrelated",+ ),+ pytest.param(+ "reserved-constraint-index",+ id="reserved-constraint-index",+ ),+ pytest.param("reserved-alias-relation", id="reserved-alias-relation"),+ pytest.param("relation-rls", id="relation-rls"),+ pytest.param("relation-forced-rls", id="relation-forced-rls"),+ pytest.param("relation-policy", id="relation-policy"),+ pytest.param("relation-trigger", id="relation-trigger"),+ pytest.param("relation-rule", id="relation-rule"),+ pytest.param("relation-inheritance", id="relation-inheritance"),+ pytest.param("relation-view", id="relation-view"),+ pytest.param("relation-partition", id="relation-partition"),+)+++async def _apply_column_or_relation_mutation(+ connection: Any,+ mutation: str,+) -> None:+ if mutation == "missing-column":+ await connection.execute(+ "ALTER TABLE campaigns DROP COLUMN notes"+ )+ elif mutation == "extra-column":+ await connection.execute(+ "ALTER TABLE campaigns ADD COLUMN unexpected_column TEXT"+ )+ elif mutation == "wrong-order":+ await connection.execute(+ """+ ALTER TABLE campaigns DROP COLUMN notes;+ ALTER TABLE campaigns+ ADD COLUMN notes TEXT DEFAULT ''+ """+ )+ elif mutation == "wrong-type":+ await connection.execute(+ """+ ALTER TABLE campaigns+ ALTER COLUMN notes TYPE VARCHAR(64)+ """+ )+ elif mutation == "wrong-nullability":+ await connection.execute(+ """+ ALTER TABLE campaigns+ ALTER COLUMN notes SET NOT NULL+ """+ )+ elif mutation == "wrong-default":+ await connection.execute(+ """+ ALTER TABLE campaigns+ ALTER COLUMN status SET DEFAULT 'unexpected'+ """+ )+ elif mutation == "identity-column":+ await connection.execute(+ """+ ALTER TABLE audit_log ALTER COLUMN id DROP DEFAULT;+ ALTER TABLE audit_log+ ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY+ """+ )+ elif mutation == "generated-column":+ await connection.execute(+ """+ ALTER TABLE campaigns DROP COLUMN notes;+ ALTER TABLE campaigns ADD COLUMN notes TEXT+ GENERATED ALWAYS AS (''::text) STORED+ """+ )+ elif mutation == "custom-collation":+ await connection.execute(+ """+ CREATE COLLATION ares_m0008_collation FROM "C";+ ALTER TABLE campaigns+ ALTER COLUMN notes TYPE TEXT+ COLLATE ares_m0008_collation+ """+ )+ elif mutation == "sequence-default":+ await connection.execute(+ """+ ALTER TABLE audit_log+ ALTER COLUMN id SET DEFAULT 7+ """+ )+ elif mutation == "sequence-ownership":+ await connection.execute(+ "ALTER SEQUENCE audit_log_id_seq OWNED BY NONE"+ )+ elif mutation == "sequence-owner-schema":+ await connection.execute(+ """+ CREATE SCHEMA ares_m0008_shadow;+ CREATE TABLE ares_m0008_shadow.audit_log(+ id INTEGER NOT NULL+ );+ ALTER SEQUENCE audit_log_id_seq+ OWNED BY ares_m0008_shadow.audit_log.id+ """+ )+ elif mutation == "sequence-options":+ await connection.execute(+ "ALTER SEQUENCE audit_log_id_seq INCREMENT BY 2"+ )+ elif mutation == "planned-primary-relation":+ await connection.execute(+ """+ DROP TABLE module_runs;+ CREATE TABLE module_runs_pkey(value TEXT)+ """+ )+ elif mutation == "planned-unique-relation":+ await connection.execute(+ """+ ALTER TABLE users DROP CONSTRAINT uq_users_username;+ CREATE TABLE uq_users_username(value TEXT)+ """+ )+ elif mutation == "planned-sequence-relation":+ await connection.execute(+ """+ DROP TABLE rate_limit_events;+ CREATE TABLE rate_limit_events_id_seq(value TEXT)+ """+ )+ elif mutation == "optional-type-collision":+ await connection.execute(+ """+ DROP TABLE module_runs;+ CREATE DOMAIN module_runs AS TEXT+ """+ )+ elif mutation == "root-foreign-key":+ await connection.execute(+ """+ ALTER TABLE campaigns+ ADD CONSTRAINT unexpected_campaign_self_fk+ FOREIGN KEY(id) REFERENCES campaigns(id)+ """+ )+ elif mutation == "duplicate-foreign-key":+ await connection.execute(+ """+ ALTER TABLE api_keys+ ADD CONSTRAINT duplicate_api_keys_user+ FOREIGN KEY(user_id) REFERENCES users(id)+ ON DELETE CASCADE+ """+ )+ elif mutation == "extra-exclusion-constraint":+ await connection.execute(+ """+ ALTER TABLE campaigns+ ADD CONSTRAINT unexpected_campaign_exclusion+ EXCLUDE USING btree (id WITH =)+ """+ )+ elif mutation == "regrouped-check":+ await connection.execute(+ """+ ALTER TABLE websocket_tickets+ DROP CONSTRAINT ck_ws_ticket_time_order;+ ALTER TABLE websocket_tickets+ ADD CONSTRAINT ck_ws_ticket_time_order+ CHECK (+ (expires_at > created_at AND consumed_at IS NULL)+ OR consumed_at < expires_at+ )+ """+ )+ elif mutation == "ticket-scope-literal-case":+ await connection.execute(+ """+ ALTER TABLE websocket_tickets+ DROP CONSTRAINT ck_ws_ticket_source_shape;+ ALTER TABLE websocket_tickets+ ADD CONSTRAINT ck_ws_ticket_source_shape+ CHECK (+ credential_kind = 'bearer'::text+ AND bearer_subject IS NOT NULL+ AND length(btrim(bearer_subject)) > 0+ AND bearer_subject = btrim(bearer_subject)+ AND bearer_jti IS NOT NULL+ AND length(btrim(bearer_jti)) > 0+ AND bearer_jti = btrim(bearer_jti)+ AND bearer_expires_at IS NOT NULL+ AND api_key_id IS NULL+ AND required_scope IS NULL+ OR credential_kind = 'api_key'::text+ AND bearer_subject IS NULL+ AND bearer_jti IS NULL+ AND bearer_expires_at IS NULL+ AND api_key_id IS NOT NULL+ AND length(btrim(api_key_id)) > 0+ AND api_key_id = btrim(api_key_id)+ AND required_scope = 'READ'::text+ )+ """+ )+ elif mutation == "ticket-hash-literal-case":+ await connection.execute(+ """+ ALTER TABLE websocket_tickets+ DROP CONSTRAINT ck_ws_ticket_hash;+ UPDATE websocket_tickets+ SET ticket_hash=upper(ticket_hash);+ ALTER TABLE websocket_tickets+ ADD CONSTRAINT ck_ws_ticket_hash+ CHECK (ticket_hash ~ '^[0-9A-F]{64}$'::text)+ """+ )+ elif mutation == "canonical-index-unrelated":+ await connection.execute(+ """+ DROP INDEX idx_users_role;+ CREATE INDEX idx_users_role ON campaigns(status)+ """+ )+ elif mutation == "alias-index-unrelated":+ await connection.execute(+ """+ CREATE INDEX idx_pg_users_username+ ON campaigns(status)+ """+ )+ elif mutation == "obsolete-index-unrelated":+ await connection.execute(+ """+ CREATE INDEX idx_findings_validated+ ON campaigns(status)+ """+ )+ elif mutation == "reserved-constraint-index":+ await connection.execute(+ """+ ALTER TABLE campaigns+ ADD CONSTRAINT idx_pg_users_username UNIQUE(status)+ """+ )+ elif mutation == "reserved-alias-relation":+ await connection.execute(+ """+ CREATE TABLE idx_pg_users_username(+ value TEXT+ )+ """+ )+ elif mutation == "relation-rls":+ await connection.execute(+ "ALTER TABLE campaigns ENABLE ROW LEVEL SECURITY"+ )+ elif mutation == "relation-forced-rls":+ await connection.execute(+ """+ ALTER TABLE campaigns ENABLE ROW LEVEL SECURITY;+ ALTER TABLE campaigns FORCE ROW LEVEL SECURITY+ """+ )+ elif mutation == "relation-policy":+ await connection.execute(+ """+ CREATE POLICY ares_m0008_policy+ ON campaigns USING (true)+ """+ )+ elif mutation == "relation-trigger":+ await connection.execute(+ """+ CREATE FUNCTION ares_m0008_trigger()+ RETURNS trigger+ LANGUAGE plpgsql+ AS $$+ BEGIN+ RETURN NEW;+ END+ $$;+ CREATE TRIGGER ares_m0008_trigger+ BEFORE UPDATE ON campaigns+ FOR EACH ROW+ EXECUTE FUNCTION ares_m0008_trigger()+ """+ )+ elif mutation == "relation-rule":+ await connection.execute(+ """+ CREATE RULE ares_m0008_rule AS+ ON UPDATE TO campaigns DO ALSO NOTHING+ """+ )+ elif mutation == "relation-inheritance":+ await connection.execute(+ """+ CREATE TABLE ares_m0008_campaign_child()+ INHERITS (campaigns)+ """+ )+ elif mutation == "relation-view":+ await connection.execute(+ """+ DROP TABLE module_runs CASCADE;+ CREATE VIEW module_runs AS+ SELECT+ NULL::text AS id,+ NULL::text AS campaign_id,+ NULL::text AS module_id,+ NULL::text AS outcome,+ 0::integer AS success,+ 0::double precision AS duration_ms,+ now() AS completed_at+ WHERE false+ """+ )+ elif mutation == "relation-partition":+ await connection.execute(+ """+ DROP TABLE rate_limit_events;+ CREATE TABLE rate_limit_events(+ id INTEGER NOT NULL,+ ip_address TEXT NOT NULL,+ bucket TEXT NOT NULL,+ username TEXT,+ blocked INTEGER NOT NULL DEFAULT 0,+ timestamp TIMESTAMPTZ NOT NULL DEFAULT now()+ ) PARTITION BY RANGE(id)+ """+ )+ else:+ raise AssertionError("unknown PostgreSQL catalog mutation")+++ "catalog_mutation",+ _COLUMN_AND_RELATION_MUTATIONS,+)+async def test_real_postgres_unapproved_column_or_relation_shape_is_atomic(+ catalog_mutation: str,+) -> None:+ _postgres_test_config()+ from tests.integration import test_postgres_migration_portability as harness++ async with harness._postgres_harness() as target:+ await harness._alembic(target, "upgrade", "0007")+ connection = await harness._connect(target)+ try:+ await harness._seed_postgres_contract(connection)+ await _apply_column_or_relation_mutation(+ connection,+ catalog_mutation,+ )+ before = await harness._postgres_isolation_fingerprint(connection)+ before_data = await _application_data_digest(connection)+ finally:+ await connection.close()+ failed = False+ try:+ await harness._alembic(target, "upgrade", "0008")+ except RuntimeError:+ failed = True+ connection = await harness._connect(target)+ try:+ after = await harness._postgres_isolation_fingerprint(connection)+ after_data = await _application_data_digest(connection)+ revision_unchanged = await connection.fetchval(+ "SELECT version_num='0007' FROM alembic_version"+ )+ finally:+ await connection.close()+ _require_fixed(+ failed+ and before == after+ and before_data == after_data+ and bool(revision_unchanged),+ "unapproved PostgreSQL catalog shape was not atomic",+ )+++async def test_real_postgres_unreserved_idx_pg_name_is_preserved() -> None:+ _postgres_test_config()+ from tests.integration import test_postgres_migration_portability as harness++ async with harness._postgres_harness() as target:+ await harness._alembic(target, "upgrade", "0007")+ connection = await harness._connect(target)+ try:+ await connection.execute(+ """+ CREATE TABLE ares_m0008_unmanaged(value TEXT);+ CREATE INDEX idx_pg_unmanaged_custom+ ON ares_m0008_unmanaged(value)+ """+ )+ finally:+ await connection.close()+ await harness._alembic(target, "upgrade", "0008")+ connection = await harness._connect(target)+ try:+ preserved = await connection.fetchval(+ """+ SELECT to_regclass('ares_m0008_unmanaged') IS NOT NULL+ AND to_regclass('idx_pg_unmanaged_custom') IS NOT NULL+ AND (+ SELECT version_num='0008'+ FROM alembic_version+ )+ """+ )+ finally:+ await connection.close()+ _require_fixed(+ bool(preserved),+ "unreserved PostgreSQL index metadata was not preserved",+ )+++async def test_real_postgres_source_credential_column_is_renamed_safely(+) -> None:+ _postgres_test_config()+ from tests.integration import test_postgres_migration_portability as harness++ async with harness._postgres_harness() as target:+ await harness._alembic(target, "upgrade", "0007")+ connection = await harness._connect(target)+ try:+ await harness._seed_postgres_contract(connection)+ await connection.execute(+ """+ ALTER TABLE credentials+ RENAME COLUMN cracked_value_enc TO cracked_value+ """+ )+ await connection.execute(+ """+ UPDATE credentials+ SET cracked_value='synthetic-protected-marker'+ """+ )+ before_data = await _application_data_digest(+ connection,+ excluded_tables=frozenset({"credentials"}),+ )+ before_credentials = tuple(+ tuple(row.values())+ for row in await connection.fetch(+ """+ SELECT+ id,+ campaign_id,+ host_id,+ username,+ secret_enc,+ cred_type,+ domain,+ source_module,+ notes,+ cracked,+ cracked_value AS protected_value,+ captured_at+ FROM credentials+ ORDER BY id+ """+ )+ )+ before_marker_present = bool(before_credentials) and all(+ row[10] is not None and bool(str(row[10]))+ for row in before_credentials+ )+ finally:+ await connection.close()+ await harness._alembic(target, "upgrade", "0008")+ connection = await harness._connect(target)+ try:+ after_data = await _application_data_digest(+ connection,+ excluded_tables=frozenset({"credentials"}),+ )+ after_credentials = tuple(+ tuple(row.values())+ for row in await connection.fetch(+ """+ SELECT+ id,+ campaign_id,+ host_id,+ username,+ secret_enc,+ cred_type,+ domain,+ source_module,+ notes,+ cracked,+ cracked_value_enc AS protected_value,+ captured_at+ FROM credentials+ ORDER BY id+ """+ )+ )+ names = tuple(+ str(row["attname"])+ for row in await connection.fetch(+ """+ SELECT attribute.attname+ FROM pg_attribute AS attribute+ WHERE attribute.attrelid='credentials'::regclass+ AND attribute.attnum > 0+ AND NOT attribute.attisdropped+ ORDER BY attribute.attnum+ """+ )+ )+ revision_current = await connection.fetchval(+ "SELECT version_num='0008' FROM alembic_version"+ )+ renamed = (+ "cracked_value_enc" in names+ and "cracked_value" not in names+ )+ finally:+ await connection.close()+ credentials_preserved = (+ before_marker_present+ and before_credentials == after_credentials+ )+ _require_fixed(+ before_data == after_data+ and credentials_preserved+ and renamed+ and bool(revision_current),+ "credential column reconciliation changed protected data",+ )+++_CREDENTIAL_COLUMN_FAILURES = (+ pytest.param("both", id="both-columns"),+ pytest.param("neither", id="neither-column"),+ pytest.param("wrong-source", id="wrong-source"),+)+++ "credential_mutation",+ _CREDENTIAL_COLUMN_FAILURES,+)+async def test_real_postgres_invalid_credential_column_state_is_atomic(+ credential_mutation: str,+) -> None:+ _postgres_test_config()+ from tests.integration import test_postgres_migration_portability as harness++ async with harness._postgres_harness() as target:+ await harness._alembic(target, "upgrade", "0007")+ connection = await harness._connect(target)+ try:+ await harness._seed_postgres_contract(connection)+ if credential_mutation == "both":+ await connection.execute(+ """+ ALTER TABLE credentials+ ADD COLUMN cracked_value TEXT+ """+ )+ elif credential_mutation == "neither":+ await connection.execute(+ """+ ALTER TABLE credentials+ DROP COLUMN cracked_value_enc+ """+ )+ elif credential_mutation == "wrong-source":+ await connection.execute(+ """+ ALTER TABLE credentials+ RENAME COLUMN cracked_value_enc TO cracked_value;+ ALTER TABLE credentials+ ALTER COLUMN cracked_value SET DEFAULT ''+ """+ )+ else:+ raise AssertionError(+ "unknown PostgreSQL credential-column mutation"+ )+ before = await harness._postgres_isolation_fingerprint(connection)+ before_data = await _application_data_digest(connection)+ finally:+ await connection.close()+ failed = False+ try:+ await harness._alembic(target, "upgrade", "0008")+ except RuntimeError:+ failed = True+ connection = await harness._connect(target)+ try:+ after = await harness._postgres_isolation_fingerprint(connection)+ after_data = await _application_data_digest(connection)+ revision_unchanged = await connection.fetchval(+ "SELECT version_num='0007' FROM alembic_version"+ )+ finally:+ await connection.close()+ _require_fixed(+ failed+ and before == after+ and before_data == after_data+ and bool(revision_unchanged),+ "invalid PostgreSQL credential-column state was not atomic",+ )+++async def _prepare_unsafe_runtime_case(+ connection: Any,+ case: str,+) -> None:+ if case == "orphan":+ await connection.execute(+ """+ ALTER TABLE module_runs+ DROP CONSTRAINT module_runs_campaign_id_fkey+ """+ )+ await connection.execute(+ """+ INSERT INTO module_runs(+ id, campaign_id, module_id, outcome+ )+ VALUES(+ 'unsafe-run',+ 'missing-campaign',+ 'synthetic-module',+ 'synthetic'+ )+ """+ )+ elif case == "null":+ await connection.execute(+ "ALTER TABLE findings ALTER COLUMN trace_id DROP NOT NULL"+ )+ await connection.execute(+ """+ INSERT INTO campaigns(id, name)+ VALUES('unsafe-campaign', 'synthetic')+ """+ )+ await connection.execute(+ """+ INSERT INTO findings(+ id, campaign_id, module_id, title, description,+ severity, trace_id+ )+ VALUES(+ 'unsafe-finding',+ 'unsafe-campaign',+ 'synthetic-module',+ 'synthetic',+ 'synthetic',+ 'low',+ NULL+ )+ """+ )+ elif case == "flag":+ await connection.execute(+ """+ CREATE TABLE rate_limit_events(+ id SERIAL PRIMARY KEY,+ ip_address TEXT NOT NULL,+ bucket TEXT NOT NULL,+ username TEXT,+ blocked INTEGER NOT NULL DEFAULT 0,+ timestamp TIMESTAMPTZ NOT NULL DEFAULT now()+ )+ """+ )+ await connection.execute(+ """+ INSERT INTO rate_limit_events(ip_address, bucket, blocked)+ VALUES('192.0.2.1', 'synthetic', 2)+ """+ )+ elif case == "infinity":+ await connection.execute(+ """+ INSERT INTO campaigns(id, name, created_at)+ VALUES('unsafe-campaign', 'synthetic', 'infinity')+ """+ )+ else:+ raise AssertionError("unknown unsafe PostgreSQL fixture")++[email protected]("unsafe_case", ["orphan", "null", "flag", "infinity"])+async def test_real_postgres_unsafe_runtime_data_rolls_back_atomically(+ unsafe_case: str,+) -> None:+ _postgres_test_config()+ from tests.integration import test_postgres_migration_portability as harness++ async with harness._postgres_harness() as target:+ await _stamp_runtime_origin_0007(target)+ connection = await harness._connect(target)+ try:+ await _prepare_unsafe_runtime_case(connection, unsafe_case)+ before = await harness._postgres_isolation_fingerprint(connection)+ before_data = await _application_data_digest(connection)+ finally:+ await connection.close()+ failed = False+ try:+ await harness._alembic(target, "upgrade", "0008")+ except RuntimeError:+ failed = True+ connection = await harness._connect(target)+ try:+ after = await harness._postgres_isolation_fingerprint(connection)+ after_data = await _application_data_digest(connection)+ revision_unchanged = await connection.fetchval(+ "SELECT version_num='0007' FROM alembic_version"+ )+ finally:+ await connection.close()+ _require_fixed(+ failed+ and before == after+ and before_data == after_data+ and bool(revision_unchanged),+ "unsafe PostgreSQL reconciliation was not atomic",+ )+++_BOOLEAN_DATA_MUTATIONS = (+ pytest.param("module-success", id="module-success"),+ pytest.param("finding-validated", id="finding-validated"),+ pytest.param("finding-false-positive", id="finding-false-positive"),+ pytest.param("host-domain-controller", id="host-domain-controller"),+ pytest.param("credential-cracked", id="credential-cracked"),+ pytest.param("user-active", id="user-active"),+ pytest.param("api-key-active", id="api-key-active"),+ pytest.param("refresh-revoked", id="refresh-revoked"),+ pytest.param("rate-blocked", id="rate-blocked"),+)+++ "boolean_mutation",+ _BOOLEAN_DATA_MUTATIONS,+)+async def test_real_postgres_invalid_integer_boolean_is_atomic(+ boolean_mutation: str,+) -> None:+ _postgres_test_config()+ from tests.integration import test_postgres_migration_portability as harness++ mutation_targets = {+ "module-success": ("module_runs", "success"),+ "finding-validated": ("findings", "validated"),+ "finding-false-positive": ("findings", "false_positive"),+ "host-domain-controller": ("hosts", "is_dc"),+ "credential-cracked": ("credentials", "cracked"),+ "user-active": ("users", "is_active"),+ "api-key-active": ("api_keys", "is_active"),+ "refresh-revoked": ("refresh_tokens", "is_revoked"),+ "rate-blocked": ("rate_limit_events", "blocked"),+ }+ table, column = mutation_targets[boolean_mutation]+ async with harness._postgres_harness() as target:+ await harness._alembic(target, "upgrade", "0007")+ connection = await harness._connect(target)+ try:+ await harness._seed_postgres_contract(connection)+ await connection.execute(+ f'UPDATE "{table}" SET "{column}"=2' # noqa: S608+ )+ before = await harness._postgres_isolation_fingerprint(connection)+ before_data = await _application_data_digest(connection)+ finally:+ await connection.close()+ failed = False+ try:+ await harness._alembic(target, "upgrade", "0008")+ except RuntimeError:+ failed = True+ connection = await harness._connect(target)+ try:+ after = await harness._postgres_isolation_fingerprint(connection)+ after_data = await _application_data_digest(connection)+ revision_unchanged = await connection.fetchval(+ "SELECT version_num='0007' FROM alembic_version"+ )+ finally:+ await connection.close()+ _require_fixed(+ failed+ and before == after+ and before_data == after_data+ and bool(revision_unchanged),+ "unsafe PostgreSQL Boolean data was not atomic",+ )+++_FINITE_TIMESTAMPS = (+ ("campaigns", "created_at", "ck_campaigns_created_at_finite", False),+ ("campaigns", "updated_at", "ck_campaigns_updated_at_finite", False),+ (+ "module_runs",+ "completed_at",+ "ck_module_runs_completed_at_finite",+ False,+ ),+ (+ "findings",+ "discovered_at",+ "ck_findings_discovered_at_finite",+ False,+ ),+ ("hosts", "first_seen", "ck_hosts_first_seen_finite", False),+ ("hosts", "last_seen", "ck_hosts_last_seen_finite", False),+ (+ "credentials",+ "captured_at",+ "ck_credentials_captured_at_finite",+ False,+ ),+ ("loot", "captured_at", "ck_loot_captured_at_finite", False),+ ("audit_log", "timestamp", "ck_audit_log_timestamp_finite", False),+ ("users", "created_at", "ck_users_created_at_finite", False),+ ("users", "last_login", "ck_users_last_login_finite", True),+ ("api_keys", "last_used", "ck_api_keys_last_used_finite", True),+ ("api_keys", "expires_at", "ck_api_keys_expires_at_finite", True),+ ("api_keys", "created_at", "ck_api_keys_created_at_finite", False),+ (+ "refresh_tokens",+ "expires_at",+ "ck_refresh_tokens_expires_at_finite",+ False,+ ),+ (+ "refresh_tokens",+ "created_at",+ "ck_refresh_tokens_created_at_finite",+ False,+ ),+ (+ "refresh_tokens",+ "used_at",+ "ck_refresh_tokens_used_at_finite",+ True,+ ),+ (+ "revoked_access_tokens",+ "revoked_at",+ "ck_revoked_access_tokens_revoked_at_finite",+ False,+ ),+ (+ "revoked_access_tokens",+ "expires_at",+ "ck_revoked_access_tokens_expires_at_finite",+ False,+ ),+ (+ "rate_limit_events",+ "timestamp",+ "ck_rate_limit_events_timestamp_finite",+ False,+ ),+)+++async def test_real_postgres_all_managed_timestamps_enforce_finite_values(+) -> None:+ _postgres_test_config()+ from tests.integration import test_postgres_migration_portability as harness++ async with harness._postgres_harness() as target:+ await _stamp_runtime_origin_0007(target)+ await harness._alembic(target, "upgrade", "0008")+ connection = await harness._connect(target)+ try:+ await harness._seed_postgres_contract(connection)+ enforcement_valid = True+ finite_value = datetime(2099, 1, 1, tzinfo=timezone.utc)+ for table, column, constraint, nullable in _FINITE_TIMESTAMPS:+ catalog = await connection.fetchrow(+ """+ SELECT pg_get_constraintdef(con.oid, true) AS definition+ FROM pg_constraint AS con+ JOIN pg_class AS rel ON rel.oid=con.conrelid+ JOIN pg_namespace AS nsp ON nsp.oid=rel.relnamespace+ WHERE nsp.nspname=current_schema()+ AND rel.relname=$1+ AND con.conname=$2+ AND con.contype='c'+ AND con.convalidated+ """,+ table,+ constraint,+ )+ definition = (+ str(catalog["definition"]).replace(" ", "").lower()+ if catalog is not None+ else ""+ )+ expected_term = f"isfinite({column})"+ catalog_valid = expected_term in definition+ if nullable:+ catalog_valid = (+ catalog_valid and f"{column}isnull" in definition+ )++ finite_update = await connection.execute(+ (+ f"UPDATE {table} SET {column}=$1 " # noqa: S608+ f"WHERE ctid=(SELECT ctid FROM {table} LIMIT 1)"+ ),+ finite_value,+ )+ finite_succeeded = finite_update.startswith("UPDATE 1")+ infinity_rejected = []+ for unsafe in ("infinity", "-infinity"):+ rejected = False+ try:+ await connection.execute(+ f"UPDATE {table} " # noqa: S608+ f"SET {column}='{unsafe}'::timestamptz "+ f"WHERE ctid=("+ f"SELECT ctid FROM {table} LIMIT 1)"+ )+ except Exception:+ rejected = True+ reusable = await connection.fetchval("SELECT true")+ infinity_rejected.append(rejected and bool(reusable))++ null_rejected = False+ null_accepted = False+ try:+ null_result = await connection.execute(+ f"UPDATE {table} SET {column}=NULL " # noqa: S608+ f"WHERE ctid=(SELECT ctid FROM {table} LIMIT 1)"+ )+ null_accepted = null_result.startswith("UPDATE 1")+ except Exception:+ null_rejected = True+ reusable = await connection.fetchval("SELECT true")+ null_valid = (+ null_accepted+ if nullable+ else null_rejected+ ) and bool(reusable)+ enforcement_valid = (+ enforcement_valid+ and catalog_valid+ and finite_succeeded+ and all(infinity_rejected)+ and null_valid+ )+ finally:+ await connection.close()+ _require_fixed(+ enforcement_valid,+ "PostgreSQL finite timestamp contract diverged",+ )+++async def test_real_postgres_downgrade_refusal_is_non_mutating() -> None:+ _postgres_test_config()+ from tests.integration import test_postgres_migration_portability as harness++ async with harness._postgres_harness() as target:+ await harness._alembic(target, "upgrade", "0008")+ connection = await harness._connect(target)+ try:+ await harness._seed_postgres_contract(connection)+ before = await harness._postgres_isolation_fingerprint(connection)+ before_data = await _application_data_digest(connection)+ finally:+ await connection.close()+ refused = False+ try:+ await harness._alembic(target, "downgrade", "0007")+ except RuntimeError:+ refused = True+ connection = await harness._connect(target)+ try:+ after = await harness._postgres_isolation_fingerprint(connection)+ after_data = await _application_data_digest(connection)+ revision_current = await connection.fetchval(+ "SELECT version_num='0008' FROM alembic_version"+ )+ finally:+ await connection.close()+ _require_fixed(+ refused+ and before == after+ and before_data == after_data+ and bool(revision_current),+ "revision 0008 downgrade refusal mutated PostgreSQL state",+ )+++async def test_real_postgres_target_decoy_and_maintenance_are_isolated() -> None:+ _postgres_test_config()+ from tests.integration import test_postgres_migration_portability as harness++ async with harness._postgres_harness() as target:+ async with harness._postgres_harness() as decoy:+ maintenance_before = await harness._database_fingerprint(+ target.config,+ target.config.maintenance_database,+ )+ decoy_before = await harness._database_fingerprint(+ decoy.config,+ decoy.database_name,+ )+ await harness._alembic(target, "upgrade", "0008")+ target_after = await harness._database_fingerprint(+ target.config,+ target.database_name,+ )+ decoy_after = await harness._database_fingerprint(+ decoy.config,+ decoy.database_name,+ )+ maintenance_after = await harness._database_fingerprint(+ target.config,+ target.config.maintenance_database,+ )+ isolated = (+ bool(target_after.versions)+ and decoy_before == decoy_after+ and harness._isolation_fingerprint_has_no_ares_state(decoy_after)+ and maintenance_before == maintenance_after+ )+ _require_fixed(+ isolated,+ "PostgreSQL revision 0008 migrated an unselected database",+ )diff --git a/tests/integration/test_postgres_websocket_tickets.py b/tests/integration/test_postgres_websocket_tickets.pyindex 0164da9..ea70dd4 100644--- a/tests/integration/test_postgres_websocket_tickets.py+++ b/tests/integration/test_postgres_websocket_tickets.py@@ -40,7 +40,7 @@ _SAFE_EXCEPTION_TYPE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")_POSTGRES_OPERATION_TIMEOUT_SECONDS = 15.0_MIGRATION_PROCESS_TIMEOUT_SECONDS = 45.0_MIGRATION_ACTIONS = frozenset({"upgrade", "downgrade"})-_MIGRATION_REVISIONS = frozenset({"0006", "0007"})+_MIGRATION_REVISIONS = frozenset({"0006", "0007", "0008"})_OWNED_MIGRATION_PROCESSES: set[Any] = set()@@ -2922,7 +2922,7 @@ async def test_postgres_issue_returns_only_after_transaction_exit() -> None:@pytest.mark.asyncio-async def test_postgres_revision_0007_upgrade_and_downgrade(+async def test_postgres_revision_0007_ownership_and_0008_compatibility() -> None:migration_catalog: dict[str, object] | None = Noneasync with _postgres_harness(initialize_runtime=False) as harness:@@ -3129,20 +3129,106 @@ async def test_postgres_revision_0007_upgrade_and_downgrade(for name in ("users", "campaigns", "api_keys"))and _ticket_catalog_matches_fixed_contract(reupgraded_catalog)- and reupgraded_catalog == migration_catalog)_require_fixed(final_state_is_exact,"PostgreSQL ticket re-upgrade contract changed",)+ connection = await _connect()+ try:+ await connection.execute(+ """+ INSERT INTO websocket_tickets(+ ticket_hash, campaign_id, user_id, credential_kind,+ api_key_id, required_scope, created_at, expires_at+ )+ VALUES(+ $1, $2, $3, 'api_key', $4, 'read',+ now(), now() + interval '30 seconds'+ )+ """,+ "e" * 64,+ seed_campaign,+ seed_user,+ seed_key,+ )+ ticket_catalog_before_0008 = (+ await _ticket_catalog_fingerprint(connection)+ )+ ticket_rows_before_0008 = await connection.fetch(+ """+ SELECT ticket_hash, campaign_id, user_id, credential_kind,+ bearer_subject, bearer_jti, bearer_expires_at,+ api_key_id, required_scope, created_at, expires_at,+ consumed_at+ FROM websocket_tickets+ ORDER BY ticket_hash+ """+ )+ finally:+ await _attempt_cleanup(+ "migration-pre-0008-close",+ connection.close,+ [],+ )++ _run_ticket_migration(harness.database_name, "upgrade", "0008")+ connection = await _connect()+ try:+ migration_catalog = await _ticket_catalog_fingerprint(connection)+ ticket_rows_after_0008 = await connection.fetch(+ """+ SELECT ticket_hash, campaign_id, user_id, credential_kind,+ bearer_subject, bearer_jti, bearer_expires_at,+ api_key_id, required_scope, created_at, expires_at,+ consumed_at+ FROM websocket_tickets+ ORDER BY ticket_hash+ """+ )+ head_state = await connection.fetchrow(+ """+ SELECT+ (SELECT version_num FROM alembic_version) AS revision,+ (SELECT COUNT(*) FROM users WHERE id=$1) AS users,+ (SELECT COUNT(*) FROM campaigns WHERE id=$2) AS campaigns,+ (SELECT COUNT(*) FROM api_keys WHERE id=$3) AS api_keys+ """,+ seed_user,+ seed_campaign,+ seed_key,+ )+ finally:+ await _attempt_cleanup(+ "migration-0008-close",+ connection.close,+ [],+ )+ revision_0008_is_compatible = (+ head_state is not None+ and head_state["revision"] == "0008"+ and all(+ int(head_state[name]) == 1+ for name in ("users", "campaigns", "api_keys")+ )+ and _ticket_catalog_matches_fixed_contract(migration_catalog)+ and migration_catalog == ticket_catalog_before_0008+ and tuple(ticket_rows_after_0008)+ == tuple(ticket_rows_before_0008)+ )+ _require_fixed(+ revision_0008_is_compatible,+ "revision 0008 changed the revision 0007 ticket contract",+ )+async with _postgres_harness() as runtime_harness:async with runtime_harness.database._pool.acquire() as connection:runtime_catalog = await _ticket_catalog_fingerprint(connection)parity = (migration_catalog is not Noneand _ticket_catalog_matches_fixed_contract(runtime_catalog)- and runtime_catalog == migration_catalog+ and _ticket_catalog_matches_fixed_contract(migration_catalog))_require_fixed(parity,diff --git a/tests/unit/test_schema_reconciliation_migration.py b/tests/unit/test_schema_reconciliation_migration.pynew file mode 100644index 0000000..47e1b96--- /dev/null+++ b/tests/unit/test_schema_reconciliation_migration.py@@ -0,0 +1,2310 @@+"""SQLite coverage for revision 0008 schema reconciliation."""+from __future__ import annotations++import asyncio+import importlib+import re+import sqlite3+import tempfile+from collections.abc import Iterator+from contextlib import contextmanager+from dataclasses import replace+from pathlib import Path+from types import SimpleNamespace++import pytest+import sqlalchemy as sa+from alembic import command+from alembic.config import Config++from ares.db.database import AresDatabase++_ROOT = Path(__file__).resolve().parents[2]+_CATALOG_ERROR = "Incompatible catalog for migration 0008"+_DATA_ERROR = "Unsafe data for migration 0008"+_FORWARD_ONLY_ERROR = "Migration 0008 is forward-only"+_DIALECT_ERROR = "Unsupported migration dialect"+++def _require_fixed(condition: bool, message: str) -> None:+ if not condition:+ pytest.fail(message, pytrace=False)+++@contextmanager+def _database(label: str) -> Iterator[Path]:+ with tempfile.TemporaryDirectory(+ prefix=f"ares-0008-{label}-",+ ignore_cleanup_errors=True,+ ) as directory:+ yield Path(directory) / "migration.db"+++def _config(path: Path) -> Config:+ config = Config(str(_ROOT / "alembic.ini"))+ config.set_main_option(+ "script_location",+ str(_ROOT / "migrations"),+ )+ config.set_main_option(+ "sqlalchemy.url",+ f"sqlite:///{path.as_posix()}",+ )+ return config+++def _upgrade(path: Path, revision: str) -> None:+ command.upgrade(_config(path), revision)+++def _downgrade(path: Path, revision: str) -> None:+ command.downgrade(_config(path), revision)+++def _connect(path: Path) -> sqlite3.Connection:+ connection = sqlite3.connect(path)+ connection.execute("PRAGMA foreign_keys=ON")+ return connection+++def _version(path: Path) -> str | None:+ with _connect(path) as connection:+ row = connection.execute(+ "SELECT version_num FROM alembic_version"+ ).fetchone()+ return None if row is None else str(row[0])+++def _catalog(path: Path) -> tuple[tuple[object, ...], ...]:+ with _connect(path) as connection:+ return tuple(+ connection.execute(+ """+ SELECT type, name, tbl_name, sql+ FROM sqlite_master+ WHERE name NOT LIKE 'sqlite_%'+ AND name != 'alembic_version'+ ORDER BY type, name+ """+ )+ )+++def _data(path: Path) -> tuple[tuple[str, tuple[tuple[object, ...], ...]], ...]:+ with _connect(path) as connection:+ tables = tuple(+ str(row[0])+ for row in connection.execute(+ """+ SELECT name+ FROM sqlite_master+ WHERE type='table'+ AND name NOT LIKE 'sqlite_%'+ AND name != 'alembic_version'+ ORDER BY name+ """+ )+ )+ return tuple(+ (+ table,+ tuple(+ connection.execute(+ f'SELECT * FROM "{table}" ORDER BY rowid' # noqa: S608+ )+ ),+ )+ for table in tables+ )+++def _logical_data(path: Path) -> tuple[tuple[str, tuple[object, ...]], ...]:+ with _connect(path) as connection:+ tables = tuple(+ str(row[0])+ for row in connection.execute(+ """+ SELECT name+ FROM sqlite_master+ WHERE type='table'+ AND name NOT LIKE 'sqlite_%'+ AND name != 'alembic_version'+ ORDER BY name+ """+ )+ )+ logical: list[tuple[str, tuple[object, ...]]] = []+ for table in tables:+ columns = tuple(+ str(row[1])+ for row in connection.execute(+ f'PRAGMA table_info("{table}")' # noqa: S608+ )+ )+ rows = tuple(+ sorted(+ tuple(sorted(zip(columns, tuple(row), strict=True)))+ for row in connection.execute(+ f'SELECT * FROM "{table}"' # noqa: S608+ )+ )+ )+ logical.append((table, rows))+ return tuple(logical)+++def _snapshot(path: Path) -> tuple[object, ...]:+ with _connect(path) as connection:+ sequence = tuple(+ connection.execute(+ "SELECT name, seq FROM sqlite_sequence ORDER BY name"+ )+ )+ foreign_keys = int(+ connection.execute("PRAGMA foreign_keys").fetchone()[0]+ )+ return (_version(path), _catalog(path), _data(path), sequence, foreign_keys)+++def _physical_catalog_identity(path: Path) -> tuple[object, ...]:+ with _connect(path) as connection:+ schema_version = int(+ connection.execute("PRAGMA schema_version").fetchone()[0]+ )+ objects = tuple(+ connection.execute(+ """+ SELECT type, name, tbl_name, rootpage+ FROM sqlite_master+ WHERE name NOT LIKE 'sqlite_%'+ ORDER BY type, name+ """+ )+ )+ return (schema_version, objects)+++def _complete_managed_contract_is_exact(path: Path) -> bool:+ from tests.unit import test_migration_portability as portability+ from tests.unit import test_websocket_ticket_migration as ticket++ with _connect(path) as connection:+ actual = portability._sqlite_catalog_contract(connection)+ non_ticket = replace(+ actual,+ tables=tuple(+ table for table in actual.tables if table != "websocket_tickets"+ ),+ columns=tuple(+ item for item in actual.columns if item[0] != "websocket_tickets"+ ),+ primary_keys=tuple(+ item+ for item in actual.primary_keys+ if item[0] != "websocket_tickets"+ ),+ unique_constraints=tuple(+ item+ for item in actual.unique_constraints+ if item[0] != "websocket_tickets"+ ),+ checks=tuple(+ item for item in actual.checks if item[0] != "websocket_tickets"+ ),+ foreign_keys=tuple(+ item+ for item in actual.foreign_keys+ if item[0] != "websocket_tickets"+ ),+ indexes=tuple(+ item for item in actual.indexes if item[0] != "websocket_tickets"+ ),+ )+ return (+ non_ticket == portability._fixed_sqlite_contract("0006")+ and ticket._ticket_contract(path)+ == ticket._EXPECTED_TICKET_CONTRACT+ )+++def _seed_graph(path: Path) -> None:+ with _connect(path) as connection:+ connection.execute(+ "INSERT INTO campaigns(id, name) VALUES('c1', 'campaign')"+ )+ connection.execute(+ """+ INSERT INTO hosts(id, campaign_id, ip_address)+ VALUES('h1', 'c1', '192.0.2.1')+ """+ )+ connection.execute(+ """+ INSERT INTO credentials(+ id, campaign_id, host_id, username, cred_type,+ cracked_value_enc+ ) VALUES('k1', 'c1', 'h1', 'alice', 'password', 'ciphertext')+ """+ )+ connection.execute(+ """+ INSERT INTO loot(id, campaign_id, host_id, loot_type, name)+ VALUES('l1', 'c1', 'h1', 'file', 'artifact')+ """+ )+ connection.execute(+ """+ INSERT INTO findings(+ id, campaign_id, module_id, title, description, severity,+ cvss_score, cvss_vector, trace_id+ ) VALUES(+ 'f1', 'c1', 'm1', 'finding', 'description', 'high',+ 8.1, 'vector', 'trace'+ )+ """+ )+ connection.execute(+ """+ INSERT INTO users(id, username, hashed_password)+ VALUES('u1', 'alice', 'hash')+ """+ )+ connection.execute(+ """+ INSERT INTO api_keys(+ id, user_id, name, key_hash, key_prefix+ ) VALUES('a1', 'u1', 'key', 'hash', 'prefix')+ """+ )+ connection.execute(+ """+ INSERT INTO refresh_tokens(id, user_id, expires_at)+ VALUES('r1', 'u1', '2099-01-01 00:00:00')+ """+ )+ connection.execute(+ """+ INSERT INTO websocket_tickets(+ ticket_hash, campaign_id, user_id, credential_kind,+ api_key_id, required_scope, created_at, expires_at+ ) VALUES(+ ?, 'c1', 'u1', 'api_key', 'a1', 'read',+ '2098-01-01T00:00:00.000Z',+ '2098-01-01T00:01:00.000Z'+ )+ """,+ ("a" * 64,),+ )+ connection.execute(+ """+ INSERT INTO audit_log(campaign_id, action)+ VALUES('c1', 'seed')+ """+ )+ connection.commit()+++def _attempt_upgrade(path: Path) -> str:+ try:+ _upgrade(path, "0008")+ except RuntimeError as exc:+ return str(exc)+ return ""+++async def _runtime_bootstrap(path: Path) -> None:+ database = AresDatabase(f"file:{path.resolve().as_posix()}?mode=rwc")+ await database.connect()+ await database.close()+++def _rewrite_table_sql(path: Path, table: str, old: str, new: str) -> None:+ with _connect(path) as connection:+ connection.execute("PRAGMA writable_schema=ON")+ row = connection.execute(+ """+ SELECT sql+ FROM sqlite_master+ WHERE type='table' AND name=?+ """,+ (table,),+ ).fetchone()+ if row is None or not isinstance(row[0], str) or old not in row[0]:+ raise AssertionError("legacy fixture source fragment is absent")+ connection.execute(+ """+ UPDATE sqlite_master+ SET sql=replace(sql, ?, ?)+ WHERE type='table' AND name=?+ """,+ (old, new, table),+ )+ connection.execute(+ "PRAGMA schema_version="+ f"{int(connection.execute('PRAGMA schema_version').fetchone()[0]) + 1}"+ )+ connection.execute("PRAGMA writable_schema=OFF")+ connection.commit()+++def _append_check_constraint(path: Path, table: str) -> None:+ with _connect(path) as connection:+ connection.execute("PRAGMA writable_schema=ON")+ connection.execute(+ """+ UPDATE sqlite_master+ SET sql=substr(sql, 1, length(sql) - 1)+ || ', CONSTRAINT unexpected_check CHECK (1))'+ WHERE type='table' AND name=?+ """,+ (table,),+ )+ connection.execute(+ "PRAGMA schema_version="+ f"{int(connection.execute('PRAGMA schema_version').fetchone()[0]) + 1}"+ )+ connection.execute("PRAGMA writable_schema=OFF")+ connection.commit()+++def _remove_users_unique_constraint(path: Path) -> None:+ with _connect(path) as connection:+ connection.execute("PRAGMA foreign_keys=OFF")+ connection.execute(+ """+ CREATE TABLE users_without_unique (+ id TEXT NOT NULL PRIMARY KEY,+ username TEXT NOT NULL,+ hashed_password TEXT NOT NULL,+ role TEXT DEFAULT 'reporter' NOT NULL,+ is_active INTEGER DEFAULT '1' NOT NULL,+ created_by TEXT DEFAULT 'system' NOT NULL,+ created_at TEXT DEFAULT (datetime('now')) NOT NULL,+ last_login TEXT+ )+ """+ )+ connection.execute(+ """+ INSERT INTO users_without_unique+ SELECT * FROM users+ """+ )+ connection.execute("DROP TABLE users")+ connection.execute(+ "ALTER TABLE users_without_unique RENAME TO users"+ )+ connection.execute(+ "CREATE INDEX idx_users_username ON users(username)"+ )+ connection.execute("CREATE INDEX idx_users_role ON users(role)")+ connection.commit()+++def _replace_users_unique_contract(path: Path, variant: str) -> None:+ unique_sql = {+ "duplicate": (+ "CONSTRAINT uq_users_username UNIQUE(username)"+ ),+ "nocase": (+ "CONSTRAINT uq_users_username "+ "UNIQUE(username COLLATE NOCASE)"+ ),+ }[variant]+ with _connect(path) as connection:+ connection.execute("PRAGMA foreign_keys=OFF")+ connection.execute(+ f"""+ CREATE TABLE users_unique_variant (+ id TEXT NOT NULL PRIMARY KEY,+ username TEXT NOT NULL,+ hashed_password TEXT NOT NULL,+ role TEXT DEFAULT 'reporter' NOT NULL,+ is_active INTEGER DEFAULT '1' NOT NULL,+ created_by TEXT DEFAULT 'system' NOT NULL,+ created_at TEXT DEFAULT (datetime('now')) NOT NULL,+ last_login TEXT,+ {unique_sql}+ )+ """+ )+ connection.execute(+ """+ INSERT INTO users_unique_variant+ SELECT * FROM users+ """+ )+ connection.execute("DROP TABLE users")+ connection.execute(+ "ALTER TABLE users_unique_variant RENAME TO users"+ )+ connection.execute(+ "CREATE INDEX idx_users_username ON users(username)"+ )+ connection.execute("CREATE INDEX idx_users_role ON users(role)")+ if variant == "duplicate":+ connection.execute(+ "CREATE UNIQUE INDEX unexpected_duplicate_user "+ "ON users(username)"+ )+ connection.commit()+++def _append_table_constraint(+ path: Path,+ table: str,+ definition: str,+) -> None:+ with _connect(path) as connection:+ connection.execute("PRAGMA writable_schema=ON")+ connection.execute(+ """+ UPDATE sqlite_master+ SET sql=substr(sql, 1, length(sql) - 1) || ', ' || ? || ')'+ WHERE type='table' AND name=?+ """,+ (definition, table),+ )+ connection.execute(+ "PRAGMA schema_version="+ f"{int(connection.execute('PRAGMA schema_version').fetchone()[0]) + 1}"+ )+ connection.execute("PRAGMA writable_schema=OFF")+ connection.commit()+++def _replace_findings_with_historical_order(path: Path) -> None:+ with _connect(path) as connection:+ connection.execute("PRAGMA foreign_keys=OFF")+ connection.execute(+ """+ CREATE TABLE findings_historical (+ id TEXT NOT NULL PRIMARY KEY,+ campaign_id TEXT NOT NULL,+ module_id TEXT NOT NULL,+ title TEXT NOT NULL,+ description TEXT NOT NULL,+ severity TEXT NOT NULL,+ cvss_score FLOAT DEFAULT 0.0 NOT NULL,+ cvss_vector TEXT DEFAULT '' NOT NULL,+ confidence FLOAT DEFAULT 1.0 NOT NULL,+ mitre_technique TEXT,+ mitre_tactic TEXT,+ evidence_json TEXT DEFAULT '{}' NOT NULL,+ remediation TEXT DEFAULT '',+ host TEXT,+ validated INTEGER DEFAULT 0 NOT NULL,+ false_positive INTEGER DEFAULT 0 NOT NULL,+ discovered_at TEXT DEFAULT (datetime('now')) NOT NULL,+ trace_id TEXT DEFAULT '' NOT NULL,+ CONSTRAINT fk_findings_campaign+ FOREIGN KEY(campaign_id)+ REFERENCES campaigns(id) ON DELETE CASCADE+ )+ """+ )+ connection.execute(+ """+ INSERT INTO findings_historical(+ id, campaign_id, module_id, title, description, severity,+ cvss_score, cvss_vector, confidence, mitre_technique,+ mitre_tactic, evidence_json, remediation, host, validated,+ false_positive, discovered_at, trace_id+ )+ SELECT+ id, campaign_id, module_id, title, description, severity,+ cvss_score, cvss_vector, confidence, mitre_technique,+ mitre_tactic, evidence_json, remediation, host, validated,+ false_positive, discovered_at, trace_id+ FROM findings+ """+ )+ connection.execute("DROP TABLE findings")+ connection.execute(+ "ALTER TABLE findings_historical RENAME TO findings"+ )+ connection.execute(+ "CREATE INDEX idx_findings_campaign ON findings(campaign_id)"+ )+ connection.execute(+ "CREATE INDEX idx_findings_severity ON findings(severity)"+ )+ connection.execute(+ "CREATE INDEX idx_findings_fp ON findings(false_positive)"+ )+ connection.execute(+ "CREATE INDEX idx_findings_mitre ON findings(mitre_technique)"+ )+ connection.execute(+ "CREATE INDEX idx_findings_cvss ON findings(cvss_score)"+ )+ connection.commit()+++def _replace_campaigns_with_nocase_primary_key(path: Path) -> None:+ with _connect(path) as connection:+ connection.execute("PRAGMA foreign_keys=OFF")+ connection.execute(+ """+ CREATE TABLE campaigns_nocase (+ id TEXT COLLATE NOCASE NOT NULL PRIMARY KEY,+ name TEXT NOT NULL,+ client TEXT DEFAULT 'Internal' NOT NULL,+ operator TEXT DEFAULT 'unknown' NOT NULL,+ noise_profile TEXT DEFAULT 'stealth' NOT NULL,+ status TEXT DEFAULT 'created' NOT NULL,+ scope_json TEXT DEFAULT '[]' NOT NULL,+ targets_json TEXT DEFAULT '[]' NOT NULL,+ notes TEXT DEFAULT '',+ created_at TEXT DEFAULT (datetime('now')) NOT NULL,+ updated_at TEXT DEFAULT (datetime('now')) NOT NULL+ )+ """+ )+ connection.execute(+ """+ INSERT INTO campaigns_nocase+ SELECT * FROM campaigns+ """+ )+ connection.execute("DROP TABLE campaigns")+ connection.execute(+ "ALTER TABLE campaigns_nocase RENAME TO campaigns"+ )+ connection.commit()+++def _weaken_ticket_hash_check_with_comment(path: Path) -> None:+ pattern = re.compile(+ r"""+ CONSTRAINT\s+ck_ws_ticket_hash\s++ CHECK\s*\(\s*+ length\s*\(\s*ticket_hash\s*\)\s*=\s*64\s++ AND\s+ticket_hash\s+NOT\s+GLOB\s++ '\*\[\^0-9a-f\]\*'\s*+ \)+ """,+ re.IGNORECASE | re.VERBOSE,+ )+ expected_fragment = (+ "CONSTRAINT ck_ws_ticket_hash CHECK ("+ "length(ticket_hash)=64 AND "+ "ticket_hash NOT GLOB '*[^0-9a-f]*')"+ )+ replacement = (+ "CONSTRAINT ck_ws_ticket_hash CHECK /* parser gap */ (1) "+ f"/* {expected_fragment} */"+ )+ with _connect(path) as connection:+ row = connection.execute(+ """+ SELECT sql FROM sqlite_master+ WHERE type='table' AND name='websocket_tickets'+ """+ ).fetchone()+ if row is None or not isinstance(row[0], str):+ raise AssertionError("ticket table fixture source is absent")+ rewritten, count = pattern.subn(replacement, row[0], count=1)+ if count != 1:+ raise AssertionError("ticket check fixture source is absent")+ connection.execute("PRAGMA writable_schema=ON")+ connection.execute(+ """+ UPDATE sqlite_master+ SET sql=?+ WHERE type='table' AND name='websocket_tickets'+ """,+ (rewritten,),+ )+ connection.execute(+ "PRAGMA schema_version="+ f"{int(connection.execute('PRAGMA schema_version').fetchone()[0]) + 1}"+ )+ connection.execute("PRAGMA writable_schema=OFF")+ connection.commit()+++def _replace_ticket_contract_fragment(+ path: Path,+ source_pattern: str,+ replacement: str,+) -> None:+ with _connect(path) as connection:+ row = connection.execute(+ """+ SELECT sql FROM sqlite_master+ WHERE type='table' AND name='websocket_tickets'+ """+ ).fetchone()+ if row is None or not isinstance(row[0], str):+ raise AssertionError("ticket table fixture source is absent")+ rewritten, count = re.subn(+ source_pattern,+ replacement,+ row[0],+ count=1,+ flags=re.IGNORECASE,+ )+ if count != 1:+ raise AssertionError("ticket literal fixture source is absent")+ connection.execute("PRAGMA writable_schema=ON")+ connection.execute(+ """+ UPDATE sqlite_master+ SET sql=?+ WHERE type='table' AND name='websocket_tickets'+ """,+ (rewritten,),+ )+ connection.execute(+ "PRAGMA schema_version="+ f"{int(connection.execute('PRAGMA schema_version').fetchone()[0]) + 1}"+ )+ connection.execute("PRAGMA writable_schema=OFF")+ connection.commit()+++def _spoof_audit_autoincrement_with_comment(path: Path) -> None:+ with _connect(path) as connection:+ row = connection.execute(+ """+ SELECT sql FROM sqlite_master+ WHERE type='table' AND name='audit_log'+ """+ ).fetchone()+ if row is None or not isinstance(row[0], str):+ raise AssertionError("audit table fixture source is absent")+ rewritten, count = re.subn(+ r"\bAUTOINCREMENT\b",+ "/* AUTOINCREMENT */",+ row[0],+ count=1,+ flags=re.IGNORECASE,+ )+ if count != 1:+ raise AssertionError("audit AUTOINCREMENT fixture source is absent")+ connection.execute("PRAGMA writable_schema=ON")+ connection.execute(+ """+ UPDATE sqlite_master+ SET sql=?+ WHERE type='table' AND name='audit_log'+ """,+ (rewritten,),+ )+ connection.execute(+ "PRAGMA schema_version="+ f"{int(connection.execute('PRAGMA schema_version').fetchone()[0]) + 1}"+ )+ connection.execute("PRAGMA writable_schema=OFF")+ connection.commit()+++def _weaken_blocked_check_with_comment(path: Path) -> None:+ pattern = re.compile(+ r"""+ CONSTRAINT\s+ck_rate_limit_events_blocked_bool\s++ CHECK\s*\(\s*blocked\s+IN\s*\(\s*0\s*,\s*1\s*\)\s*\)+ """,+ re.IGNORECASE | re.VERBOSE,+ )+ expected_fragment = (+ "CONSTRAINT ck_rate_limit_events_blocked_bool "+ "CHECK (blocked IN (0, 1))"+ )+ replacement = (+ "CONSTRAINT ck_rate_limit_events_blocked_bool "+ "CHECK /* parser gap */ (1) "+ f"/* {expected_fragment} */"+ )+ with _connect(path) as connection:+ row = connection.execute(+ """+ SELECT sql FROM sqlite_master+ WHERE type='table' AND name='rate_limit_events'+ """+ ).fetchone()+ if row is None or not isinstance(row[0], str):+ raise AssertionError("rate-limit table fixture source is absent")+ rewritten, count = pattern.subn(replacement, row[0], count=1)+ if count != 1:+ raise AssertionError("blocked-check fixture source is absent")+ connection.execute("PRAGMA writable_schema=ON")+ connection.execute(+ """+ UPDATE sqlite_master+ SET sql=?+ WHERE type='table' AND name='rate_limit_events'+ """,+ (rewritten,),+ )+ connection.execute(+ "PRAGMA schema_version="+ f"{int(connection.execute('PRAGMA schema_version').fetchone()[0]) + 1}"+ )+ connection.execute("PRAGMA writable_schema=OFF")+ connection.commit()+++def test_empty_base_upgrades_to_real_0008_head() -> None:+ with _database("empty") as path:+ _upgrade(path, "head")+ with _connect(path) as connection:+ tables = {+ str(row[0])+ for row in connection.execute(+ "SELECT name FROM sqlite_master WHERE type='table'"+ )+ }+ foreign_keys = int(+ connection.execute("PRAGMA foreign_keys").fetchone()[0]+ )+ _require_fixed(+ _version(path) == "0008"+ and {"module_runs", "rate_limit_events", "websocket_tickets"}+ <= tables+ and _complete_managed_contract_is_exact(path)+ and foreign_keys == 1,+ "empty-base upgrade did not produce the managed 0008 schema",+ )+++ "starting_revision",+ ["0001", "0002", "0003", "0004", "0005", "0006", "0007"],+)+def test_each_supported_historical_revision_upgrades_to_0008(+ starting_revision: str,+) -> None:+ with _database(f"historical-{starting_revision}") as path:+ _upgrade(path, starting_revision)+ with _connect(path) as connection:+ connection.execute(+ "INSERT INTO campaigns(id, name) VALUES('c1', 'campaign')"+ )+ connection.execute(+ """+ INSERT INTO users(id, username, hashed_password)+ VALUES('u1', 'account', 'hash')+ """+ )+ connection.commit()+ _upgrade(path, "0008")+ with _connect(path) as connection:+ preserved = (+ connection.execute(+ "SELECT count(*) FROM campaigns WHERE id='c1'"+ ).fetchone()[0]+ == 1+ and connection.execute(+ "SELECT count(*) FROM users WHERE id='u1'"+ ).fetchone()[0]+ == 1+ )+ _require_fixed(+ _version(path) == "0008"+ and preserved+ and _complete_managed_contract_is_exact(path),+ "supported historical revision did not upgrade losslessly",+ )+++def test_exact_0007_is_catalog_and_data_noop_except_version() -> None:+ with _database("exact-noop") as path:+ _upgrade(path, "0007")+ _seed_graph(path)+ before = _snapshot(path)+ identity_before = _physical_catalog_identity(path)+ _upgrade(path, "0008")+ after = _snapshot(path)+ identity_after = _physical_catalog_identity(path)+ _require_fixed(+ before[0] == "0007"+ and after[0] == "0008"+ and after[1:] == before[1:]+ and identity_after == identity_before,+ "exact revision 0007 changed outside Alembic version state",+ )+++def test_missing_owned_tables_and_indexes_are_recreated_with_data_preserved(+) -> None:+ with _database("missing") as path:+ _upgrade(path, "0007")+ _seed_graph(path)+ with _connect(path) as connection:+ connection.execute("DROP TABLE module_runs")+ connection.execute("DROP TABLE rate_limit_events")+ connection.execute("DROP INDEX idx_findings_mitre")+ connection.execute("DROP INDEX idx_creds_username")+ connection.commit()+ protected = _data(path)+ _upgrade(path, "0008")+ with _connect(path) as connection:+ objects = {+ str(row[0])+ for row in connection.execute(+ "SELECT name FROM sqlite_master WHERE type IN ('table','index')"+ )+ }+ _require_fixed(+ _version(path) == "0008"+ and {+ "module_runs",+ "rate_limit_events",+ "idx_findings_mitre",+ "idx_creds_username",+ }+ <= objects+ and _complete_managed_contract_is_exact(path)+ and all(+ rows == dict(_data(path)).get(table)+ for table, rows in protected+ ),+ "missing managed objects were not reconciled losslessly",+ )++[email protected]("object_kind", ["view", "index", "trigger"])+def test_optional_table_name_collision_is_rejected_before_mutation(+ object_kind: str,+) -> None:+ statements = {+ "view": "CREATE VIEW module_runs AS SELECT 1 AS id",+ "index": "CREATE INDEX module_runs ON campaigns(name)",+ "trigger": (+ "CREATE TRIGGER module_runs AFTER INSERT ON campaigns "+ "BEGIN SELECT 1; END"+ ),+ }+ with _database(f"optional-name-{object_kind}") as path:+ _upgrade(path, "0007")+ with _connect(path) as connection:+ connection.execute("DROP TABLE module_runs")+ connection.execute(statements[object_kind])+ connection.commit()+ before = _snapshot(path)+ observed = _attempt_upgrade(path)+ after = _snapshot(path)+ _require_fixed(+ observed == _CATALOG_ERROR+ and after == before+ and _version(path) == "0007",+ "optional-table name collision was not rejected atomically",+ )+++def test_representative_legacy_catalog_converges_and_is_repeat_stable() -> None:+ with _database("legacy") as path:+ _upgrade(path, "0007")+ _seed_graph(path)+ with _connect(path) as connection:+ connection.execute("DROP INDEX idx_findings_mitre")+ connection.execute(+ "CREATE INDEX idx_findings_validated ON findings(validated)"+ )+ connection.execute("DROP TABLE module_runs")+ connection.execute("DROP TABLE rate_limit_events")+ connection.commit()+ ticket_before = dict(_data(path))["websocket_tickets"]+ _upgrade(path, "0008")+ first = _snapshot(path)+ command.stamp(_config(path), "0007")+ _upgrade(path, "0008")+ second = _snapshot(path)+ _require_fixed(+ first == second+ and _complete_managed_contract_is_exact(path)+ and dict(_data(path))["websocket_tickets"] == ticket_before,+ "legacy reconciliation was unstable or changed ticket state",+ )+++def test_runtime_origin_stamped_0007_converges_to_fixed_contract() -> None:+ with _database("runtime-origin") as path:+ asyncio.run(_runtime_bootstrap(path))+ with _connect(path) as connection:+ before_order = tuple(+ str(row[1])+ for row in connection.execute(+ "PRAGMA table_info(findings)"+ )+ )+ connection.execute(+ """+ CREATE TABLE alembic_version(+ version_num VARCHAR(32) NOT NULL,+ CONSTRAINT alembic_version_pkc PRIMARY KEY(version_num)+ )+ """+ )+ connection.execute(+ "INSERT INTO alembic_version(version_num) VALUES('0007')"+ )+ connection.commit()+ _seed_graph(path)+ before_data = _logical_data(path)+ _upgrade(path, "0008")+ with _connect(path) as connection:+ after_order = tuple(+ str(row[1])+ for row in connection.execute(+ "PRAGMA table_info(findings)"+ )+ )+ _require_fixed(+ before_order.index("trace_id") < before_order.index("evidence_json")+ and after_order.index("trace_id") > after_order.index("discovered_at"),+ "runtime-origin findings order did not converge",+ )+ _require_fixed(+ _complete_managed_contract_is_exact(path),+ "runtime-origin catalog did not reach the fixed contract",+ )+ after_data = dict(_logical_data(path))+ _require_fixed(+ all(+ rows == after_data.get(table)+ for table, rows in before_data+ ),+ "runtime-origin application rows were not preserved",+ )+++def test_historical_cvss_before_confidence_order_converges_losslessly(+) -> None:+ with _database("historical-findings-order") as path:+ _upgrade(path, "0007")+ _seed_graph(path)+ _replace_findings_with_historical_order(path)+ with _connect(path) as connection:+ before_order = tuple(+ str(row[1])+ for row in connection.execute(+ "PRAGMA table_info(findings)"+ )+ )+ before_row = connection.execute(+ """+ SELECT+ id, campaign_id, module_id, title, description,+ severity, confidence, mitre_technique, mitre_tactic,+ cvss_score, cvss_vector, evidence_json, remediation,+ host, validated, false_positive, discovered_at, trace_id+ FROM findings+ """+ ).fetchone()+ _upgrade(path, "0008")+ with _connect(path) as connection:+ after_order = tuple(+ str(row[1])+ for row in connection.execute(+ "PRAGMA table_info(findings)"+ )+ )+ after_row = connection.execute(+ """+ SELECT+ id, campaign_id, module_id, title, description,+ severity, confidence, mitre_technique, mitre_tactic,+ cvss_score, cvss_vector, evidence_json, remediation,+ host, validated, false_positive, discovered_at, trace_id+ FROM findings+ """+ ).fetchone()+ _require_fixed(+ before_order.index("cvss_score")+ < before_order.index("confidence")+ and after_order.index("confidence")+ < after_order.index("cvss_score")+ and before_row is not None+ and after_row is not None+ and tuple(before_row) == tuple(after_row)+ and _complete_managed_contract_is_exact(path),+ "historical findings order did not converge losslessly",+ )+++def test_missing_foreign_key_and_blocked_check_converge(+) -> None:+ with _database("structural-drift") as path:+ _upgrade(path, "0007")+ _seed_graph(path)+ _rewrite_table_sql(+ path,+ "credentials",+ ", \n\tCONSTRAINT fk_credentials_host FOREIGN KEY(host_id) "+ "REFERENCES hosts (id) ON DELETE SET NULL",+ "",+ )+ _rewrite_table_sql(+ path,+ "rate_limit_events",+ ", \n\tCONSTRAINT ck_rate_limit_events_blocked_bool "+ "CHECK (blocked IN (0, 1))",+ "",+ )+ before_rows = _data(path)+ _upgrade(path, "0008")+ with _connect(path) as connection:+ credential_columns = tuple(+ str(row[1])+ for row in connection.execute(+ "PRAGMA table_info(credentials)"+ )+ )+ credential_fks = {+ (+ str(row[2]),+ str(row[3]),+ str(row[4]),+ str(row[6]),+ )+ for row in connection.execute(+ "PRAGMA foreign_key_list(credentials)"+ )+ }+ rate_sql = str(+ connection.execute(+ """+ SELECT sql FROM sqlite_master+ WHERE type='table' AND name='rate_limit_events'+ """+ ).fetchone()[0]+ )+ _require_fixed(+ credential_columns[10] == "cracked_value_enc"+ and ("hosts", "host_id", "id", "SET NULL") in credential_fks+ and "ck_rate_limit_events_blocked_bool" in rate_sql+ and _complete_managed_contract_is_exact(path)+ and dict(_data(path))["credentials"]+ == dict(before_rows)["credentials"],+ "structural legacy drift did not converge losslessly",+ )+++def test_safe_legacy_credential_shape_and_order_converges() -> None:+ with _database("credential-shape") as path:+ _upgrade(path, "0007")+ _seed_graph(path)+ _rewrite_table_sql(+ path,+ "credentials",+ "cracked_value_enc TEXT",+ "cracked_value TEXT",+ )+ before = dict(_data(path))["credentials"]+ _upgrade(path, "0008")+ with _connect(path) as connection:+ columns = tuple(+ str(row[1])+ for row in connection.execute(+ "PRAGMA table_info(credentials)"+ )+ )+ _require_fixed(+ "cracked_value" not in columns+ and columns[10] == "cracked_value_enc"+ and _complete_managed_contract_is_exact(path)+ and dict(_data(path))["credentials"] == before,+ "safe legacy credential shape did not converge losslessly",+ )++[email protected]("variant", ["duplicate", "nocase"])+def test_noncanonical_unique_metadata_is_rejected_without_mutation(+ variant: str,+) -> None:+ with _database(f"unique-{variant}") as path:+ _upgrade(path, "0007")+ _seed_graph(path)+ _replace_users_unique_contract(path, variant)+ with _connect(path) as connection:+ index_rows = list(+ connection.execute("PRAGMA index_list(users)")+ )+ unique_rows = [+ row+ for row in index_rows+ if str(row[3]) == "u"+ ]+ collations = tuple(+ str(detail[4]).upper()+ for row in unique_rows+ for detail in connection.execute(+ f'PRAGMA index_xinfo("{str(row[1])}")' # noqa: S608+ )+ if bool(detail[5])+ )+ fixture_is_authentic = (+ variant == "duplicate"+ and len(unique_rows) == 1+ and sum(+ bool(row[2]) and str(row[3]) == "c"+ for row in index_rows+ )+ == 1+ ) or (+ variant == "nocase"+ and len(unique_rows) == 1+ and collations == ("NOCASE",)+ )+ _require_fixed(+ fixture_is_authentic,+ "noncanonical unique fixture was not authentic",+ )+ before = _snapshot(path)+ observed = _attempt_upgrade(path)+ after = _snapshot(path)+ _require_fixed(+ observed == _CATALOG_ERROR+ and after == before+ and _version(path) == "0007",+ "noncanonical unique metadata was not rejected atomically",+ )+++def test_nocase_managed_text_primary_key_is_rejected_without_mutation(+) -> None:+ with _database("nocase-primary-key") as path:+ _upgrade(path, "0007")+ _replace_campaigns_with_nocase_primary_key(path)+ with _connect(path) as connection:+ primary_rows = [+ row+ for row in connection.execute(+ "PRAGMA index_list(campaigns)"+ )+ if str(row[3]).lower() == "pk"+ ]+ primary_columns = (+ ()+ if len(primary_rows) != 1+ else tuple(+ (+ int(row[1]),+ None if row[2] is None else str(row[2]),+ int(row[3]),+ str(row[4]).upper(),+ int(row[5]),+ )+ for row in connection.execute(+ f'PRAGMA index_xinfo("{str(primary_rows[0][1])}")'+ )+ )+ )+ fixture_is_authentic = (+ len(primary_rows) == 1+ and primary_columns+ and primary_columns[0] == (0, "id", 0, "NOCASE", 1)+ )+ _require_fixed(+ bool(fixture_is_authentic),+ "NOCASE primary-key fixture was not authentic",+ )+ before = _snapshot(path)+ observed = _attempt_upgrade(path)+ after = _snapshot(path)+ _require_fixed(+ observed == _CATALOG_ERROR+ and after == before+ and _version(path) == "0007",+ "NOCASE primary-key metadata was not rejected atomically",+ )+++def test_ticket_generated_hidden_column_is_rejected_without_mutation(+) -> None:+ with _database("ticket-hidden-column") as path:+ _upgrade(path, "0007")+ with _connect(path) as connection:+ connection.execute(+ """+ ALTER TABLE websocket_tickets+ ADD COLUMN ticket_marker TEXT+ GENERATED ALWAYS AS (credential_kind) VIRTUAL+ """+ )+ connection.commit()+ visible_count = len(+ tuple(+ connection.execute(+ "PRAGMA table_info(websocket_tickets)"+ )+ )+ )+ extended_rows = tuple(+ connection.execute(+ "PRAGMA table_xinfo(websocket_tickets)"+ )+ )+ fixture_is_authentic = (+ visible_count == 12+ and len(extended_rows) == 13+ and str(extended_rows[-1][1]) == "ticket_marker"+ and int(extended_rows[-1][6]) != 0+ )+ _require_fixed(+ fixture_is_authentic,+ "generated-column fixture was not authentic",+ )+ before = _snapshot(path)+ observed = _attempt_upgrade(path)+ after = _snapshot(path)+ _require_fixed(+ observed == _CATALOG_ERROR+ and after == before+ and _version(path) == "0007",+ "generated ticket column was not rejected atomically",+ )+++def test_ticket_index_sql_drift_is_rejected_without_mutation() -> None:+ with _database("ticket-index-sql") as path:+ _upgrade(path, "0007")+ with _connect(path) as connection:+ connection.execute("DROP INDEX idx_ws_tickets_expires")+ connection.execute(+ """+ CREATE INDEX idx_ws_tickets_expires+ ON websocket_tickets(expires_at COLLATE BINARY ASC)+ """+ )+ connection.commit()+ index_sql = str(+ connection.execute(+ """+ SELECT sql FROM sqlite_master+ WHERE type='index' AND name='idx_ws_tickets_expires'+ """+ ).fetchone()[0]+ )+ key_rows = tuple(+ row+ for row in connection.execute(+ "PRAGMA index_xinfo(idx_ws_tickets_expires)"+ )+ if bool(row[5])+ )+ fixture_is_authentic = (+ "COLLATE BINARY ASC" in index_sql.upper()+ and len(key_rows) == 1+ and int(key_rows[0][1]) == 10+ and str(key_rows[0][2]) == "expires_at"+ and int(key_rows[0][3]) == 0+ and str(key_rows[0][4]).upper() == "BINARY"+ )+ _require_fixed(+ fixture_is_authentic,+ "index-definition drift fixture was not authentic",+ )+ before = _snapshot(path)+ observed = _attempt_upgrade(path)+ after = _snapshot(path)+ _require_fixed(+ observed == _CATALOG_ERROR+ and after == before+ and _version(path) == "0007",+ "ticket index definition drift was not rejected atomically",+ )+++def test_ticket_check_comment_differential_is_rejected_without_mutation(+) -> None:+ with _database("ticket-check-comment") as path:+ _upgrade(path, "0007")+ _seed_graph(path)+ _weaken_ticket_hash_check_with_comment(path)+ weak_check_accepted = False+ comment_present = False+ with _connect(path) as connection:+ table_sql = str(+ connection.execute(+ """+ SELECT sql FROM sqlite_master+ WHERE type='table' AND name='websocket_tickets'+ """+ ).fetchone()[0]+ )+ comment_present = "parser gap" in table_sql+ connection.execute("SAVEPOINT check_authenticity")+ try:+ connection.execute(+ """+ INSERT INTO websocket_tickets(+ ticket_hash, campaign_id, user_id, credential_kind,+ api_key_id, required_scope, created_at, expires_at+ ) VALUES(+ ?, 'c1', 'u1', 'api_key', 'a1', 'read',+ '2098-01-01T00:00:00.000Z',+ '2098-01-01T00:01:00.000Z'+ )+ """,+ ("short",),+ )+ weak_check_accepted = True+ except sqlite3.IntegrityError:+ weak_check_accepted = False+ finally:+ connection.execute(+ "ROLLBACK TO SAVEPOINT check_authenticity"+ )+ connection.execute("RELEASE SAVEPOINT check_authenticity")+ _require_fixed(+ comment_present and weak_check_accepted,+ "comment-bearing weakened CHECK fixture was not authentic",+ )+ before = _snapshot(path)+ observed = _attempt_upgrade(path)+ after = _snapshot(path)+ _require_fixed(+ observed == _CATALOG_ERROR+ and after == before+ and _version(path) == "0007",+ "comment-bearing weakened CHECK was not rejected atomically",+ )++[email protected]("variant", ["scope", "hash"])+def test_ticket_quoted_literal_case_drift_is_rejected_without_mutation(+ variant: str,+) -> None:+ with _database(f"ticket-literal-{variant}") as path:+ _upgrade(path, "0007")+ _seed_graph(path)+ if variant == "scope":+ _replace_ticket_contract_fragment(+ path,+ r"required_scope\s*=\s*'read'",+ "required_scope='READ'",+ )+ ticket_hash = "b" * 64+ required_scope = "READ"+ else:+ _replace_ticket_contract_fragment(+ path,+ r"'\*\[\^0-9a-f\]\*'",+ "'*[^0-9A-F]*'",+ )+ ticket_hash = "B" * 64+ required_scope = "read"+ altered_literal_accepted = False+ with _connect(path) as connection:+ try:+ connection.execute(+ """+ INSERT INTO websocket_tickets(+ ticket_hash, campaign_id, user_id, credential_kind,+ api_key_id, required_scope, created_at, expires_at+ ) VALUES(+ ?, 'c1', 'u1', 'api_key', 'a1', ?,+ '2098-01-01T00:02:00.000Z',+ '2098-01-01T00:03:00.000Z'+ )+ """,+ (ticket_hash, required_scope),+ )+ connection.commit()+ altered_literal_accepted = True+ except sqlite3.IntegrityError:+ altered_literal_accepted = False+ _require_fixed(+ altered_literal_accepted,+ "quoted-literal drift fixture was not authentic",+ )+ before = _snapshot(path)+ observed = _attempt_upgrade(path)+ after = _snapshot(path)+ _require_fixed(+ observed == _CATALOG_ERROR+ and after == before+ and _version(path) == "0007",+ "quoted-literal drift was not rejected atomically",+ )+++def test_audit_autoincrement_comment_spoof_is_rejected_without_mutation(+) -> None:+ with _database("audit-autoincrement-comment") as path:+ _upgrade(path, "0007")+ _spoof_audit_autoincrement_with_comment(path)+ with _connect(path) as connection:+ table_sql = str(+ connection.execute(+ """+ SELECT sql FROM sqlite_master+ WHERE type='table' AND name='audit_log'+ """+ ).fetchone()[0]+ )+ without_comments = re.sub(+ r"/\*.*?\*/|--[^\r\n]*",+ "",+ table_sql,+ flags=re.DOTALL,+ )+ _require_fixed(+ "AUTOINCREMENT" in table_sql.upper()+ and "AUTOINCREMENT" not in without_comments.upper(),+ "comment-bearing AUTOINCREMENT fixture was not authentic",+ )+ before = _snapshot(path)+ observed = _attempt_upgrade(path)+ after = _snapshot(path)+ _require_fixed(+ observed == _CATALOG_ERROR+ and after == before+ and _version(path) == "0007",+ "comment-bearing AUTOINCREMENT spoof was not rejected atomically",+ )+++def test_rate_limit_check_comment_spoof_is_rejected_without_mutation() -> None:+ with _database("blocked-check-comment") as path:+ _upgrade(path, "0007")+ _weaken_blocked_check_with_comment(path)+ invalid_flag_accepted = False+ comment_present = False+ with _connect(path) as connection:+ table_sql = str(+ connection.execute(+ """+ SELECT sql FROM sqlite_master+ WHERE type='table' AND name='rate_limit_events'+ """+ ).fetchone()[0]+ )+ comment_present = "parser gap" in table_sql+ connection.execute("SAVEPOINT check_authenticity")+ try:+ connection.execute(+ """+ INSERT INTO rate_limit_events(+ ip_address, bucket, blocked+ ) VALUES('192.0.2.1', 'auth', 2)+ """+ )+ invalid_flag_accepted = True+ except sqlite3.IntegrityError:+ invalid_flag_accepted = False+ finally:+ connection.execute(+ "ROLLBACK TO SAVEPOINT check_authenticity"+ )+ connection.execute("RELEASE SAVEPOINT check_authenticity")+ _require_fixed(+ comment_present and invalid_flag_accepted,+ "comment-bearing weakened blocked CHECK fixture was not authentic",+ )+ before = _snapshot(path)+ observed = _attempt_upgrade(path)+ after = _snapshot(path)+ _require_fixed(+ observed == _CATALOG_ERROR+ and after == before+ and _version(path) == "0007",+ "comment-bearing weakened blocked CHECK was not rejected atomically",+ )+++def test_reserved_index_on_unrelated_table_is_rejected_without_mutation(+) -> None:+ with _database("reserved-index-owner") as path:+ _upgrade(path, "0007")+ with _connect(path) as connection:+ connection.execute("DROP INDEX idx_findings_mitre")+ connection.execute(+ """+ CREATE TABLE operator_notes(+ id TEXT NOT NULL PRIMARY KEY,+ note TEXT NOT NULL+ )+ """+ )+ connection.execute(+ "CREATE INDEX idx_findings_mitre ON operator_notes(note)"+ )+ connection.execute(+ "INSERT INTO operator_notes(id, note) VALUES('n1', 'note')"+ )+ connection.commit()+ index_owner = connection.execute(+ """+ SELECT tbl_name FROM sqlite_master+ WHERE type='index' AND name='idx_findings_mitre'+ """+ ).fetchone()+ fixture_is_authentic = (+ index_owner is not None+ and str(index_owner[0]) == "operator_notes"+ )+ _require_fixed(+ fixture_is_authentic,+ "reserved-index owner fixture was not authentic",+ )+ before = _snapshot(path)+ observed = _attempt_upgrade(path)+ after = _snapshot(path)+ _require_fixed(+ observed == _CATALOG_ERROR+ and after == before+ and _version(path) == "0007",+ "reserved index on unrelated table was not rejected atomically",+ )+++def test_duplicate_non_ticket_foreign_key_is_rejected_without_mutation(+) -> None:+ with _database("duplicate-non-ticket-fk") as path:+ _upgrade(path, "0007")+ _append_table_constraint(+ path,+ "findings",+ "CONSTRAINT duplicate_findings_campaign "+ "FOREIGN KEY(campaign_id) REFERENCES campaigns(id) "+ "ON DELETE CASCADE",+ )+ with _connect(path) as connection:+ foreign_keys = tuple(+ connection.execute("PRAGMA foreign_key_list(findings)")+ )+ fixture_is_authentic = (+ len(foreign_keys) == 2+ and len(+ {+ (+ str(row[2]),+ str(row[3]),+ str(row[4]),+ str(row[5]).upper(),+ str(row[6]).upper(),+ )+ for row in foreign_keys+ }+ )+ == 1+ )+ _require_fixed(+ fixture_is_authentic,+ "duplicate foreign-key fixture was not authentic",+ )+ before = _snapshot(path)+ observed = _attempt_upgrade(path)+ after = _snapshot(path)+ _require_fixed(+ observed == _CATALOG_ERROR+ and after == before+ and _version(path) == "0007",+ "duplicate non-ticket foreign key was not rejected atomically",+ )+++ ("mutation", "expected"),+ [+ ("orphan", _DATA_ERROR),+ ("duplicate", _DATA_ERROR),+ ("null", _DATA_ERROR),+ ("flag", _DATA_ERROR),+ ("timestamp", _DATA_ERROR),+ ("ambiguous", _CATALOG_ERROR),+ ("extra-check", _CATALOG_ERROR),+ ("other-flag", _DATA_ERROR),+ ],+)+def test_rejected_legacy_state_is_atomic(+ mutation: str,+ expected: str,+) -> None:+ with _database(f"reject-{mutation}") as path:+ _upgrade(path, "0007")+ if mutation == "duplicate":+ _remove_users_unique_constraint(path)+ elif mutation == "null":+ _rewrite_table_sql(+ path,+ "findings",+ "cvss_vector TEXT DEFAULT ('') NOT NULL",+ "cvss_vector TEXT DEFAULT ('')",+ )+ elif mutation == "extra-check":+ _append_check_constraint(path, "campaigns")+ with _connect(path) as connection:+ if mutation == "orphan":+ connection.execute("PRAGMA foreign_keys=OFF")+ connection.execute(+ """+ INSERT INTO hosts(id, campaign_id, ip_address)+ VALUES('h1', 'missing', '192.0.2.2')+ """+ )+ elif mutation == "duplicate":+ connection.execute(+ """+ INSERT INTO users(id, username, hashed_password)+ VALUES('u1', 'duplicate', 'hash')+ """+ )+ connection.execute(+ """+ INSERT INTO users(id, username, hashed_password)+ VALUES('u2', 'duplicate', 'hash')+ """+ )+ elif mutation == "null":+ connection.execute(+ """+ INSERT INTO campaigns(id, name)+ VALUES('c1', 'campaign')+ """,+ )+ connection.execute(+ """+ INSERT INTO findings(+ id, campaign_id, module_id, title, description,+ severity, cvss_vector+ ) VALUES(+ 'f1', 'c1', 'module', 'finding', 'description',+ 'high', NULL+ )+ """+ )+ elif mutation == "flag":+ connection.execute("PRAGMA ignore_check_constraints=ON")+ connection.execute(+ """+ INSERT INTO rate_limit_events(ip_address, bucket, blocked)+ VALUES('192.0.2.3', 'login', 2)+ """+ )+ elif mutation == "timestamp":+ connection.execute(+ """+ INSERT INTO revoked_access_tokens(+ jti, user_id, expires_at+ ) VALUES('j1', 'u1', 'not-a-timestamp')+ """+ )+ elif mutation == "ambiguous":+ connection.execute(+ "CREATE TRIGGER managed_ambiguous AFTER INSERT ON users "+ "BEGIN SELECT 1; END"+ )+ elif mutation == "extra-check":+ pass+ elif mutation == "other-flag":+ connection.execute(+ """+ INSERT INTO users(+ id, username, hashed_password, is_active+ ) VALUES('u1', 'account', 'hash', 2)+ """+ )+ else:+ raise AssertionError("unknown mutation")+ connection.commit()+ before = _snapshot(path)+ observed = _attempt_upgrade(path)+ after = _snapshot(path)+ _require_fixed(+ observed == expected+ and after == before+ and _version(path) == "0007",+ "rejected reconciliation mutated catalog, data, or revision",+ )+++ "flag_case",+ [+ "module-success",+ "finding-validated",+ "finding-false-positive",+ "host-domain-controller",+ "credential-cracked",+ "user-active",+ "api-key-active",+ "refresh-revoked",+ ],+)+def test_each_non_rate_integer_flag_rejects_non_boolean_data(+ flag_case: str,+) -> None:+ statements = {+ "module-success": (+ "INSERT INTO module_runs("+ "id, campaign_id, module_id, outcome, success"+ ") VALUES('m1', 'c1', 'module', 'outcome', 2)"+ ),+ "finding-validated": (+ "INSERT INTO findings("+ "id, campaign_id, module_id, title, description, severity, "+ "validated"+ ") VALUES("+ "'f1', 'c1', 'module', 'finding', 'description', 'high', 2"+ ")"+ ),+ "finding-false-positive": (+ "INSERT INTO findings("+ "id, campaign_id, module_id, title, description, severity, "+ "false_positive"+ ") VALUES("+ "'f1', 'c1', 'module', 'finding', 'description', 'high', 2"+ ")"+ ),+ "host-domain-controller": (+ "INSERT INTO hosts(id, campaign_id, ip_address, is_dc) "+ "VALUES('h1', 'c1', '192.0.2.8', 2)"+ ),+ "credential-cracked": (+ "INSERT INTO credentials("+ "id, campaign_id, username, cred_type, cracked"+ ") VALUES('k1', 'c1', 'account', 'password', 2)"+ ),+ "user-active": (+ "INSERT INTO users(id, username, hashed_password, is_active) "+ "VALUES('u1', 'account', 'hash', 2)"+ ),+ "api-key-active": (+ "INSERT INTO api_keys("+ "id, user_id, name, key_hash, key_prefix, is_active"+ ") VALUES('a1', 'u1', 'key', 'hash', 'prefix', 2)"+ ),+ "refresh-revoked": (+ "INSERT INTO refresh_tokens("+ "id, user_id, is_revoked, expires_at"+ ") VALUES('r1', 'u1', 2, '2099-01-01 00:00:00')"+ ),+ }+ with _database(f"flag-{flag_case}") as path:+ _upgrade(path, "0007")+ with _connect(path) as connection:+ if flag_case in {+ "module-success",+ "finding-validated",+ "finding-false-positive",+ "host-domain-controller",+ "credential-cracked",+ }:+ connection.execute(+ "INSERT INTO campaigns(id, name) "+ "VALUES('c1', 'campaign')"+ )+ if flag_case in {"api-key-active", "refresh-revoked"}:+ connection.execute(+ "INSERT INTO users(id, username, hashed_password) "+ "VALUES('u1', 'account', 'hash')"+ )+ connection.execute(statements[flag_case])+ connection.commit()+ before = _snapshot(path)+ observed = _attempt_upgrade(path)+ after = _snapshot(path)+ _require_fixed(+ observed == _DATA_ERROR+ and after == before+ and _version(path) == "0007",+ "non-Boolean integer flag was not rejected atomically",+ )+++ "variant",+ [+ "hash",+ "kind",+ "created",+ "expires",+ "consumed",+ "time-order",+ "source-shape",+ ],+)+def test_ticket_row_check_violations_are_rejected_before_reconciliation(+ variant: str,+) -> None:+ with _database(f"ticket-row-{variant}") as path:+ _upgrade(path, "0007")+ _seed_graph(path)+ values: dict[str, object | None] = {+ "ticket_hash": "b" * 64,+ "credential_kind": "api_key",+ "bearer_subject": None,+ "bearer_jti": None,+ "bearer_expires_at": None,+ "api_key_id": "a1",+ "required_scope": "read",+ "created_at": "2098-01-01T00:00:00.000Z",+ "expires_at": "2098-01-01T00:01:00.000Z",+ "consumed_at": None,+ }+ if variant == "hash":+ values["ticket_hash"] = "short"+ elif variant == "kind":+ values["credential_kind"] = "unknown"+ elif variant == "created":+ values["created_at"] = "not-a-timestamp"+ elif variant == "expires":+ values["expires_at"] = "not-a-timestamp"+ elif variant == "consumed":+ values["consumed_at"] = "not-a-timestamp"+ elif variant == "time-order":+ values["expires_at"] = "2097-12-31T23:59:59.000Z"+ else:+ values["required_scope"] = "write"+ with _connect(path) as connection:+ connection.execute("PRAGMA ignore_check_constraints=ON")+ connection.execute(+ """+ INSERT INTO websocket_tickets(+ ticket_hash, campaign_id, user_id, credential_kind,+ bearer_subject, bearer_jti, bearer_expires_at,+ api_key_id, required_scope, created_at, expires_at,+ consumed_at+ ) VALUES(?, 'c1', 'u1', ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ values["ticket_hash"],+ values["credential_kind"],+ values["bearer_subject"],+ values["bearer_jti"],+ values["bearer_expires_at"],+ values["api_key_id"],+ values["required_scope"],+ values["created_at"],+ values["expires_at"],+ values["consumed_at"],+ ),+ )+ connection.execute("PRAGMA ignore_check_constraints=OFF")+ connection.execute("DROP TABLE module_runs")+ connection.commit()+ before = _snapshot(path)+ observed = _attempt_upgrade(path)+ after = _snapshot(path)+ _require_fixed(+ observed == _DATA_ERROR+ and after == before+ and _version(path) == "0007",+ "invalid ticket row was not rejected before reconciliation",+ )+++ "orphan_kind",+ ["campaign", "user", "api-key"],+)+def test_ticket_foreign_key_orphans_are_rejected_without_mutation(+ orphan_kind: str,+) -> None:+ with _database(f"ticket-orphan-{orphan_kind}") as path:+ _upgrade(path, "0007")+ _seed_graph(path)+ values = {+ "campaign": ("missing", "u1", "a1"),+ "user": ("c1", "missing", "a1"),+ "api-key": ("c1", "u1", "missing"),+ }[orphan_kind]+ with _connect(path) as connection:+ connection.execute("PRAGMA foreign_keys=OFF")+ connection.execute(+ """+ INSERT INTO websocket_tickets(+ ticket_hash, campaign_id, user_id, credential_kind,+ api_key_id, required_scope, created_at, expires_at+ ) VALUES(+ ?, ?, ?, 'api_key', ?, 'read',+ '2098-01-01T00:00:00.000Z',+ '2098-01-01T00:01:00.000Z'+ )+ """,+ ("b" * 64, *values),+ )+ connection.commit()+ before = _snapshot(path)+ observed = _attempt_upgrade(path)+ after = _snapshot(path)+ _require_fixed(+ observed == _DATA_ERROR+ and after == before+ and _version(path) == "0007",+ "ticket foreign-key orphan was not rejected atomically",+ )++[email protected]("variant", ["duplicate", "deferrable"])+def test_noncanonical_ticket_foreign_key_is_rejected_without_mutation(+ variant: str,+) -> None:+ definition = (+ "CONSTRAINT unexpected_ws_campaign "+ "FOREIGN KEY(campaign_id) REFERENCES campaigns(id) "+ "ON DELETE CASCADE"+ )+ if variant == "deferrable":+ definition += " DEFERRABLE INITIALLY DEFERRED"+ with _database(f"ticket-fk-{variant}") as path:+ _upgrade(path, "0007")+ _seed_graph(path)+ _append_table_constraint(path, "websocket_tickets", definition)+ with _connect(path) as connection:+ foreign_key_count = len(+ tuple(+ connection.execute(+ "PRAGMA foreign_key_list(websocket_tickets)"+ )+ )+ )+ table_sql = str(+ connection.execute(+ """+ SELECT sql FROM sqlite_master+ WHERE type='table' AND name='websocket_tickets'+ """+ ).fetchone()[0]+ )+ fixture_is_authentic = foreign_key_count == 4 and (+ variant != "deferrable"+ or "DEFERRABLE INITIALLY DEFERRED" in table_sql+ )+ _require_fixed(+ fixture_is_authentic,+ "noncanonical ticket foreign-key fixture was not authentic",+ )+ before = _snapshot(path)+ observed = _attempt_upgrade(path)+ after = _snapshot(path)+ _require_fixed(+ observed == _CATALOG_ERROR+ and after == before+ and _version(path) == "0007",+ "noncanonical ticket foreign key was not rejected atomically",+ )+++def test_downgrade_is_fixed_forward_only_and_has_zero_mutation() -> None:+ with _database("downgrade") as path:+ _upgrade(path, "0008")+ before = _snapshot(path)+ observed = ""+ try:+ _downgrade(path, "0007")+ except RuntimeError as exc:+ observed = str(exc)+ _require_fixed(+ observed == _FORWARD_ONLY_ERROR+ and _snapshot(path) == before+ and _version(path) == "0008",+ "revision 0008 downgrade mutated forward-only state",+ )+++def test_unsupported_dialect_is_rejected_with_fixed_error(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ migration = importlib.import_module(+ "migrations.versions.0008_reconcile_schema_parity"+ )+ fake_bind = SimpleNamespace(dialect=SimpleNamespace(name="unsupported"))+ monkeypatch.setattr(migration.op, "get_bind", lambda: fake_bind)+ observed = ""+ try:+ migration.upgrade()+ except RuntimeError as exc:+ observed = str(exc)+ _require_fixed(+ observed == _DIALECT_ERROR,+ "revision 0008 accepted an unsupported dialect",+ )+++def test_temp_trigger_on_managed_table_is_rejected_before_preflight_reads(+) -> None:+ migration = importlib.import_module(+ "migrations.versions.0008_reconcile_schema_parity"+ )+ with _database("temp-trigger-shadow") as path:+ _upgrade(path, "0007")+ before = _snapshot(path)+ engine = sa.create_engine(f"sqlite:///{path.as_posix()}")+ observed = ""+ temp_trigger_present = False+ try:+ with engine.connect() as connection:+ connection.exec_driver_sql("PRAGMA foreign_keys=ON")+ connection.exec_driver_sql(+ """+ CREATE TEMP TRIGGER operator_hook+ AFTER INSERT ON campaigns+ BEGIN+ SELECT 1;+ END+ """+ )+ try:+ migration._sqlite_preflight(connection)+ except RuntimeError as exc:+ observed = str(exc)+ temp_trigger_present = (+ connection.exec_driver_sql(+ """+ SELECT count(*) FROM sqlite_temp_master+ WHERE type='trigger' AND tbl_name='campaigns'+ """+ ).scalar_one()+ == 1+ )+ finally:+ engine.dispose()+ _require_fixed(+ observed == _CATALOG_ERROR+ and temp_trigger_present+ and _snapshot(path) == before+ and _version(path) == "0007",+ "temporary managed-table trigger was not rejected before reads",+ )+++def test_exact_temp_table_shadow_is_rejected_before_preflight_reads() -> None:+ migration = importlib.import_module(+ "migrations.versions.0008_reconcile_schema_parity"+ )+ with _database("temp-table-shadow") as path:+ _upgrade(path, "0007")+ before = _snapshot(path)+ engine = sa.create_engine(f"sqlite:///{path.as_posix()}")+ observed = ""+ temp_table_present = False+ try:+ with engine.connect() as connection:+ source = connection.exec_driver_sql(+ """+ SELECT sql FROM main.sqlite_master+ WHERE type='table' AND name='campaigns'+ """+ ).scalar_one()+ shadow_sql, replacement_count = re.subn(+ r"^\s*CREATE\s+TABLE\s+(?:\"campaigns\"|campaigns)",+ "CREATE TEMP TABLE campaigns",+ str(source),+ count=1,+ flags=re.IGNORECASE,+ )+ _require_fixed(+ replacement_count == 1,+ "temporary managed-table fixture was not constructed",+ )+ connection.exec_driver_sql(shadow_sql)+ connection.exec_driver_sql(+ """+ CREATE INDEX temp.idx_campaigns_status+ ON campaigns(status)+ """+ )+ connection.exec_driver_sql(+ """+ CREATE INDEX temp.idx_campaigns_created+ ON campaigns(created_at)+ """+ )+ try:+ migration._sqlite_preflight(connection)+ except RuntimeError as exc:+ observed = str(exc)+ temp_table_present = (+ connection.exec_driver_sql(+ """+ SELECT count(*) FROM sqlite_temp_master+ WHERE type='table' AND name='campaigns'+ """+ ).scalar_one()+ == 1+ )+ finally:+ engine.dispose()+ _require_fixed(+ observed == _CATALOG_ERROR+ and temp_table_present+ and _snapshot(path) == before+ and _version(path) == "0007",+ "temporary managed-table shadow was not rejected before reads",+ )+++def test_exact_temp_version_table_shadow_is_rejected_before_preflight_reads(+) -> None:+ migration = importlib.import_module(+ "migrations.versions.0008_reconcile_schema_parity"+ )+ with _database("temp-version-shadow") as path:+ _upgrade(path, "0007")+ before = _snapshot(path)+ engine = sa.create_engine(f"sqlite:///{path.as_posix()}")+ observed = ""+ temp_table_present = False+ try:+ with engine.connect() as connection:+ connection.exec_driver_sql(+ """+ CREATE TEMP TABLE alembic_version(+ version_num VARCHAR(32) NOT NULL,+ CONSTRAINT alembic_version_pkc+ PRIMARY KEY(version_num)+ )+ """+ )+ connection.exec_driver_sql(+ """+ INSERT INTO temp.alembic_version(version_num)+ VALUES('0007')+ """+ )+ try:+ migration._sqlite_preflight(connection)+ except RuntimeError as exc:+ observed = str(exc)+ temp_table_present = (+ connection.exec_driver_sql(+ """+ SELECT count(*) FROM sqlite_temp_master+ WHERE type='table' AND name='alembic_version'+ """+ ).scalar_one()+ == 1+ )+ finally:+ engine.dispose()+ _require_fixed(+ observed == _CATALOG_ERROR+ and temp_table_present+ and _snapshot(path) == before+ and _version(path) == "0007",+ "temporary version-table shadow was not rejected before reads",+ )+++def test_sqlite_audit_autoincrement_and_connection_reuse() -> None:+ with _database("autoincrement") as path:+ _upgrade(path, "0007")+ with _connect(path) as connection:+ connection.execute(+ "INSERT INTO audit_log(action) VALUES('first')"+ )+ first = int(+ connection.execute(+ "SELECT max(id) FROM audit_log"+ ).fetchone()[0]+ )+ connection.execute("DELETE FROM audit_log")+ connection.commit()+ _upgrade(path, "0008")+ with _connect(path) as connection:+ connection.execute(+ "INSERT INTO audit_log(action) VALUES('second')"+ )+ second = int(+ connection.execute(+ "SELECT max(id) FROM audit_log"+ ).fetchone()[0]+ )+ foreign_keys = int(+ connection.execute("PRAGMA foreign_keys").fetchone()[0]+ )+ reusable = connection.execute("SELECT 1").fetchone() == (1,)+ _require_fixed(+ second > first and foreign_keys == 1 and reusable,+ "AUTOINCREMENT, foreign keys, or connection reuse regressed",+ )+++def test_injected_version_update_failure_rolls_back_reconciliation() -> None:+ with _database("version-failure") as path:+ _upgrade(path, "0007")+ with _connect(path) as connection:+ connection.execute("DROP TABLE module_runs")+ connection.commit()+ before = _snapshot(path)+ trigger_installed = False++ def install_failure_trigger(+ _connection: object,+ cursor: object,+ statement: str,+ _parameters: object,+ _context: object,+ _executemany: bool,+ ) -> None:+ nonlocal trigger_installed+ normalized = re.sub(r"\s+", " ", statement).lower()+ if (+ trigger_installed+ or re.search(+ r"create table \"?module_runs\"?",+ normalized,+ )+ is None+ ):+ return+ trigger_installed = True+ cursor.execute(+ """+ CREATE TRIGGER block_revision_0008+ BEFORE UPDATE ON alembic_version+ BEGIN+ SELECT RAISE(ABORT, 'injected version update failure');+ END+ """+ )++ failed = False+ sa.event.listen(+ sa.engine.Engine,+ "after_cursor_execute",+ install_failure_trigger,+ )+ try:+ try:+ _upgrade(path, "0008")+ except Exception:+ failed = True+ finally:+ sa.event.remove(+ sa.engine.Engine,+ "after_cursor_execute",+ install_failure_trigger,+ )+ _require_fixed(+ trigger_installed+ and failed+ and _snapshot(path) == before+ and _version(path) == "0007",+ "version-update failure did not roll back revision reconciliation",+ )+++def test_version_table_trigger_cannot_mutate_application_data() -> None:+ with _database("version-trigger") as path:+ _upgrade(path, "0007")+ _seed_graph(path)+ with _connect(path) as connection:+ connection.execute(+ """+ CREATE TRIGGER mutate_on_revision+ AFTER UPDATE ON alembic_version+ BEGIN+ UPDATE campaigns+ SET notes='changed'+ WHERE id='c1';+ END+ """+ )+ connection.commit()+ before = _snapshot(path)+ observed = _attempt_upgrade(path)+ after = _snapshot(path)+ _require_fixed(+ observed == _CATALOG_ERROR+ and after == before+ and _version(path) == "0007",+ "version-table trigger was not rejected before application mutation",+ )diff --git a/tests/unit/test_websocket_ticket_migration.py b/tests/unit/test_websocket_ticket_migration.pyindex f10cac0..02799a6 100644--- a/tests/unit/test_websocket_ticket_migration.py+++ b/tests/unit/test_websocket_ticket_migration.py@@ -1393,12 +1393,12 @@ async def _runtime_bootstrap(path: Path) -> bool:await database.close()-def test_migration_head_is_real_empty_base_to_0007() -> None:+def test_migration_head_is_real_empty_base_to_0008() -> None:with _temporary_database("empty-head") as path:initially_empty = _application_tables(path) == ()initial_revision_absent = _version(path) is None- _upgrade(path, "0007")- revision_is_current = _version(path) == "0007"+ _upgrade(path, "head")+ revision_is_current = _version(path) == "0008"exact_contract = _ticket_contract(path) == _EXPECTED_TICKET_CONTRACTenforcement_holds = _exercise_ticket_enforcement(path)@@ -1407,18 +1407,18 @@ def test_migration_head_is_real_empty_base_to_0007() -> None:"fresh migration database was not empty",)_require_fixed(SCHEMA_VERSION == 7, "SQLite schema version is not seven")- _require_fixed(revision_is_current, "Alembic head is not revision 0007")+ _require_fixed(revision_is_current, "Alembic head is not revision 0008")_require_fixed(exact_contract,- "fresh revision 0007 ticket fingerprint diverged",+ "fresh revision 0008 ticket fingerprint diverged",)_require_fixed(enforcement_holds,- "fresh revision 0007 enforcement diverged",+ "fresh revision 0008 enforcement diverged",)-def test_sqlite_0006_to_0007_to_0006_to_0007_preserves_parent_data() -> None:+def test_sqlite_0007_ownership_and_0008_compatibility_preserve_data() -> None:with _temporary_database("round-trip") as path:_upgrade(path, "0006")parent_before = _non_ticket_snapshot(path)@@ -1467,9 +1467,27 @@ def test_sqlite_0006_to_0007_to_0006_to_0007_preserves_parent_data() -> None:)connection = _connect(path)try:+ _insert_bearer_ticket(+ connection,+ digest_character="b",+ expires_at="2099-01-01T00:00:30.000Z",+ )+ connection.commit()final_parent_count = _parent_row_count(connection)finally:connection.close()+ ticket_contract_before_0008 = _ticket_contract(path)+ ticket_data_before_0008 = _ticket_data_snapshot(path)++ _upgrade(path, "0008")+ ticket_contract_after_0008 = _ticket_contract(path)+ ticket_data_after_0008 = _ticket_data_snapshot(path)+ revision_0008_is_compatible = (+ _version(path) == "0008"+ and ticket_contract_before_0008 == _EXPECTED_TICKET_CONTRACT+ and ticket_contract_after_0008 == ticket_contract_before_0008+ and ticket_data_after_0008 == ticket_data_before_0008+ )_require_fixed(upgraded_exact, "revision 0007 upgrade was incomplete")_require_fixed(@@ -1480,19 +1498,24 @@ def test_sqlite_0006_to_0007_to_0006_to_0007_preserves_parent_data() -> None:reupgraded_exact and final_parent_count == parent_count_before,"revision 0007 re-upgrade did not converge",)+ _require_fixed(+ revision_0008_is_compatible,+ "revision 0008 changed the revision 0007 ticket contract",+ )def test_runtime_bootstrap_and_alembic_have_exact_ticket_parity() -> None:with _temporary_database("migration") as migration_path:with _temporary_database("runtime") as runtime_path:- _upgrade(migration_path, "0007")+ _upgrade(migration_path, "head")repeated_is_stable = asyncio.run(_runtime_bootstrap(runtime_path))migration_contract = _ticket_contract(migration_path)runtime_contract = _ticket_contract(runtime_path)both_exact = (- migration_contract == _EXPECTED_TICKET_CONTRACT+ _version(migration_path) == "0008"+ and migration_contract == _EXPECTED_TICKET_CONTRACTand runtime_contract == _EXPECTED_TICKET_CONTRACTand migration_contract == runtime_contract)