Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 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
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
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
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
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
da49517
Merge origin/main into metacode/qa5-am-gateway-migrations
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
25 changes: 25 additions & 0 deletions gateway/docs/schema-051-rollout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Schema 051: SQLite boolean defaults and rollback boundary

Migration `051_sqlite_boolean_defaults` revises
`050_demo_key_first_used` (the api-chain port, PR #234). PR #61 must merge
after PR #234.
On SQLite it repairs legacy text booleans in refresh tokens, human approvals,
and permits, then replaces their text defaults with integer false defaults.
PostgreSQL schema and data are unchanged.

## Compatibility release before migration

Before an authorized rollout, confirm the database revision, back up the
database, and qualify a 051-capable recovery image. Rehearse the migration on
a copy of any SQLite database created before the corrected 022 and 023
migrations, including existing rows and inserts that omit these columns.
The application requires its packaged Alembic head, so an older image cannot
restart after the database reaches 051.

## Rollback after activation

SQLite downgrade raises `sqlite_boolean_defaults_downgrade_unsupported`
instead of marking a database downgraded while retaining corrected values
and defaults. Recover with a 051-capable image and the database at 051.
Returning to an older packaged head requires a separately reviewed migration
and compatibility plan.
4 changes: 3 additions & 1 deletion gateway/migrations/versions/022_refresh_tokens.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ def upgrade() -> None:
"refresh_tokens",
sa.Column("jti", sa.String(length=64), nullable=False),
sa.Column("wallet_id", sa.String(length=50), nullable=False),
sa.Column("revoked", sa.Boolean(), nullable=False, server_default="false"),
# sa.false() renders as 0 on SQLite and false on PostgreSQL. The string
# "false" is stored as text on SQLite and reads back as true.
sa.Column("revoked", sa.Boolean(), nullable=False, server_default=sa.false()),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("expires_at", sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(["wallet_id"], ["wallets.wallet_id"]),
Expand Down
6 changes: 4 additions & 2 deletions gateway/migrations/versions/023_human_approval_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,13 @@
def upgrade() -> None:
op.add_column(
"permits",
# sa.false() renders as 0 on SQLite and false on PostgreSQL. The string
# "false" is stored as text on SQLite and reads back as true.
sa.Column(
"requires_human_approval",
sa.Boolean(),
nullable=False,
server_default="false",
server_default=sa.false(),
),
)

Expand All @@ -46,7 +48,7 @@ def upgrade() -> None:
sa.Column(
"status", sa.String(length=16), nullable=False, server_default="pending"
),
sa.Column("simulated", sa.Boolean(), nullable=False, server_default="false"),
sa.Column("simulated", sa.Boolean(), nullable=False, server_default=sa.false()),
sa.Column("sentinel_action_id", sa.String(length=64), nullable=True),
sa.Column("requested_at", sa.DateTime(), nullable=False),
sa.Column("expires_at", sa.DateTime(), nullable=False),
Expand Down
57 changes: 32 additions & 25 deletions gateway/migrations/versions/024_human_approval_hardening.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,16 @@
reloaded approval reject an invoke that reused the same idempotency key with
different arguments or a different current price.

2. Repair ``permits.requires_human_approval`` on SQLite. Migration 023 added
the column with ``server_default="false"`` — a plain string that SQLite
stores as the *text* ``'false'`` and then reads back through SQLAlchemy's
non-native Boolean as ``True`` (``bool("false")``). Every permit that
existed before 023 therefore reports ``requires_human_approval=True`` and
fails signature verification (the flag enters the signed payload only when
true). Postgres parses ``'false'`` as boolean false, so it is unaffected;
the repair runs on SQLite only, normalizing any non-0/1 value back to 0.
2. Repair text booleans on SQLite. Migrations 022 and 023 added
``refresh_tokens.revoked``, ``permits.requires_human_approval``, and
``human_approvals.simulated`` with the string server default ``"false"``.
SQLite stores that as the text ``'false'``. SQLAlchemy then reads any
non-empty text as true, so a live refresh token looks revoked, a permit
looks like it requires human approval (and fails signature verification,
because the flag enters the signed payload only when true), and a real
approval looks simulated. Postgres parses ``'false'`` as boolean false, so
it is unaffected. The repair runs on SQLite only and rewrites the known
text values in the correct direction. Unexpected text is left alone.

Revision ID: 024_human_approval_hardening
Revises: 023_human_approval_gate
Expand All @@ -40,25 +42,30 @@ def upgrade() -> None:

bind = op.get_bind()
if bind.dialect.name == "sqlite":
# Existing rows backfilled by 023 hold the text 'false'. Repair only
# the known text booleans, in the correct direction, so an unexpected
# value is never silently downgraded to "approval not required" (that
# would remove a control rather than restore one). 023's server_default
# can only produce 'false', but the 'true' side is handled defensively.
op.execute(
sa.text(
"UPDATE permits SET requires_human_approval = 0 "
"WHERE typeof(requires_human_approval) = 'text' "
"AND lower(requires_human_approval) IN ('false', 'f', '0', 'no')"
# Rows created under the old string default hold the text 'false'.
# Repair only the known text booleans, in the correct direction, so an
# unexpected value is never silently turned into "not set". The old
# server default can only produce 'false', but the 'true' side is
# handled so a real true is not left as text.
for table, column in (
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
("permits", "requires_human_approval"),
("human_approvals", "simulated"),
("refresh_tokens", "revoked"),
):
op.execute(
sa.text(
f"UPDATE {table} SET {column} = 0 "
f"WHERE typeof({column}) = 'text' "
f"AND lower({column}) IN ('false', 'f', '0', 'no')"
)
)
)
op.execute(
sa.text(
"UPDATE permits SET requires_human_approval = 1 "
"WHERE typeof(requires_human_approval) = 'text' "
"AND lower(requires_human_approval) IN ('true', 't', '1', 'yes')"
op.execute(
sa.text(
f"UPDATE {table} SET {column} = 1 "
f"WHERE typeof({column}) = 'text' "
f"AND lower({column}) IN ('true', 't', '1', 'yes')"
)
)
)


def downgrade() -> None:
Expand Down
50 changes: 50 additions & 0 deletions gateway/migrations/versions/051_sqlite_boolean_defaults.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"""Repair legacy SQLite text booleans and replace their text defaults.

Revision ID: 051_sqlite_boolean_defaults
Revises: 050_demo_key_first_used
"""

from alembic import op
import sqlalchemy as sa

revision: str = "051_sqlite_boolean_defaults"
down_revision: str = "050_demo_key_first_used"
branch_labels = None
depends_on = None


def upgrade() -> None:
if op.get_bind().dialect.name != "sqlite":
return

for table, column in (
("refresh_tokens", "revoked"),
("human_approvals", "simulated"),
("permits", "requires_human_approval"),
):
op.execute(
sa.text(
f"UPDATE {table} SET {column} = 0 "
f"WHERE typeof({column}) = 'text' "
f"AND lower({column}) IN ('false', 'f', '0', 'no')"
)
)
op.execute(
sa.text(
f"UPDATE {table} SET {column} = 1 "
f"WHERE typeof({column}) = 'text' "
f"AND lower({column}) IN ('true', 't', '1', 'yes')"
)
)
with op.batch_alter_table(table) as batch_op:
batch_op.alter_column(
column,
existing_type=sa.Boolean(),
existing_nullable=False,
server_default=sa.false(),
)


def downgrade() -> None:
if op.get_bind().dialect.name == "sqlite":
raise RuntimeError("sqlite_boolean_defaults_downgrade_unsupported")
6 changes: 4 additions & 2 deletions gateway/tests/test_action_migrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,9 @@ def migrate(url, revision, direction="upgrade"):
def test_action_migration_retains_legacy_and_blocks_authority_loss(
tmp_path, start_revision, authority
):
head_revision = current_head_revision()
# Exercise the 042 downgrade without crossing the irreversible SQLite
# boolean repair in later migrations.
head_revision = "044_receipt_resolutions"
path = tmp_path / "migration.sqlite"
url = f"sqlite+aiosqlite:///{path}"
result = migrate(url, "040_permit_repeat_window")
Expand Down Expand Up @@ -121,7 +123,7 @@ def test_action_migration_retains_legacy_and_blocks_authority_loss(
("",),
("w",),
]
result = migrate(url, "head")
result = migrate(url, head_revision)
assert result.returncode == 0, result.stderr
with sqlite3.connect(path) as db:
assert db.execute("SELECT version_num FROM alembic_version").fetchone() == (
Expand Down
8 changes: 4 additions & 4 deletions gateway/tests/test_migrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -784,7 +784,7 @@ def test_041_scrubs_legacy_plaintext_owner_keys_from_content_tables(

Rows whose owner_key is a known wallet id (what the factory routers write
now) keep their owner, and an already-blank row stays blank. The rows are
inserted at head and the scrub is exercised by stepping back to 040 and
inserted at 044 and the scrub is exercised by stepping back to 040 and
forward again, which also pins that the downgrade is a no-op (the scrubbed
values were credentials and are unrecoverable) and the upgrade idempotent.
"""
Expand All @@ -796,7 +796,7 @@ def test_041_scrubs_legacy_plaintext_owner_keys_from_content_tables(

monkeypatch.setenv("DATABASE_URL", async_url)
config = Config("alembic.ini")
command.upgrade(config, "head")
command.upgrade(config, "044_receipt_resolutions")
asyncio.set_event_loop(asyncio.new_event_loop())

engine = create_engine(sync_url)
Expand Down Expand Up @@ -872,7 +872,7 @@ def owners() -> tuple[dict, dict]:

command.downgrade(config, "040_permit_repeat_window")
asyncio.set_event_loop(asyncio.new_event_loop())
command.upgrade(config, "head")
command.upgrade(config, "044_receipt_resolutions")
asyncio.set_event_loop(asyncio.new_event_loop())

pipelines, campaigns = owners()
Expand All @@ -883,6 +883,6 @@ def owners() -> tuple[dict, dict]:
# Idempotent: a second pass changes nothing.
command.downgrade(config, "040_permit_repeat_window")
asyncio.set_event_loop(asyncio.new_event_loop())
command.upgrade(config, "head")
command.upgrade(config, "044_receipt_resolutions")
asyncio.set_event_loop(asyncio.new_event_loop())
assert owners() == (pipelines, campaigns)
Loading
Loading