Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
18 changes: 18 additions & 0 deletions gateway/app/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,15 @@ class Settings(BaseSettings):
DATABASE_URL: str = ""
REDIS_URL: str = ""
SQLITE_URL: str = ""
# PostgreSQL row-level security for wallet-scoped tables (migration
# 048_tenant_rls), ported from the archived agent-middleware-api Settings
# with the same name, default and validation. "off" (default): the
# migration creates the policies but leaves RLS disabled, so nothing
# changes for any client. "enforce": migrating in this mode enables and
# forces RLS. This gateway does not yet set app.current_wallet_id per
# transaction, so enforce fails closed for a NOSUPERUSER NOBYPASSRLS
# runtime role; see docs/schema-048-rollout.md. No effect on SQLite.
TENANT_RLS_MODE: str = "off"

# --- Database Pool Settings ---
# Used for SQLModel/SQLAlchemy async sessions
Expand Down Expand Up @@ -317,6 +326,15 @@ def demo_allowed_tools_list(self) -> list[str]:
# advertised rate drift from the rate real money converts at.
EXCHANGE_RATE: Decimal = Decimal("1000.0")

@field_validator("TENANT_RLS_MODE")
@classmethod
def _validate_tenant_rls_mode(cls, value: str) -> str:
"""Only the two documented modes; a typo must not silently mean off."""
normalized = (value or "").strip().lower()
if normalized not in {"off", "enforce"}:
raise ValueError("TENANT_RLS_MODE must be 'off' or 'enforce'")
return normalized

