feat(gitlabapi): add the namespace limit block and the billing anchor (#1823 stack: 1/2)

Summary

This merge request builds the service side of the namespace billing states. It adds a nullable limit_blocked_at column to the namespaces table, with its migration. It adds a fourth reversible condition and its two literal routes, limit_block and unlimit_block. It derives a sixth status, limit_blocked, and the write predicate now reads the sixth lifecycle column.

It adds a BillingServiceable predicate that answers a limit-blocked namespace. It adds four shared reason codes and enumerates them in the OpenAPI document of the management API. It returns the billing anchor in the namespace resource.

The S33 amendment that merged in !3774 (merged) changed the spec only. It never built the service side of the billing states.

The namespaces table had no limit_blocked_at column. The status derivation had no sixth state, and the write predicate read five columns. No billing predicate existed. The OpenAPI document of the GitLab API declared neither the limit-block routes nor the billing anchor.

The spec coverage scope and the acceptance criteria

Spec coverage

Spec: docs/specs/S33-gitlab-api.md Card: issue 1823, cycle 2 -- the service side of the S33 amendment.

Scope: the limit_blocked_at column and its migration, the limit-block condition and its two routes, the derived limit_blocked status, the write predicate's sixth column, the billing predicate, the four reason codes, and the billing anchor in the resolution response. The author's decision holds the condition gates and the surfaces that answer the four reason codes for #1790; another of the author's decisions leaves the namespace soft-delete and hard-delete endpoints out of this cycle; the re-anchor endpoint is out of scope for this issue (#1666).

Acceptance criteria

# Criterion Tests
AC-1 POST /api/gitlab/v1/namespaces with a valid slug and an unused anchor returns 201, creates the row, and the response includes the namespace UUID, slug, and status: active TestCreateNamespace_ValidRequest_Returns201 (existing on main; not this unit's change)
AC-2 Repeating the same POST returns 200 with the previously created namespace, unaltered TestCreateNamespace_ExactReplay_Returns200 (existing)
AC-3 Repeating the POST with a disagreeing body returns 409; the row is unchanged TestCreateNamespace_StoreConflicts_Return409 (existing)
AC-4 With the Brand-List Validator enabled and unreachable, POST returns 503 and creates no row TestCreateNamespace_ExactReplay_OutranksSlugRefusal (existing; the "still fails closed" row)
AC-5 POST with a slug failing the syntactic rules, a reserved name, or a brand-list rejection returns 422 TestCreateNamespace_ExactReplay_OutranksSlugRefusal (existing; the brand-listed and policy-invalid rows)
AC-6 POST with a slug already taken by another namespace returns 409 TestCreateNamespace_StoreConflicts_Return409 (existing)
AC-7 GET /api/gitlab/v1/namespaces/:uuid returns the owner anchor, the billing anchor, the slug, and the derived status; an unknown UUID returns 404, a non-canonical id 400 TestResolveNamespace_ReturnsTheBillingAnchor (new: the billing anchor on the response), TestResolveNamespace_UnknownUUID_Returns404 and TestResolveNamespace_NonCanonicalID_Returns400 (existing)
AC-8 Each of the eight condition endpoints sets or clears exactly its own column; the response and a subsequent GET report the derived status with the precedence TestNamespaceCondition_EachAction_Returns200WithUpdatedResource (extended to eight actions), TestNamespaceStore_WriteCondition_Apply, TestNamespaceStore_WriteCondition_Lift, TestNamespaceStore_WriteCondition_ApplyReplayKeepsTheTimestamp, TestNamespaceStore_WriteCondition_LiftNotInEffectIsANoOp and TestNamespaceStore_Conditions_ReturnEveryLifecycleColumn (extended to the fourth condition), TestNamespaceCondition_RouteTable_MatchesTheContract
AC-9 With suspended_at or limit_blocked_at set, a client-surface download succeeds and a client-surface push is rejected The refusal is held for #1790 by the author's decision: the condition gates do not ship in this unit. The predicate half this unit owns is TestWriteServiceable and TestReadServiceable (the limit-blocked rows)
AC-10 Management-surface requests under a gated namespace are rejected by the same predicate table Held for #1790 by the author's decision
AC-11 POST .../repositories/verifications returns 204 when every id belongs, 422 listing the failing ids, 400 for a malformed batch; a soft-deleted repository verifies as belonging TestVerifyRepositories_AllIDsBelong_Returns204, TestVerifyRepositories_UnverifiedIDs_Returns422WithFailingIDs, TestVerifyRepositories_RejectedBatches_Return400 (existing)
AC-12 Resolution, condition, and verification endpoints work on a namespace in every state, including soft-deleted, purged, and limit-blocked TestNamespaceStore_FindByID_ReturnsEveryLifecycleState (now sweeps limit_blocked), TestResolveNamespace_EveryLifecycleState_Returns200, TestNamespaceCondition_EveryLifecycleState_Returns200, TestVerifyRepositories_EveryLifecycleState_Returns204 (each with limit_blocked rows)
AC-13 The OpenAPI document defines every endpoint, schema, and response above and validates against the OpenAPI 3.1 schema in CI TestContract_DocumentValidates, TestContract_LimitBlockOperations_MatchesTheRouteTable (new), TestContract_NamespaceSchema_MatchesResource (extended: seven required keys, the billing pair emitted but not required during a rolling deploy, seven statuses), TestContract_NamespaceSchema_DeclaresTheBillingAnchor (new)
AC-14 On the client and management surfaces, each condition's refusal answers 403 with the reason message and, where the surface's error shape carries the shared vocabulary, the reason code; a deleted or purged namespace answers 404; a denied caller gets S09's denial answer The refusals are held for #1790 by the author's decision: the gates and the surfaces that answer them. This unit defines and enumerates the vocabulary only -- TestErrorCodes_NamespaceReasonCodes (the four codes' wire values) and TestContract_ErrorCodeEnum_MatchesTransportCodes (the management API's enum, extended with the four)
AC-15 A billing query answers no suspended namespace and answers a limit-blocked one; a retention query answers both; the predicate is read when usage is metered TestBillingServiceable (new), TestNamespaceState_StatusPredicateConsistency (the billing column over all 64 combinations). The predicate has no caller yet: S24 (usage metering) calls it, as the serviceability gating section of S33 says
AC-16 POST .../billing_anchor with both billing fields replaces the stored billing anchor and answers 200 Out of scope for this issue (#1666)
AC-17 A body carrying one billing field and not the other answers 422 and changes nothing Out of scope for this issue (#1666)
AC-18 Repeating a request that carries the pair the row already holds answers 200 and changes nothing Out of scope for this issue (#1666)
AC-19 A re-anchor that changes the stored pair records an audit entry Out of scope for this issue (#1666)
AC-20 The re-anchor endpoint works on a namespace in every lifecycle state Out of scope for this issue (#1666)
The error cases

Error cases

# Condition Status Envelope code Tests
E-1 All: missing or invalid service token 401 unauthorized The service-token middleware's own suite (internal/auth/servicetoken); not this unit's surface
E-2 All: malformed JSON body 400 bad_request TestCreateNamespace_ValidRequest_Returns201's malformed-body case and TestVerifyRepositories_RejectedBatches_Return400 (existing)
E-3 Provision: the slug fails syntactic, reserved-name, or brand-list validation, and the anchor is free 422 unprocessable_entity TestCreateNamespace_ExactReplay_OutranksSlugRefusal (existing)
E-4 Provision: the owner anchor is not the locked triple, and the anchor holds no exactly matching row 422 unprocessable_entity TestCreateNamespace_LegacyAnchorReplay_ExemptsShapeRules (existing)
E-5 Provision: the slug is taken by another namespace 409 conflict TestCreateNamespace_StoreConflicts_Return409 (existing)
E-6 Provision: the replay body disagrees with the stored row 409 conflict TestCreateNamespace_StoreConflicts_Return409 (existing)
E-7 Provision: the Brand-List Validator is enabled but unreachable, and the anchor is free 503 service_unavailable TestCreateNamespace_ExactReplay_OutranksSlugRefusal (existing; the "still fails closed" row)
E-8 Resolution, conditions, verifications, re-anchoring: the :uuid segment is not a canonical UUID 400 bad_request TestResolveNamespace_NonCanonicalID_Returns400, TestNamespaceCondition_NonCanonicalID_Returns400, TestVerifyRepositories_NonCanonicalNamespaceID_Returns400 (existing)
E-9 Resolution, conditions, verifications, re-anchoring: unknown namespace UUID 404 not_found TestResolveNamespace_UnknownUUID_Returns404, TestNamespaceCondition_UnknownNamespace_Returns404 (existing)
E-10 Conditions: unknown <action> segment 404 not_found TestNamespaceCondition_UnknownAction_Returns404, TestNewHandler_UnknownPath_Returns404WithEnvelope (existing; the limit-block segments are literal routes, so an unregistered one takes the fallback)
E-11 Client, management: a write to a namespace suspended after a plan lapse 403 namespace_suspended The refusal is held for #1790 by the author's decision. The code is defined and enumerated here: TestErrorCodes_NamespaceReasonCodes and TestContract_ErrorCodeEnum_MatchesTransportCodes
E-12 Client, management: a write to a namespace limit-blocked because the usage limit is reached or the overage terms are not accepted 403 namespace_limit_blocked The refusal is held for #1790 by the author's decision. The code is defined and enumerated here: TestErrorCodes_NamespaceReasonCodes and TestContract_ErrorCodeEnum_MatchesTransportCodes; the predicate that will refuse the write is TestWriteServiceable's limit-blocked row
E-13 Client, management: the namespace is disabled by its owning organization 403 namespace_disabled The refusal is held for #1790 by the author's decision. The code is defined and enumerated here: TestErrorCodes_NamespaceReasonCodes and TestContract_ErrorCodeEnum_MatchesTransportCodes
E-14 Client, management: the namespace is blocked for security reasons 403 namespace_blocked The refusal is held for #1790 by the author's decision. The code is defined and enumerated here: TestErrorCodes_NamespaceReasonCodes and TestContract_ErrorCodeEnum_MatchesTransportCodes
E-15 All: body over the request size cap 413 request_entity_too_large TestVerifyRepositories_OversizedChunkedBody_Returns413 (existing)
E-16 Verifications: empty or oversized batch, or a value that is not a canonical UUID 400 bad_request TestVerifyRepositories_RejectedBatches_Return400, TestVerifyRepositories_NonCanonicalBodyIDs_Return400 (existing)
E-17 Verifications: any id unknown or outside the namespace 422 unprocessable_entity, failing ids in error.details.repository_ids TestVerifyRepositories_UnverifiedIDs_Returns422WithFailingIDs, TestVerifyRepositories_FailureMessage_IsStatic (existing)
E-18 Re-anchoring: the body carries one billing field and not the other 422 unprocessable_entity Out of scope for this issue (#1666)
E-19 Re-anchoring: billing_entity_id is empty or longer than 255 characters 422 unprocessable_entity Out of scope for this issue (#1666)
E-20 Re-anchoring: billing_entity_type is not a value the payer enum holds 422 unprocessable_entity Out of scope for this issue (#1666)
The security considerations

Security considerations

# Concern Tests
S-1 The surface is internet-facing but never customer-facing; the opaque 401 gives a probing scanner nothing to distinguish The service-token middleware's own suite (internal/auth/servicetoken); not this unit's surface
S-2 The limit-block action sits under the same service token as every other route, and its action segment is a literal: a segment outside the action list matches no route and answers 404, so scanning traffic lands on no state-bearing route TestNamespaceCondition_UnknownAction_Returns404, TestNamespaceCondition_RouteRegistration_StampsOnePatternPerAction (each action is its own ServeMux route, so scanner traffic takes the fallback's series), TestNewHandler_UnknownPath_Returns404WithEnvelope. The two limit-block segments join the same literal table
S-3 The verifications 422 lists the failing ids but never the reason TestVerifyRepositories_UnverifiedIDs_Returns422WithFailingIDs, TestVerifyRepositories_FailureMessage_IsStatic (existing); not this unit's surface
S-4 Resolution returns the anchors the caller supplied, while a Kubernetes peer reads the owner and billing anchors of any namespace TestResolveNamespace_ReturnsTheBillingAnchor (new: the response carries the pair), internal/gitlabapi/peer_test.go (the peer's admission)
S-5 A condition's reason discloses a state the masked 404 used to hide; the reason reaches only a caller the authorization layer has admitted Held for #1790 by the author's decision: no surface answers a reason code yet. The codes are defined and enumerated here: TestErrorCodes_NamespaceReasonCodes and TestContract_ErrorCodeEnum_MatchesTransportCodes
S-6 Slug input crosses a trust boundary into SQL and the Brand-List Validator call TestCreateNamespace_ExactReplay_OutranksSlugRefusal (existing); not this unit's surface
S-7 The re-anchor endpoint changes who is billed Out of scope for this issue (#1666)
The behavior obligations from the spec prose

Behavior obligations from the spec prose

# Obligation Tests
B-1 "The limit block is a fourth reversible condition, with its own column limit_blocked_at" TestNamespacesLimitBlockedAt_MigrationAddsTheColumn (the migration adds the column and drops it on the way down), TestNamespaceStore_WriteCondition_Apply and _Lift (the fourth condition's own column)
B-2 "The limit block's status is limit_blocked, a new member of the status enum" TestNamespaceStatus/limit_blocked_only_derives_limit_blocked, TestNamespaceFromModel_DerivedStatus/limit_blocked_at_set_is_limit_blocked, TestContract_NamespaceSchema_MatchesResource (the enum grows to seven)
B-3 "The status precedence puts suspended above limit_blocked" TestNamespaceStatus/suspended_beats_limit_blocked, TestNamespaceState_StatusPredicateConsistency/suspended+limit_blocked
B-4 "The limit block's actions are limit_block and unlimit_block" TestNamespaceCondition_EachAction_Returns200WithUpdatedResource (the two segments, their condition and their direction), TestNamespaceCondition_RouteRegistration_StampsOnePatternPerAction, TestContract_LimitBlockOperations_MatchesTheRouteTable
B-5 "Both states make the namespace read-only, and each carries its own client reason, so one column cannot hold both" TestWriteServiceable/limit_blocked_rejects_writes and TestReadServiceable/limit_blocked_only_still_serves_reads (the read-only degradation), TestErrorCodes_NamespaceReasonCodes (the two billing reasons are distinct codes)
B-6 "A billing query answers no suspended namespace ... A limit-blocked namespace answers billing queries" TestBillingServiceable, TestNamespaceState_StatusPredicateConsistency
B-7 "The implementation adds a billing predicate beside WriteServiceable and ReadServiceable in internal/datastore/namespace_state.go" TestBillingServiceable (the predicate exists and answers the row)
B-8 "The billing anchor comes back because the caller supplied it ... the registry's row is the authority on it" TestResolveNamespace_ReturnsTheBillingAnchor, TestNamespace_WireShape, TestContract_NamespaceSchema_DeclaresTheBillingAnchor
B-9 "No indexes on the six lifecycle columns" The db:structure-check CI job (the committed structure.sql carries the column with no index, and the job fails when the migrated schema differs from it)
B-10 "GitLab API routes are exempt from gating" TestNamespaceStore_FindByID_ReturnsEveryLifecycleState (now sweeps limit_blocked), TestResolveNamespace_EveryLifecycleState_Returns200, TestNamespaceCondition_EveryLifecycleState_Returns200, TestVerifyRepositories_EveryLifecycleState_Returns204 (each with limit_blocked rows)

Database Review Evidence

Some query detail is left out of this public description: the rendered SQL, the bound arguments and the raw plans, and each detail of a confidential review thread is shown as (withheld).

Migrations

Note

Timings are from CI (db:migrate matrix, goose verbose) against an empty database, in apply / rollback order per PG version. Production-scale validation via Database Lab is not yet available. See Database review evidence for the matrix rationale and how to read the numbers.

Migration PG 16 PG 17 PG 18
20261112221200_add_namespaces_limit_blocked_at.sql OK (1.79ms / 4.62ms) OK (2.17ms / 5.08ms) OK (1.65ms / 3.82ms)

Migration notes:

  • add_namespaces_limit_blocked_at.sql: a nullable timestamptz column with no default, metadata-only in both directions. The Up and the Down set lock_timeout and statement_timeout to 5s around the ALTER TABLE. Collected from pipeline 3056435161 at head f4c39a741. No anomalies.

Queries

Note

Plans are from EXPLAIN (ANALYZE, BUFFERS) against an ephemeral PostgreSQL 17 container (17.11, matching GL_PG_CURR_VERSION from .gitlab-ci-other-versions.yml), with synthesized seed data rolled back per query and the container torn down at the end of the run. Numbers reflect moderate cardinality and do not capture production-scale effects. See Database review evidence for seed sizing, methodology, and the anomalies the skill flags. Expand each row's details for the seed shape, rendered SQL, bound args, and raw plan.

Method Plan node Index Rows (plan / actual) Cost Time Buffers (hit / read) Partitions
datastore.FindByID Limit pk_namespaces 1 / 1 8.30 0.006ms 3 / 0 n/a
datastore.WriteCondition.LimitBlockedInEffect Update pk_namespaces 1 / 1 8.30 0.619ms 156 / 0 n/a
datastore.WriteCondition.LimitBlockedLift Update pk_namespaces 1 / 1 8.30 0.112ms 8 / 0 n/a
testutil.ClearNamespaceLifecycle.limit_blocked Update pk_namespaces 0 / 0 8.30 0.090ms 8 / 0 n/a
testutil.SetNamespaceLifecycle.limit_blocked Update pk_namespaces 0 / 0 8.30 0.098ms 8 / 0 n/a

Query notes:

  • Scope: the only new statement shape is WriteCondition's limit_blocked branch (both directions) and the two testutil fixture statements. Every other namespaces read and write (FindByID, ListPage, FindBySlug, FindByAnchor, WriteCondition's other branches, the insert's RETURNING) keeps its chain byte-identical and only gains limit_blocked_at in the shared namespaceColumns() projection. FindByID stands in for that projection change.
  • The write rows use 5,000 seeded namespaces. The skill's default write seed (1 target plus 49 siblings) fits in one heap page, and there all four UPDATEs chose a Seq Scan (cost 1.63, 49 rows removed by filter); at 5,000 rows each uses pk_namespaces. No anomalies.
  • namespaces is not partitioned, so no partition pruning applies.
datastore.FindByID

Summary: Plan matches the method's intent: a primary-key Index Scan on pk_namespaces under LIMIT 1, 1 / 1 rows. The extra projected column (limit_blocked_at) changes only the row width. No anomalies.

Seed shape: namespaces=5000

Timings: planning 0.204ms, execution 0.016ms, total 0.220ms.

datastore.WriteCondition.LimitBlockedInEffect

Summary: Plan matches the method's intent: a one-row UPDATE keyed by id through pk_namespaces, 1 / 1 rows. The higher buffer count (156) is the first write in the transaction touching the table's heap and indexes; the later writes on the same row hit 8. No anomalies.

Seed shape: namespaces=5000

Timings: planning 0.102ms, execution 0.677ms, total 0.779ms.

datastore.WriteCondition.LimitBlockedLift

Summary: Plan matches the method's intent: a one-row UPDATE that sets limit_blocked_at to NULL, keyed by id through pk_namespaces, 1 / 1 rows. No anomalies.

Seed shape: namespaces=5000

Timings: planning 0.077ms, execution 0.186ms, total 0.263ms.

testutil.ClearNamespaceLifecycle.limit_blocked

Summary: Test fixture statement (internal/testutil/namespace_lifecycle.go), plain SQL with no RETURNING. A one-row UPDATE keyed by id through pk_namespaces. No anomalies.

Seed shape: namespaces=5000

Timings: planning 0.057ms, execution 0.146ms, total 0.203ms.

testutil.SetNamespaceLifecycle.limit_blocked

Summary: Test fixture statement (internal/testutil/namespace_lifecycle.go), plain SQL with no RETURNING. A one-row UPDATE keyed by id through pk_namespaces. No anomalies.

Seed shape: namespaces=5000

Timings: planning 0.059ms, execution 0.159ms, total 0.218ms.

Checklist

  • Ran it: A fresh service was booted from this branch's binary, and the GitLab API was driven with a service token. The limit block was applied, replayed and lifted, and a suspension showed the status precedence. The billing anchor was read back from the resolution response. A write to a limit-blocked namespace answered 403 with the current suspended message, and its read answered 200. The smoke suite of the service driver then passed 103 checks with no failure.
  • Interfaces and data: The GitLab API gains two routes and two fields on the namespace resource. The OpenAPI document of the management API gains four error codes. The namespaces table gains one nullable column. Existing clients keep working, because the new column is nullable with no default and the two new response fields are additive. The four codes are new values in the error-code enum. The spec docs/specs/S33-gitlab-api.md covers all of this.
  • Failure: The two new routes answer the same envelope as the six existing condition routes. They answer 400 for a malformed body, 401 without a service token, and 404 for an unknown namespace. They answer 413 for a body over the size cap and 500 for an internal error. An action segment outside the eight literals matches no route and answers 404. A write to a limit-blocked namespace answers 403 with the current suspended message, because the gates are held for issue #1790.
  • Rollout: The migration is additive, so the previous release runs against the new schema without a change. A replica of the previous release reads a limit-blocked namespace as active. It still serves the writes of that namespace, because the old write predicate reads five columns. A rolling deploy therefore keeps a replica that does not know the limit block until the new release reaches it. After a rollback of the binary only, limit-blocked rows read as active and their writes are served until the roll-forward. The down migration drops the column and with it every limit block, so do not run it while any row has limit_blocked_at set.
  • Hot path: No new query runs on a request path. The namespace projection gains one column, so each namespace read carries one more value. The two new routes reuse the same write statement as the existing condition routes.
  • Database: Yes. One migration adds a nullable timestamptz column named limit_blocked_at to namespaces, with no default and no index. The down migration drops it. The namespace queries gain the column in their projection, so the status and the predicates read it.
  • Security: Two routes are added. They are registered by the same loop as the six existing condition routes, so they sit under the same service token. The service-token middleware admits the caller, and the Kubernetes peer rule refuses these two routes. The action segment is a literal, so a segment outside the action list matches no route and answers 404. No new permission and no audited action are added.
  • ADRs: ADR-009 (API design) and ADR-022 (namespace decoupling) govern this change, and it holds their constraints. The status stays derived from the lifecycle columns, and the billing anchor rides on the resource as an additive field. Other decision records for this area are internal. Their text stays in the internal handbook, so this description names none of them.
  • E2E: No scenario row changes. The catalogs in docs/testing/e2e/ cover client journeys against the management API and the format protocols. This change adds a service-side namespace state, its two routes and its storage column. The client-visible refusals, the condition gates, are held for issue #1790, so no journey changes.
  • Simplicity: The change rejects a shared column for suspended and limit_blocked, because the two states carry different client reasons. It also rejects a stored status column, because the status stays derived from the lifecycle columns. Each condition keeps its own column, as the three existing conditions do.

Reviewable lines of code (LOC) at head 3e2e0c87: api/ 179, docs/ 8, internal/auth/ 2, internal/datastore/ 507, internal/gitlabapi/ 315, internal/lifecycle/ 52, internal/managementapi/ and internal/namespace/ 26, internal/testutil/ 8, internal/transport/ 84, total 1181.

Merge order

  • This MR is part 1 of 2. !4102 (merged) holds the limit-blocked test of the management API, moved out to keep this MR under the 1,000-line Go limit, and merges after it.
  • The migration is re-stamped to 20261112221200 so it sorts after the latest migration on main; its content and the timings above are unchanged.
  • The author's decision holds the condition gates and the surfaces that answer the four reason codes for issue #1790. Until they ship, a write to a limit-blocked namespace answers the current suspended message. No namespace_limit_blocked code is emitted yet.
  • The author's decision leaves the namespace soft-delete and hard-delete endpoints out of this cycle. They wait for !3964 (merged) and an S33 amendment.
  • The re-anchor endpoint is out of scope for this issue (issue #1666).
  • BillingServiceable has no production caller yet. The spec puts it in internal/datastore/namespace_state.go for S24 (usage metering) to call, in the serviceability gating section of S33.
  • Merge request !3637 docs(administration): publish the self-managed install and limitations pages copies row 11 of the self-managed limitations register into docs/administration/limitations.md. Whichever of the two merge requests merges second carries the reword of that row.

Related to https://gitlab.com/gitlab-org/ops/artifact-registry/-/work_items/1823

This merge request leaves the condition gates and the surfaces that answer the four reason codes to #1823 Part 2, after the Rails mapping in #2017. It also leaves the namespace soft-delete and hard-delete endpoints out of this cycle, so issue #1823 stays open.

Edited by Pawel Rozlach

Merge request reports

Loading
Loading