Skip to content

feat(contracts): inventory, ledger, and tier-1 scenario catalogs for the legacy native surface [api-v2 phase 1] - #902

Merged
Quick104 merged 16 commits into
apiv2from
api-v2/phase-1-scenario-catalogs
Sep 5, 2026
Merged

Quick104 merged 16 commits into
apiv2from
api-v2/phase-1-scenario-catalogs

Conversation

@Quick104

@Quick104 Quick104 commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Problem

Related issue: #135 (phase issue: #881)

Migrating the native API to /api/v2 starts with knowing exactly what the legacy surface is, who calls it, and what it does. Today none of that is recorded: routes are registered across three listeners with conditional wiring (the fully-wired golden fixture reaches only 368 of the API listener's 691 registrations), first-party client call sites live in three repositories with no mapping to server routes, and the behavior each release-critical route is expected to keep exists only in the handlers. Phase 1 of the program makes the surface enumerable, ledgered, and baselined before any v2 code is written.

Base branch: api-v2/phase-0-program-setup (PR #880) — stacked; merge #880 first. Phase 2 (the Huma foundation, #882) stacks on this branch.

Approach

Three stages, one commit series each, all under contracts/api/v2/ with CI gates:

Stage A — route inventory (contracts/api/v2/route-inventory.json, 762 method+path rows across four listeners: root ServeMux, API, proxy, transcode node). cmd/route-inventory enumerates registrations from source with go/packages type information, recording conditions instead of evaluating them, so conditional wiring cannot hide a route. The completeness guarantee is structural: each listener entry function returns a sealed http.Handler whose dynamic type is never a router; the constructors are unexported and the generator audits the sealing invariant; closures passed to Use/With/NotFound/MethodNotAllowed are leak-checked; a full-tree ruleguard lint rule reports any type assertion, type switch, generic instantiation, or reflection that recovers a router; runtime reconcile tests in every listener package are the backstop. The analysis is pinned to the linux production build and refuses any build-constrained non-test file in an audited package; the reflect and unsafe shapes that could reach the router behind a sealed handler are refused as well. make verify-route-inventory byte-checks the artifact in CI. No production route registration changed; internal/streamtelemetry identifies capture functions with %p instead of reflect.Value.Pointer (same semantics) because the sweep now refuses that call.

Stage B — consumer inventory and migration ledger (contracts/api/v2/migration.json + JSON Schema, internal/contractledger). One entry per inventory row with the plan's required fields: 1,100 first-party call sites across web, Apple, and Android (siblings read from pinned origin/main commits recorded in the ledger header; sites resolved and content-checked against those pins by a test), server-internal URL builders, release flow and tier, and a proposed disposition per row under conservative rules (709 ported, 39 documented exclusions, 8 removed — the string settings routes already in the v1-scope removals table — 6 redesigned per already-ratified decisions; 491 rows are tier 1). make verify-migration-ledger reconciles every inventory-copied field and fails on any drift or unledgered route. Every row is review_state: proposed; owners are pending until execution input 1 on #135 names reviewers. The extraction and merge scripts are committed under scripts/apiv2-ledger/.

Stage C — tier-1 scenario catalogs and harnesses (contracts/api/v2/scenarios/, internal/scenariocatalog, internal/apibench). A closed schema for behavior scenarios (status/headers, data meaning, presence/nullability, authorization, sorting, filtering, pagination, error, raw protocol) with a predicate vocabulary that pins product behavior, an in-process executor over the real router and middleware (principals minted through the real session, API-key, and profile-token paths), a gate that ties every tier-1 row to catalog coverage, and the wave-1 (identity and discovery) catalogs populated: 70 rows, 579 scenarios, every one passing against a scratch database. Accidental current behavior is recorded faithfully and flagged in notes for the section PRs rather than corrected (72 flags, including a typed-nil panic on avatar upload, 500s where 409/422 belong, and API-key listing returning full secrets). Per the maintainer decision on #135, later waves populate their catalogs before their first section PR. The executor learns which routes the offline (no-database) wiring registers from a committed golden (contracts/api/v2/offline-routes.txt, 304 routes) that an in-package test generates and byte-verifies, so nothing outside the listener packages recovers a router. The hot-path benchmark harness captures latency percentiles, throughput, bytes, allocations, and database counters with no thresholds (budgets are execution input 6).

Validation

  • make embed-stub, go build ./..., gofmt (empty), go vet ./...: pass.
  • golangci-lint run --new-from-merge-base="origin/main" ./...: 0 issues. make lint-router-recovery (full tree): 0 issues.
  • make test-go: all packages ok.
  • make verify-route-inventory, make verify-migration-ledger, make verify-scenario-catalogs, make verify-offline-routes: pass, deterministic across two regenerations each.
  • Executor: CI subset passes offline; the full wave-1 set passes against a scratch database gated on SILO_SCENARIO_DATABASE_URL (the executor refuses any database holding media rows, non-fixture users, or secret-bearing settings, and checks before migrating).
  • make verify-settings-bindings-all, make verify-playback-fixtures, make verify-local-paths: pass (the leak check now also scans catalog bodies for non-reserved hosts, IPs, and credentials).
  • Web: pnpm run lint, format:check, build, make test-web: pass.

Scope

14 commits, three stages; every commit is a Conventional Commit and the stage boundaries are visible in the history. The architecture doc gains three subsections (route inventory, migration ledger, scenario catalogs).

Risks

  • Contract artifacts only; no served route changes. The sealing refactor changes the declared return type of the listener entry functions from chi.Router to http.Handler; every caller already consumed them as http.Handler, and the in-package tests now use the unexported constructors.
  • Ledger dispositions are proposals awaiting ratification; nothing is removed by this PR.
  • SILO_SCENARIO_DATABASE_URL is a new, deliberately separate variable so the executor's reseed cannot touch the database other DB-gated tests share.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.

AI Disclosure

  • Harness: Claude Code
  • Tool(s): Claude Code (orchestrator session driving implementation and review subagents)
  • Model(s): claude-opus-5 (early stage A rounds), claude-fable-5 (later implementation, orchestration, and all review agents)
  • Involvement: Fully AI-generated; maintainer review pending (opened by the orchestrating agent under the maintainer's program instruction)
  • Adversarial review: every stage went through repeated independent blind panels. Stage A had four hardening rounds against an xhigh completeness re-attack that reproduced bypasses with synthetic repositories and against the real tree; the final design (sealed handlers plus type-audited constructors plus a full-tree lint rule) replaced the earlier AST carrier-tracking layer per the maintainer decision recorded on API v2 program epic: /api/v2 contract reset on Huma, bounded bridge, v1 retirement at 1.0 #135. Stage B had three rounds (helper-built client paths, mis-rooted call sites, gate reconciling only one field, source-tree pins). Stage C had a scenario-fidelity review that checked 36 scenarios against handler source plus security, gate, and hygiene lenses (executor database isolation, cross-account authorization coverage, leak-check scope). All blocking and major findings were fixed and re-reviewed; dismissed findings are recorded on API v2 program epic: /api/v2 contract reset on Huma, bounded bridge, v1 retirement at 1.0 #135.

Quick104 and others added 14 commits September 1, 2026 14:41
…sses

Track chi/ServeMux constructions in every binding form (var, multi-value,
parenthesized, package scope), refuse listener handlers passed to helpers
the audit cannot see into, and refuse method-aware ServeMux patterns.

Co-Authored-By: Claude Fable 5 <[email protected]>
…s, and carrier escapes

Round-3 hardening of the source sweep: ServeMux/chi.Mux built via new() or
literals, constructors reached through function values or dot-imports,
DefaultServeMux and pprof/expvar registrations, http.Handler-parameter
callees audited with the parameter as a carrier, and carriers bound in any
form. Adds a root-listener runtime reconcile test in cmd/silo.

Co-Authored-By: Claude Fable 5 <[email protected]>
…sweep and lint rule

Loads the module with go/packages and resolves router identity through
go/types, deletes the AST carrier-tracking layer and its fixtures, and adds a
ruleguard rule that reports type assertions to router types outside tests.
Artifact unchanged at 762 routes.

Co-Authored-By: Claude Fable 5 <[email protected]>
Each listener entry function now returns a sealed http.Handler whose dynamic
type is never a router; the chi/ServeMux constructors are unexported and the
generator audits the sealing invariant with type information. Closures and
IIFEs passed to Use, With, NotFound, and MethodNotAllowed are leak-checked.
The ruleguard rule matches router types by method set and is enforced
full-tree by a dedicated lint step. Artifact unchanged at 762 routes.

Co-Authored-By: Claude Fable 5 <[email protected]>
…nter laundering

Pins the analysis to the linux production build and refuses any
build-constrained non-test file in an audited package, refuses reflect.NewAt
and the reflect pointer/method-enumeration calls that recover a sealed router
without an unsafe import, refuses unsafe imports in the audited packages, and
widens the ruleguard patterns to match router types in any type-switch clause
position, generic instantiations, and the Route/Group/With shapes. The full-tree
lint step now names every offender. internal/streamtelemetry identifies capture
functions with fmt %p instead of reflect.Value.Pointer, which the sweep now
refuses; identity semantics are unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>
Resolves helper-built client paths and Kotlin/Swift string builders in the
consumer extractor, pins the sibling source trees by commit, reconciles every
inventory-copied field in the gate, adds owner and administrator-action
fields to removed/redesigned rows, applies the root-probe rule to the node
listeners, and reclassifies release flows by route intent.

Co-Authored-By: Claude Fable 5 <[email protected]>
The pinned-tree test now fails, rather than skips, when a sibling checkout is
present but its pinned commit is unfetched, and asserts each site mentions the
route's last static segment near the credited line. Sites whose literal lives
in a constant carry path_literal_line; stream-URL resolvers are recorded with
the new follower match kind.

Co-Authored-By: Claude Fable 5 <[email protected]>
… harness

Adds the scenario-catalog schema, the wave-1 (identity and discovery)
catalogs, a gate that ties tier-1 ledger rows to catalog coverage, an
in-process executor over the real router and middleware, and a hot-path
benchmark harness with no thresholds.

Co-Authored-By: Claude Fable 5 <[email protected]>
…og gates

Gates the executor on a dedicated SILO_SCENARIO_DATABASE_URL and runs the
scratch guard before migrations, scopes the leak check to catalog bodies
with a reserved-origin allowlist, requires at least one executable
assertion per tier-1 row and the right catalog per route group, adds the
cross-account profile-header scenario to every profile-scoped row, and keeps
database credentials out of the benchmark usage text.

Co-Authored-By: Claude Fable 5 <[email protected]>
…d pin cross-request effects

Derives rate limiting from the ledger so every scenario on a rate-limited
registration exercises the limiting middleware, adds the then and none
primitives, rejects vacuous collection predicates and non-JSON bodies, mints
impersonation tokens through the real service, pins path-level cross-account
cases on profile mutations, and widens the leak check to the generators.

Co-Authored-By: Claude Fable 5 <[email protected]>
…overage counts honest

The non_empty guard now exempts only every/none, the gate reports offline
candidates with the executor's own predicate, the verify-pin cross-account
probe targets a seeded PIN-bearing profile so an unscoped lookup would be
detected, and the leak check no longer mistakes filenames for hostnames.

Co-Authored-By: Claude Fable 5 <[email protected]>
…olden

The executor no longer recovers the API router from its sealed handler to
learn which routes the offline wiring registers. An in-package test builds
the same wiring through the unexported constructor, walks it, and byte-checks
contracts/api/v2/offline-routes.txt; the executor loads that golden and
refuses one generated for a different wiring.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104 Quick104 added api-v2 API v2 / Huma migration program (epic #135); long-running, stacked by phase stacked Base is another open PR; merge in stack order named in the body labels Sep 2, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 2, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-02T13:31:54.920767Z ee2371a New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Team

Run ID: d4eefc9d-8260-4eb4-9051-86bf8a14d969

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4c1ae028df

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

`TRUNCATE TABLE device_login_requests`,
`TRUNCATE TABLE invite_codes RESTART IDENTITY CASCADE`,
`TRUNCATE TABLE invitations RESTART IDENTITY CASCADE`,
`TRUNCATE TABLE access_groups RESTART IDENTITY CASCADE`,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve the seeded default access group

Truncating access_groups removes the Default Group inserted by 20260702173000_default_access_group.sql, while the only replacement created later is Fixture Group with IsDefault left false. auth.UserRepository.Create assigns new non-admin accounts with SELECT id FROM access_groups WHERE is_default, so signup and invitation-acceptance scenarios create ungrouped users and baseline different effective policy behavior from a migrated production database. Recreate a default fixture group before creating users.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ee2371a. Reseed now re-inserts the migration-seeded Default Group (same column set and values as 20260702173000_default_access_group.sql) immediately after the truncate, before any fixture user exists, so users.Create attaches it exactly as in production. TestReseedRestoresDefaultGroup asserts one is_default row named Default Group, that the seeded member inherited it, and that a user created through the real auth.Service.Signup path lands in it; the test fails with 'default access groups after Reseed = 0, want 1' when the INSERT is removed. The wave-1 catalogs did not change: 579/579 pass before and after, and no committed scenario depended on group membership or ceilings.

Comment on lines +104 to +107
if s.HasStatements() {
var calls int64
if err := s.Pool.QueryRow(ctx, `SELECT COALESCE(SUM(calls), 0) FROM pg_stat_statements`).Scan(&calls); err != nil {
return nil, fmt.Errorf("pg_stat_statements: %w", err)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Exclude sampler queries from statement-call deltas

When pg_stat_statements is installed, this cluster-wide sum includes every database and the sampler's own SQL. The first sampling query completes after its value is read, so the second sample counts that query (and the intervening pg_stat_database query) as API work; activity from sibling databases is counted too. This materially inflates statement_calls and calls_per_request, especially for once paths, so filter by the target database and exclude the sampler statements.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ee2371a. The calls query now joins pg_database on dbid and filters datname = $1, and excludes the sampler's own rows. A leading comment does not survive pg_stat_statements normalization (verified on the pg18 image with compute_query_id=auto), and string constants are replaced by $n, so every sampler statement carries the identifier alias AS apibench_sampler and the filter is strpos(query, 'apibench_sampler') = 0, with NULL query text counted rather than dropped. Verified on a scratch pg_stat_statements container: idle resample is stable, one foreign SELECT bumps the delta by exactly 1. The remaining residual (other clients of the same database inside the window) is documented in the code and README. TestSamplerStatementsCarryTag pins the alias; TestPostgresSamplerExcludesItself is gated on SILO_BENCH_DATABASE_URL.

Comment thread cmd/apibench/main.go Outdated
Comment on lines +118 to +123
func databaseName(dsn string) string {
u, err := url.Parse(dsn)
if err != nil {
return ""
}
return strings.TrimPrefix(u.Path, "/")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Derive the database name through pgx

When -db or SILO_BENCH_DATABASE_URL uses pgx's supported keyword/value connection form, such as host=... dbname=silo, the pool connects successfully but this URL-only parser returns the wrong database name. The subsequent pg_stat_database WHERE datname = $1 sample finds no row, its error is merely logged, and the report silently omits database metrics. Read the database from pgx's parsed connection configuration or query current_database() instead.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ee2371a. databaseName now uses pgx.ParseConfig(dsn).Database, so URL and keyword/value forms resolve identically to what the pool connects to, and it rejects a DSN that names no database rather than letting the sampler filter silently match nothing. TestDatabaseName covers both forms plus invalid and database-less DSNs with PGDATABASE/PGSERVICE cleared.

…t timeout

CI's diff-scoped golangci-lint run exceeded the 5m run.timeout on this
branch, and review on #902 found three defects in the Phase 1 harnesses:
the scenario executor's Reseed truncated access_groups and lost the
migration-seeded Default Group that users.Create attaches to new users;
the apibench pg_stat_statements sampler counted every database and its
own probe queries; and cmd/apibench derived the database name by hand
from the DSN.

- .golangci.yml: run.timeout 5m -> 15m; the CI command is unchanged.
- executor.Reseed re-inserts Default Group with the migration's column
  set before any fixture user exists; TestReseedRestoresDefaultGroup
  covers the row, inherited membership, and the real signup path. The
  wave-1 catalogs are unchanged (579/579 before and after).
- Sampler statements filter pg_stat_statements to the target database
  and exclude their own rows by an identifier alias (comments and string
  constants do not survive query normalization). NULL query text is
  counted rather than dropped. Unit and DB-gated tests added.
- databaseName uses pgx.ParseConfig and rejects a DSN that names no
  database, so the sampler filter cannot silently match nothing.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ee2371a7f2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread cmd/apibench/main.go
Comment on lines +88 to +89
if *metricsURL != "" {
runner.Metrics = &apibench.PrometheusSampler{URL: *metricsURL}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor the plan's metrics URL

When a benchmark plan supplies the documented metrics_url field but the caller does not also pass -metrics, this condition leaves runner.Metrics nil, so the report silently says metrics_sampled: false and omits allocation measurements. The shipped example plan includes this field, and Plan.MetricsURL describes it as the allocation endpoint; use it as the fallback when the CLI override is empty.

Useful? React with 👍 / 👎.

The fixture's amd64-only file registers /hidden with a handler that was
never defined, so on an amd64 runner the loader reported a compile error
instead of the constraint refusal the test asserts. On arm64 hosts the
file is excluded and the case passed, which is why this only surfaced in
CI once the lint timeout stopped masking the test step. Define the
handler in the unconstrained file so the sweep is what refuses the
fixture under every GOARCH.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

@Quick104 Quick104 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two new P2 findings in the performance harness are attached inline. These affect the evidence used to assess the migration, rather than production request dispatch. The existing metrics_url finding is also still present at this revision; I have not duplicated that thread.

Validation: reproduced the unexpanded search term with the benchmark runner and a fake HTTP transport; traced the warm-up requests through the production playback idempotency paths. No live performance comparison or database-backed scenario run was performed.

Reviewed as part of the api-v2 stack intended for individual review and a coordinated merge once satisfactory. Review tooling: Codex, with gpt-6-astra subagents at medium reasoning and parent verification.

Comment on lines +317 to +323
// Warm-up (and session capture for playback start).
for i := 0; i < r.Plan.Warmup || (p.CaptureSessionID && i == 0); i++ {
req, err := build()
if err != nil {
return res, err
}
status, raw, _, err := r.do(req)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Measure fresh playback planning instead of idempotent replay

Warm-up and measured requests reuse the same request body, including playback_attempt_id and replan_request_id. After successful warm-up, measured requests return stored responses before performing planning. Playback start forces this warm-up even when configured with warmup: 0. Consequently, the reported latency, queries, and allocations can miss planning regressions entirely. Measured mutations need fresh identities and suitable session setup.

The replay paths return before planning in playback start and replan.

}

build := func() (*http.Request, error) {
u := base + strings.ReplaceAll(p.URL, "${session_id}", r.currentSession())

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Expand environment placeholders in benchmark URLs

URL construction expands ${session_id} only. The shipped example uses ${SILO_BENCH_SEARCH_TERM}, which reaches the server literally. I reproduced setting the variable to Arrival and receiving ${SILO_BENCH_SEARCH_TERM} in the query. This can produce an empty-result benchmark instead of the intended search workload. Expand the configured URL placeholders as well as the captured session placeholder.

Reviewed URL construction.

Base automatically changed from api-v2/phase-0-program-setup to apiv2 September 5, 2026 04:27
@Quick104
Quick104 merged commit 4482786 into apiv2 Sep 5, 2026
8 checks passed
@Quick104
Quick104 deleted the api-v2/phase-1-scenario-catalogs branch September 5, 2026 04:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api-v2 API v2 / Huma migration program (epic #135); long-running, stacked by phase stacked Base is another open PR; merge in stack order named in the body

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant