Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
232b833
QA: agent-middleware gateway/migrations/
PetrefiedThunder Oct 8, 2026
b22fd2a
Merge main into metacode/qa5-am-gateway-migrations
PetrefiedThunder Oct 24, 2026
7a8b331
Fix legacy SQLite boolean defaults
PetrefiedThunder Oct 24, 2026
206364d
Test legacy SQLite boolean row repair
PetrefiedThunder Oct 24, 2026
d3726fc
Merge remote-tracking branch 'origin/main' into metacode/qa5-am-gatew…
PetrefiedThunder Oct 24, 2026
f992032
Chain SQLite boolean repair after API key usage migration
PetrefiedThunder Oct 24, 2026
5919ba1
Merge remote-tracking branch 'origin/main' into metacode/qa5-am-gatew…
PetrefiedThunder Oct 25, 2026
036356b
Merge remote-tracking branch 'origin/main' into metacode/qa5-am-gatew…
PetrefiedThunder Oct 25, 2026
89a5956
Chain SQLite boolean repair after approval gate migration
PetrefiedThunder Oct 25, 2026
89428ce
Merge remote-tracking branch 'origin/main' into metacode/qa5-am-gatew…
PetrefiedThunder Oct 25, 2026
874515d
Rechain SQLite boolean migration after API key usage events
PetrefiedThunder Oct 25, 2026
6b4c2f2
Merge remote-tracking branch 'origin/main' into hermes-tmp-61
PetrefiedThunder Oct 25, 2026
9020bf6
Merge remote-tracking branch 'origin/main' into hermes-tmp-61
PetrefiedThunder Oct 25, 2026
c96958b
feat(migrations): port agent-middleware-api 047-050 with the same rev…
PetrefiedThunder Oct 25, 2026
22fdca0
Merge port of api migrations 047-050; renumber SQLite boolean default…
PetrefiedThunder Oct 25, 2026
02ad942
Sign enforcement mode and gateway build into receipts (migration 052)
PetrefiedThunder Oct 25, 2026
345b64c
Add 053: recreate 044-046 objects missing on api-chain databases
PetrefiedThunder Oct 25, 2026
f563483
fix(migrations): rls_bypass in env.py, boot check for reconcile columns
PetrefiedThunder Oct 25, 2026
e3bf41b
Merge #234 head f5634837 (review fixes)
PetrefiedThunder Oct 25, 2026
e705953
Merge #61 head e3bf41bc6ddbb245b8205b1329be6497a0462074
PetrefiedThunder Oct 25, 2026
2247bb1
Merge #236 head
PetrefiedThunder Oct 25, 2026
29d6363
test: cover receipt 052 columns in migration proof
PetrefiedThunder Oct 26, 2026
8d72b22
Merge branch 'hermes/receipt-mode-build' into hermes/repair-api-linea…
PetrefiedThunder Oct 26, 2026
830cf4d
docs: regenerate receipt provenance OpenAPI schema
PetrefiedThunder Oct 26, 2026
ea5e13e
Merge branch 'hermes/receipt-mode-build' into hermes/repair-api-linea…
PetrefiedThunder Oct 26, 2026
e6d5f99
fix(migrations): port TENANT_RLS_MODE setting; RLS for resolution tables
PetrefiedThunder Oct 26, 2026
40615d3
Merge #234 head e6d5f997 (TENANT_RLS_MODE, resolution-table RLS)
PetrefiedThunder Oct 26, 2026
8bc350a
Merge #61 (carries #234 e6d5f997)
PetrefiedThunder Oct 26, 2026
855d1c9
Merge #236 (carries #234 e6d5f997)
PetrefiedThunder Oct 26, 2026
6d977e2
feat(migrations): add opt-in TENANT_RLS_MODE=enable and PG RLS proof
PetrefiedThunder Oct 26, 2026
6ea1f92
Merge remote-tracking branch 'origin/main' into fix/234-v2
PetrefiedThunder Oct 26, 2026
72f1d97
fix(053): apply amw_tenant_isolation to repaired resolution tables
PetrefiedThunder Oct 26, 2026
e62d99e
Revert "feat(migrations): add opt-in TENANT_RLS_MODE=enable and PG RL…
PetrefiedThunder Oct 26, 2026
ae9a810
Merge e62d99e2a into metacode/qa5-am-gateway-migrations
PetrefiedThunder Oct 26, 2026
2b820df
Merge ae9a81050 into hermes/receipt-mode-build
PetrefiedThunder Oct 26, 2026
8bcac0e
Merge 2b820dfb9 into hermes/repair-api-lineage-053
PetrefiedThunder Oct 26, 2026
01a676c
Merge remote-tracking branch 'origin/main' into fix/237-merge
PetrefiedThunder Oct 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ This repository starts with a fresh history. Releases are listed here once tagge
- Receipts: new optional signed fields `enforcement_mode` ("enforce" or
"permissive") and `gateway_build` (build commit). Each is signed only when set,
so older receipts still verify. Migration 052 adds the columns.
- Migrations: 053 recreates `receipt_resolutions`, `resolution_chain_heads`,
`approval_gate_approvals`, `api_key_usage_events` and the `api_key_usage_daily`
view on databases built by the archived api chain, only when missing.
- Replay: whitespace-only recorded `approval_id` now raises `ReplayError` like the
empty string, and `amw-replay` writes `receipts.jsonl`, `summary.json`, and
`keys.json` atomically (temp file in the output dir, then rename), leaving no
Expand Down
34 changes: 34 additions & 0 deletions gateway/docs/schema-053-rollout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Schema 053: repair databases built by the archived api chain