@field_validator("EXCHANGE_RATE")
@classmethod
def _validate_exchange_rate(cls, value: Decimal) -> Decimal:
Expand Down
12 changes: 11 additions & 1 deletion gateway/app/db/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,17 @@
"created_at",
}
),
"mcp_dispatch_attempts": frozenset({"dispatch_claim_hash"}),
"mcp_dispatch_attempts": frozenset(
{
"dispatch_claim_hash",
"reconcile_status",
"reconcile_lease_owner",
"reconcile_lease_expires_at",
"reconcile_next_probe_at",
"reconcile_probe_count",
"reconciled_at",
}
),
"resolution_chain_heads": frozenset({"last_sequence", "last_hash"}),
"receipt_resolutions": frozenset(
{
Expand Down
15 changes: 15 additions & 0 deletions gateway/app/db/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1253,6 +1253,21 @@ class McpDispatchAttemptModel(SQLModel, table=True):
completed_at: Optional[datetime] = Field(
sa_type=NaiveUTCDateTime, default=None, index=True
)
# Provider-status reconciliation (047_dispatch_reconcile_lease, ported from
# the agent-middleware-api chain). Nothing in this service writes them yet;
# they are mapped so the model matches databases migrated by either chain.
reconcile_status: Optional[str] = Field(default=None, max_length=32, index=True)
reconcile_lease_owner: Optional[str] = Field(default=None, max_length=64)
reconcile_lease_expires_at: Optional[datetime] = Field(
sa_type=NaiveUTCDateTime, default=None, index=True
)
reconcile_next_probe_at: Optional[datetime] = Field(
sa_type=NaiveUTCDateTime, default=None, index=True
)
reconcile_probe_count: int = Field(
default=0, sa_column_kwargs={"server_default": "0"}
)
reconciled_at: Optional[datetime] = Field(sa_type=NaiveUTCDateTime, default=None)

model_config = {"arbitrary_types_allowed": True}

Expand Down
36 changes: 36 additions & 0 deletions gateway/docs/schema-047-rollout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Schema 047: dispatch reconcile lease (ported)

Migration `047_dispatch_reconcile_lease` revises `046_api_key_usage_events`. It is
ported from the archived agent-middleware-api chain with the same revision id,
so databases that service already migrated to 047-050 (staging and production,
both at `050_demo_key_first_used`) are at a revision this repository knows.

It adds nullable `reconcile_status`, `reconcile_lease_owner`,
`reconcile_lease_expires_at`, `reconcile_next_probe_at`, `reconciled_at`, and
`reconcile_probe_count` (NOT NULL, default 0) to `mcp_dispatch_attempts`, plus
three indexes. Columns and indexes are added only when missing. No row is
updated. `McpDispatchAttemptModel` maps the columns; nothing here writes them yet.

## Lineage gap for databases at the api chain's 050

The two chains share 001-042 and then diverge. A database migrated by the api
chain to 050 never ran this repository's `044_receipt_resolutions`,
`045_approval_gate_approvals`, or `046_api_key_usage_events`. Because 047 now
follows this repository's 046, Alembic treats those as applied, so such a
database stays at 050 without `receipt_resolutions`, `resolution_chain_heads`,
`approval_gate_approvals`, `api_key_usage_events`, or the `api_key_usage_daily`
view. It also keeps the api-only insights tables, which no model here maps.
This port does not repair that; a later idempotent migration must create the
missing objects before code that uses them serves against such a database.

## Compatibility release

Production boot requires the database revision to match the packaged head.
Fresh databases from this chain gain 047-050 normally. Qualify against a
disposable PostgreSQL upgrade from 046 and from an api-chain 050 copy.
These release checks have not been run against staging or production.

## Rollback boundary

Downgrade to 046 refuses while any row has a non-NULL `reconcile_status` and
otherwise drops the six columns and three indexes.
39 changes: 39 additions & 0 deletions gateway/docs/schema-048-rollout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Schema 048: tenant RLS policies (ported)

Migration `048_tenant_rls` revises `047_dispatch_reconcile_lease`. It is ported
from the agent-middleware-api chain with the same revision id and is
PostgreSQL only. It creates the `amw_tenant_isolation` policy on the 15
archived wallet-scoped tables and the `amw_delegated_issuer_read` policies.

The two wallet-scoped tables from this repo's 044, `receipt_resolutions` and
`resolution_chain_heads`, get the same `amw_tenant_isolation` policy when they
already exist. On an api-chain database they don't exist yet;
`053_repair_api_lineage` creates them and applies the identical policy.

`TENANT_RLS_MODE` is ported from the api Settings with the same default (`off`)
and the same validation (`off` or `enforce`).

- `off`: the policies exist, but row-level security stays disabled, so nothing
changes. This matches the original's default.
- `enforce`: running the migration enables and forces RLS on every listed table.

`migrations/env.py` sets `app.rls_bypass` to `on` for the migration
transaction only, as the archived env.py did. That lets data migrations, such
as the 050 backfill, see every row under FORCE with a non-superuser owner.

## Compatibility release

There is no behaviour change in `off` mode.

Warning: this gateway does not yet set `app.current_wallet_id` per transaction
(the api repo's runtime tenant scope is not ported). A database that was
migrated under `enforce` therefore fails closed for a NOSUPERUSER NOBYPASSRLS
runtime role: wallet-scoped tables read as empty and writes are refused. That
includes an api-chain 050 database that already has RLS forced. Don't migrate
under `enforce`, and don't point this gateway at such a database with a
policy-bound role, until the runtime scope is ported.

## Rollback

Downgrade drops the policies. It also runs NO FORCE / DISABLE ROW LEVEL
SECURITY on each listed table, including the two late tables when they exist.
9 changes: 9 additions & 0 deletions gateway/docs/schema-049-rollout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Schema 049: demo key attribution (ported)

Migration `049_demo_key_attribution` revises `048_tenant_rls`, ported with the
same revision id. `043_demo_key_fields` already adds the UTM and referrer
columns here, so on this chain it adds only missing columns (normally none).

## Rollback boundary

Downgrade is a no-op; the columns belong to 043, which retains them.
11 changes: 11 additions & 0 deletions gateway/docs/schema-050-rollout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Schema 050: demo key first use (ported)

Migration `050_demo_key_first_used` revises `049_demo_key_attribution`, ported
with the same revision id. `043_demo_key_fields` already adds
`api_keys.first_used_at` and the `demo_key_funnel_by_source` view, so this adds
them only when missing and backfills only NULL `first_used_at` from
`last_used_at`. Staging and production are at this revision.

## Rollback boundary

Downgrade is a no-op; the column and view belong to 043, which retains them.
9 changes: 9 additions & 0 deletions gateway/migrations/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,15 @@ def do_run_migrations(connection: Connection) -> None:
context.configure(connection=connection, target_metadata=target_metadata)

with context.begin_transaction():
if connection.dialect.name == "postgresql":
# Explicit admin mechanism for migrations, as in the archived api
# chain: FORCE ROW LEVEL SECURITY (048_tenant_rls, enforce mode)
# binds the table owner too, so data migrations such as the 050
# backfill opt out of the wallet policies for this transaction
# only (set_config is_local=true, the SET LOCAL equivalent).
connection.exec_driver_sql(
"SELECT set_config('app.rls_bypass', 'on', true)"
)
context.run_migrations()


Expand Down
107 changes: 107 additions & 0 deletions gateway/migrations/versions/047_dispatch_reconcile_lease.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
"""Add provider-status reconciliation columns to governed MCP dispatch attempts.

Additive and nullable (the probe counter defaults to zero). Existing
``delivery_uncertain`` rows upgrade to an unresolved reconcile status, which
is exactly their meaning today: parked for manual review. No data update or
backfill is performed, and ``state`` is never touched.

Revision ID: 047_dispatch_reconcile_lease
Revises: 046_api_key_usage_events

Ported from the archived agent-middleware-api chain with the same revision
id so databases already stamped at 047-050 by that service stay on a known
revision. Here it follows this repo's 046. Columns and indexes are added only
when missing.
"""

from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op


revision: str = "047_dispatch_reconcile_lease"
down_revision: Union[str, None] = "046_api_key_usage_events"
Comment thread
PetrefiedThunder marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


_COLUMNS = (
(
"reconcile_status",
lambda: sa.Column("reconcile_status", sa.String(length=32), nullable=True),
),
(
"reconcile_lease_owner",
lambda: sa.Column("reconcile_lease_owner", sa.String(length=64), nullable=True),
),
(
"reconcile_lease_expires_at",
lambda: sa.Column("reconcile_lease_expires_at", sa.DateTime(), nullable=True),
),
(
"reconcile_next_probe_at",
lambda: sa.Column("reconcile_next_probe_at", sa.DateTime(), nullable=True),
),
(
"reconcile_probe_count",
lambda: sa.Column(
"reconcile_probe_count", sa.Integer(), nullable=False, server_default="0"
),
),
("reconciled_at", lambda: sa.Column("reconciled_at", sa.DateTime(), nullable=True)),
)
_INDEXES = (
("ix_mcp_dispatch_attempts_reconcile_status", "reconcile_status"),
(
"ix_mcp_dispatch_attempts_reconcile_lease_expires_at",
"reconcile_lease_expires_at",
),
("ix_mcp_dispatch_attempts_reconcile_next_probe_at", "reconcile_next_probe_at"),
)


def upgrade() -> None:
inspector = sa.inspect(op.get_bind())
columns = {c["name"] for c in inspector.get_columns("mcp_dispatch_attempts")}
indexes = {i["name"] for i in inspector.get_indexes("mcp_dispatch_attempts")}
missing_columns = [make() for name, make in _COLUMNS if name not in columns]
missing_indexes = [(n, c) for n, c in _INDEXES if n not in indexes]
if not missing_columns and not missing_indexes:
return
with op.batch_alter_table("mcp_dispatch_attempts") as batch_op:
for column in missing_columns:
batch_op.add_column(column)
for name, column in missing_indexes:
batch_op.create_index(name, [column])


def downgrade() -> None:
# Any non-NULL status is a durable provider decision. A refunded row's
# refund and budget release outlive the column, and 046 accounting counts
# every delivery_uncertain receipt as consumed, so a budget rebuild would
# re-charge the released spend; a pending row may be half applied; and a
# re-upgrade would re-probe every erased decision. Refuse rather than
# silently drop any of them.
bind = op.get_bind()
decided = bind.execute(
sa.text(
"SELECT COUNT(*) FROM mcp_dispatch_attempts "
"WHERE reconcile_status IS NOT NULL"
)
).scalar_one()
if decided:
raise RuntimeError(
f"047 downgrade refused: {decided} dispatch attempt(s) carry a "
"reconcile_status decision that 046 cannot represent"
)
with op.batch_alter_table("mcp_dispatch_attempts") as batch_op:
batch_op.drop_index("ix_mcp_dispatch_attempts_reconcile_next_probe_at")
batch_op.drop_index("ix_mcp_dispatch_attempts_reconcile_lease_expires_at")
batch_op.drop_index("ix_mcp_dispatch_attempts_reconcile_status")
batch_op.drop_column("reconciled_at")
batch_op.drop_column("reconcile_probe_count")
batch_op.drop_column("reconcile_next_probe_at")
batch_op.drop_column("reconcile_lease_expires_at")
batch_op.drop_column("reconcile_lease_owner")
batch_op.drop_column("reconcile_status")
Loading
Loading