Migration `053_repair_api_lineage` revises `052_receipt_mode_build`. A database
that reached `050_demo_key_first_used` through the archived agent-middleware-api
chain never ran this repo's 044-046, so it lacks `receipt_resolutions`,
`resolution_chain_heads`, `approval_gate_approvals`, `api_key_usage_events` and
the `api_key_usage_daily` view. 053 creates each one only when absent, with the
columns, indexes and constraints of 044-046, and writes no rows. On a database
built from this chain it changes nothing.

On PostgreSQL, 053 also gives `receipt_resolutions` and
`resolution_chain_heads` the `amw_tenant_isolation` policy from
`048_tenant_rls` wherever that policy is missing. This is the case on an
api-chain database, because 048 ran there before these tables existed. RLS is
enabled and forced on them when `TENANT_RLS_MODE` is `enforce`, or when
`api_keys` already has forced RLS. A fresh database and a repaired api-chain
database therefore end up with identical policies. Downgrade leaves the
policies in place, together with the tables.

The api-only tables such as `insight_reporting_principals` are left in place.

## Compatibility release

Production boot requires the database revision to match the packaged head, so
a 052-packaged image cannot restart after 053 is applied. Qualify a
053-capable image against a disposable PostgreSQL copy of the database first.
These release checks have not been run against staging or production.

## Rollback

Downgrade is a documented no-op. After upgrade nothing records whether 053 or
044-046 created an object, so dropping them could destroy tables a fresh
chain owns. Rolling back to 052 leaves the repaired objects in place, which is
compatible with 052 code.
245 changes: 245 additions & 0 deletions gateway/migrations/versions/053_repair_api_lineage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,245 @@
"""Repair databases that reached 050 through the archived api chain.

Revision ID: 053_repair_api_lineage
Revises: 052_receipt_mode_build

The archived agent-middleware-api chain shares revision ids 047-050 with this
chain but never ran this repo's 044-046, so a database stamped there arrives
at 050 without receipt_resolutions, resolution_chain_heads,
approval_gate_approvals, api_key_usage_events and the
api_key_usage_daily view. This revision creates each one only when it is
absent, with exactly the columns, indexes and constraints of 044-046. It
writes no rows. On a database built from this chain it changes nothing.

PostgreSQL only: receipt_resolutions and resolution_chain_heads are
wallet-scoped, and on this chain 048_tenant_rls gives them the
amw_tenant_isolation policy. An api-chain database ran 048 before they
existed, so this revision creates that identical policy (same name and
predicate, frozen copy) on each table that lacks it. It enables and forces
RLS when TENANT_RLS_MODE is enforce or when api_keys already has forced RLS,
so the repaired tables match the posture the rest of the database already has.

Downgrade is a deliberate no-op: once applied, nothing in the schema records
whether 053 or 044-046 created an object, so dropping any of them could
destroy tables a fresh chain owns. Rolling back 044-046 remains their job.
"""

import sqlalchemy as sa
from alembic import op

revision: str = "053_repair_api_lineage"
down_revision: str = "052_receipt_mode_build"
branch_labels = None
depends_on = None

# Copied verbatim from 046_api_key_usage_events.
CREATE_API_KEY_USAGE_DAILY_VIEW_SQL = """
CREATE VIEW api_key_usage_daily AS
WITH ranked AS (
SELECT
key_id,
DATE(created_at) AS day,
status_code,
latency_ms,
created_at,
ROW_NUMBER() OVER (
PARTITION BY key_id, DATE(created_at)
ORDER BY latency_ms, id
) AS latency_rank,
COUNT(*) OVER (
PARTITION BY key_id, DATE(created_at)
) AS call_count
FROM api_key_usage_events
), positioned AS (
SELECT
*,
((call_count - 1) * 50) / 100 + 1 AS p50_floor_rank,
((call_count - 1) * 50) % 100 AS p50_remainder,
((call_count - 1) * 95) / 100 + 1 AS p95_floor_rank,
((call_count - 1) * 95) % 100 AS p95_remainder
FROM ranked
)
SELECT
key_id,
day,
COUNT(*) AS calls,
SUM(CASE WHEN status_code BETWEEN 400 AND 499 THEN 1 ELSE 0 END) AS calls_4xx,
SUM(CASE WHEN status_code BETWEEN 500 AND 599 THEN 1 ELSE 0 END) AS calls_5xx,
SUM(CASE WHEN latency_rank = p50_floor_rank THEN latency_ms * (100 - p50_remainder) / 100.0 WHEN latency_rank = p50_floor_rank + 1 THEN latency_ms * p50_remainder / 100.0 ELSE 0 END) AS p50_latency_ms,
SUM(CASE WHEN latency_rank = p95_floor_rank THEN latency_ms * (100 - p95_remainder) / 100.0 WHEN latency_rank = p95_floor_rank + 1 THEN latency_ms * p95_remainder / 100.0 ELSE 0 END) AS p95_latency_ms,
MIN(created_at) AS first_call_at,
MAX(created_at) AS last_call_at
FROM positioned
GROUP BY key_id, day
"""


def _resolution_chain_heads() -> None:
op.create_table(
"resolution_chain_heads",
sa.Column("wallet_id", sa.String(length=50), primary_key=True),
sa.Column("last_sequence", sa.Integer(), nullable=False, server_default="0"),
sa.Column("last_hash", sa.String(length=64), nullable=True),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(["wallet_id"], ["wallets.wallet_id"]),
sa.CheckConstraint(
"last_sequence >= 0", name="ck_resolution_chain_heads_sequence"
),
)


def _receipt_resolutions() -> None:
op.create_table(
"receipt_resolutions",
sa.Column("resolution_id", sa.String(length=64), primary_key=True),
sa.Column("receipt_id", sa.String(length=64), nullable=False),
sa.Column("wallet_id", sa.String(length=50), nullable=False),
sa.Column("sequence", sa.Integer(), nullable=False),
sa.Column("prev_hash", sa.String(length=64), nullable=True),
sa.Column("receipt_hash", sa.String(length=64), nullable=False),
sa.Column("outcome", sa.String(length=32), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("payload_hash", sa.String(length=64), nullable=False),
sa.Column("resolution_hash", sa.String(length=64), nullable=False),
sa.Column("signing_input", sa.Text(), nullable=False),
sa.Column("signature", sa.String(), nullable=False),
sa.Column("signature_key_id", sa.String(length=64), nullable=False),
sa.ForeignKeyConstraint(["receipt_id"], ["receipts.receipt_id"]),
sa.ForeignKeyConstraint(["wallet_id"], ["wallets.wallet_id"]),
sa.ForeignKeyConstraint(["signature_key_id"], ["signing_keys.key_id"]),
sa.UniqueConstraint(
"wallet_id", "sequence", name="uq_receipt_resolutions_wallet_seq"
),
sa.CheckConstraint("sequence >= 1", name="ck_receipt_resolutions_sequence"),
sa.CheckConstraint(
"outcome IN ('confirmed_success', 'confirmed_not_delivered')",
name="ck_receipt_resolutions_outcome",
),
)
for column in (
"receipt_id",
"wallet_id",
"receipt_hash",
"resolution_hash",
"signature_key_id",
):
op.create_index(
f"ix_receipt_resolutions_{column}",
"receipt_resolutions",
[column],
unique=column in {"receipt_id", "resolution_hash"},
)


def _approval_gate_approvals() -> None:
op.create_table(
"approval_gate_approvals",
sa.Column("nonce", sa.String(length=64), primary_key=True),
sa.Column("idempotency_key", sa.String(length=128), nullable=False),
sa.Column("args_hash", sa.String(length=128), nullable=False),
sa.Column("principal", sa.String(length=255), nullable=False),
sa.Column("tool", sa.String(length=128), nullable=False),
sa.Column("session_id", sa.String(length=128), nullable=False),
sa.Column("status", sa.String(length=16), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("deadline", sa.DateTime(), nullable=False),
sa.Column("decided_at", sa.DateTime(), nullable=True),
sa.Column("consumed_at", sa.DateTime(), nullable=True),
sa.CheckConstraint(
"status IN ('pending', 'approved', 'denied', 'expired')",
name="ck_approval_gate_approvals_status",
),
)
for column in ("idempotency_key", "status"):
op.create_index(
f"ix_approval_gate_approvals_{column}",
"approval_gate_approvals",
[column],
unique=False,
)


def _api_key_usage_events() -> None:
op.create_table(
"api_key_usage_events",
sa.Column("id", sa.String(length=36), primary_key=True),
sa.Column("key_id", sa.String(length=50), nullable=False),
sa.Column("tenant", sa.String(length=32), nullable=True),
sa.Column("method", sa.String(length=16), nullable=False),
sa.Column("endpoint", sa.String(length=512), nullable=False),
sa.Column("status_code", sa.Integer(), nullable=False),
sa.Column("latency_ms", sa.Integer(), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=False),
)
op.create_index(
"ix_api_key_usage_events_key_created",
"api_key_usage_events",
["key_id", "created_at"],
)
op.create_index(
"ix_api_key_usage_events_created", "api_key_usage_events", ["created_at"]
)


# Creation order respects foreign keys; each runs only if its table is absent.
TABLES = (
("resolution_chain_heads", _resolution_chain_heads),
("receipt_resolutions", _receipt_resolutions),
("approval_gate_approvals", _approval_gate_approvals),
("api_key_usage_events", _api_key_usage_events),
)


# Frozen copy of 048_tenant_rls's policy for its LATE_RLS_TABLES.
POLICY_NAME = "amw_tenant_isolation"
_CURRENT_WALLET = "NULLIF(current_setting('app.current_wallet_id', true), '')"
_BYPASS = "current_setting('app.rls_bypass', true) = 'on'"
RLS_TABLES = ("receipt_resolutions", "resolution_chain_heads")


def _apply_tenant_policy(bind) -> None:
from app.core.config import get_settings

forced_already = bind.execute(
sa.text(
"SELECT relforcerowsecurity FROM pg_class "
"WHERE relname = 'api_keys' AND relkind = 'r' "
"AND relnamespace = current_schema()::regnamespace"
)
).scalar()
enforce = get_settings().TENANT_RLS_MODE == "enforce" or bool(forced_already)
predicate = f"(wallet_id = {_CURRENT_WALLET}) OR {_BYPASS}"
for table in RLS_TABLES:
has_policy = bind.execute(
sa.text(
"SELECT 1 FROM pg_policy WHERE polname = :name "
"AND polrelid = to_regclass(:table)"
),
{"name": POLICY_NAME, "table": table},
).scalar()
if has_policy:
continue
if enforce:
op.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")
op.execute(f"ALTER TABLE {table} FORCE ROW LEVEL SECURITY")
op.execute(
f"CREATE POLICY {POLICY_NAME} ON {table} AS PERMISSIVE FOR ALL "
f"USING ({predicate}) WITH CHECK ({predicate})"
)


def upgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
tables = set(inspector.get_table_names())
for name, create in TABLES:
if name not in tables:
create()
if "api_key_usage_daily" not in set(inspector.get_view_names()):
op.execute(CREATE_API_KEY_USAGE_DAILY_VIEW_SQL)
if bind.dialect.name == "postgresql":
_apply_tenant_policy(bind)


def downgrade() -> None:
"""No-op by design; see the module docstring."""
95 changes: 95 additions & 0 deletions gateway/tests/test_repair_api_lineage_migration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
"""053 restores 044-046 objects missing from databases built by the api chain."""

import asyncio

from alembic import command
from alembic.config import Config
from alembic.script import ScriptDirectory
from sqlalchemy import create_engine, inspect, text

TABLES = (
"receipt_resolutions",
"resolution_chain_heads",
"approval_gate_approvals",
"api_key_usage_events",
)
VIEW = "api_key_usage_daily"


def _config(tmp_path, monkeypatch):
db_path = tmp_path / "repair.db"
monkeypatch.setenv("DATABASE_URL", f"sqlite+aiosqlite:///{db_path}")
return Config("alembic.ini"), f"sqlite:///{db_path}"


def _run(fn, config, target):
fn(config, target)
asyncio.set_event_loop(asyncio.new_event_loop())


def _shape(sync_url):
engine = create_engine(sync_url)
insp = inspect(engine)
shape = {
name: (
[
(c["name"], str(c["type"]), c["nullable"])
for c in insp.get_columns(name)
],
sorted(
(i["name"], tuple(i["column_names"]), bool(i["unique"]))
for i in insp.get_indexes(name)
),
sorted(str(c["sqltext"]) for c in insp.get_check_constraints(name)),
sorted(
(tuple(f["constrained_columns"]), f["referred_table"])
for f in insp.get_foreign_keys(name)
),
)
for name in TABLES
}
views = set(insp.get_view_names())
engine.dispose()
return shape, views


def test_053_follows_052():
script = ScriptDirectory.from_config(Config("alembic.ini"))
rev = script.get_revision("053_repair_api_lineage")
assert rev.down_revision == "052_receipt_mode_build"
assert len(script.get_heads()) == 1


def test_fresh_chain_upgrade_is_noop_for_053(tmp_path, monkeypatch):
config, sync_url = _config(tmp_path, monkeypatch)
_run(command.upgrade, config, "052_receipt_mode_build")
before = _shape(sync_url)
_run(command.upgrade, config, "053_repair_api_lineage")
assert _shape(sync_url) == before


def test_missing_objects_are_recreated_with_main_shape(tmp_path, monkeypatch):
config, sync_url = _config(tmp_path, monkeypatch)
_run(command.upgrade, config, "052_receipt_mode_build")
expected = _shape(sync_url)
engine = create_engine(sync_url)
with engine.begin() as conn:
conn.execute(text(f"DROP VIEW {VIEW}"))
for name in (
"receipt_resolutions",
"resolution_chain_heads",
"approval_gate_approvals",
"api_key_usage_events",
):
conn.execute(text(f"DROP TABLE {name}"))
engine.dispose()

_run(command.upgrade, config, "head")
shape, views = _shape(sync_url)
assert shape == expected[0]
assert VIEW in views
# A second upgrade is a no-op and downgrade leaves every object in place.
_run(command.upgrade, config, "head")
_run(command.downgrade, config, "052_receipt_mode_build")
shape, views = _shape(sync_url)
assert shape == expected[0] and VIEW in views
Loading