Draft: feat(ratelimit): book check outcomes and emit sampled records (S05-B plan: 3/4)

On hold: paused while the team evaluates LabKit ratelimit. See #1181 (comment 3996742796).

What

Step 3 of the S05-B rate-limiting plan: the limiter's telemetry. Check now books gitlab_artifact_registry_rate_limit_checks_total exactly once per check (success / denied / error), emits the rate_limit_denied record on every refusal in every mode, and logs check errors through a second sampler of the record's shape, so a Redis outage cannot log once per request. Both samplers hash the namespace UUID into 64 fixed process-local buckets and cap at 64 emissions per second per process; the counter stays exact.

internal/metrics/cardinality.go gains the limiter label with its one permitted value (namespace). The outcome seam already pinned success / denied / error, so it is not widened.

The increment is inert: no consumer mounts the limiter, so no request is refused, warned, or headered, and the metric family stays off /-/metrics until a consumer wires ratelimit.RegisterMetrics. The six-arm mount belongs to #1181's plan.

Stacked MR. This targets mkhalifa/s05b-rate-limiting-step-2 because step 3 builds on the limiter package that !3242 (closed) introduces, and !3242 (closed) is still under review. It will retarget to main when !3242 (closed) merges. The stack is a deliberate departure from development-model.md's "no stacked MR chains", taken to keep step 3 moving while step 2's review lands. Reviewers: read the diff against cfa175f25, not against main, which would pull in !3242 (closed)'s 16 files.

Plan and spec amendments

The step MR carries the corrections its own review proved, per conventions.md.

  1. The ADR-004 rollout order is resolved, not deviated from. The plan's ADR-conformance note recorded one deviation from ADR-004's IP-first rollout sentence, escalated in handbook MR !21345. That MR merged and the local mirror has carried it since its 2026-10-08 sync: the per-namespace class now ships first, with the Maven virtual read path. The plan and spec now record conformance, and the spec's "Key scope, and the ADR-004 order it deviates from" bullet is retitled "Key scope, and the ADR-004 rollout order".
  2. The denial record's emitter stays inline. The spec required "S03's event-specific schema and typed emitter". It now requires the schema and records the typed-emitter half as a deviation — the same one the proxy and resolve events already carry in the observability catalog — because the record ships with the check that emits it. A new spec Resolutions bullet records the decision, and the schema half is pinned by TestCheck_DenialRecordFields.
  3. Step 3's Files: list gains three files the implementation proved it needs: internal/accounting/emit_drop_log.go (the reciprocal "a change to any of the three owes the others a look" cross-reference the ported sampler owes its two in-tree precedents), docs/dev/ratelimit.md (the module quick reference gains observe.go), and internal/ratelimit/ratelimit_test.go (testLimit names the limiter through the package's limiterNamespace constant, so the cardinality audit ties the pin to the constant rather than a literal).

Size

1018 insertions / 29 deletions across 11 files, past the 500-LOC threshold in development-model.md, so here is the split and the justification.

Group LOC Files
Source 231 observe.go 193, ratelimit.go 28, cardinality.go 10
Tests 747 observe_test.go 732, cardinality_test.go 11, ratelimit_test.go 4
Docs 39 observability.md 2, ratelimit.md 2, plan 17, spec 18
Other 1 emit_drop_log.go

The source half is 231 LOC across three files. The size is the test floor at roughly 2:1 test-to-source, the repo's measured ratio for foundation packages (step 2 shipped 176 source / 478 test; internal/cache/counter shipped 176 source / 478 test). Splitting was not taken: the only extractable seam would separate the counter and the record from the Check wiring that books them, which the spec treats as one surface under AC #8 (closed), #9, and #15.

docs/user/ disposition

Not affected, no page added. Every surface this step ships is inert until #1181's mount — nothing a customer can call, see, or configure changes. The one published sentence this increment touches stands unchanged: docs/user/_index.md § Rate limits ("Limits are configured and measured, but requests are not blocked") states the enforcement posture, and this step does not move it. The user-facing rate-limit page lands with the mount's plan.

e2e disposition

No scenario added or affected. This step mounts no consumer, so no externally observable behavior changes; the rows for a served 429 belong to the mount in #1181's plan.

Spec coverage

Spec: docs/specs/S05-b-rate-limiting.md

Step 3 (limiter observability) owns AC #8 (closed), #9, and #15 and closes AC #2's check-level timeout arm. Rows owned by the earlier steps (!3206 (merged) step 1, merged; !3242 (closed) step 2, still open) or by the later step 4 are marked as such.

Acceptance criteria

# Criterion Tests
AC-1 NewRateLimitClient builds the ratelimit client with redis-ratelimit and unwrapped ErrNotConfigured Step 1 (merged !3206 (merged)): TestNewRateLimitClient_MetricName, TestNewRateLimitClient_NotConfigured. Not this MR.
AC-2 Fail-fast defaults, field-by-field override replacement, a timed-out check books error with the read served, and a stalled check returns within the budget Defaults, override replacement, and the client-level timeout arm: Step 1 (merged !3206 (merged)): TestNewRateLimitClient_FailFastDefaults, TestNewRateLimitClient_FailFastOnStalledRedis. Check-level timeout arm (this MR): TestCheck_ErrorArms (stalled fail-fast client subtest), TestCheck_BooksCounterExactlyOncePerOutcome (timeout arm books error). Budget bound: Step 2 (!3242 (closed), open): TestLimiter_Check_StalledClientReturnsWithinBudget.
AC-3 The three purpose clients register on one registerer without collision Step 1 (merged !3206 (merged)): TestJobsCacheAndRateLimitClients_NoRegistrationCollision. Not this MR.
AC-4 A rested key admits burst requests and refuses the next Step 2 (!3242 (closed), open): TestLimiter_BurstAdmitsExactlyBurst. Not this MR.
AC-5 Sustained traffic at rate/period is admitted, above it refused, admission resumes Step 2 (!3242 (closed), open): TestLimiter_SustainedRate_RecoversAfterBurst. Not this MR.
AC-6 A refused request does not advance recovery Step 2 (!3242 (closed), open): TestLimiter_RefusalsDoNotAdvanceRecovery. Not this MR.
AC-7 Check resolves each mode into its decision Step 2 (!3242 (closed), open): TestLimiter_ModeDecisionTable. This MR re-drives the refusal side per mode through TestCheck_BooksCounterExactlyOncePerOutcome and TestCheck_DenialRecord_OnEveryRefusalInEveryMode.
AC-8 The check counter books success, denied, and error exactly once per check TestCheck_BooksCounterExactlyOncePerOutcome
AC-9 On a Redis error, a check timeout, or uuid.Nil the check books error, logs, and the read is served; no error path answers 500 TestCheck_ErrorArms (all three arms), TestCheck_BooksCounterExactlyOncePerOutcome (the three arms book error). No consumer mounts the check in this increment, so "the read is served"/"no 500" is the limiter's fail-open contract (require.Zero on every error arm) and the mount's own behavior lands with #1181.
AC-10 Standalone, Sentinel, and Cluster Step 2 (!3242 (closed), open), three-topology matrix. Not this MR.
AC-11 Keys match rate:ar:ratelimit:namespace:<namespace-uuid> Step 2 (!3242 (closed), open): TestLimiter_KeyGrammar. Not this MR.
AC-12 ratelimittest.FakeLimiter replays scripted verdicts without Redis Step 2 (!3242 (closed), open): TestFakeLimiter_ReplaysScriptedVerdicts. Not this MR.
AC-13 A namespace_overrides entry replaces rate and burst for its namespace only Step 2 (!3242 (closed), open): TestLimiter_LimitFor. Not this MR.
AC-14 An omitted mode converts to observe; the loader rejects a sub-second period Step 4. Not this MR.
AC-15 The denial record's fields; the 64-bucket sampler caps the record; a second sampler caps the failed-check log TestCheck_DenialRecordFields, TestCheck_DenialRecord_OnEveryRefusalInEveryMode, TestSampler_Allow, TestBucketIndex_IsStableAndCoversEveryBucket, TestCheck_DenialRecordCapsAt64PerSecond, TestCheck_FailedCheckLogCapsAt64PerSecond, TestRegisterMetrics_PassesTheCardinalityAudit; the cardinality-table pin: TestClosedSetValues_PinTheRateLimiterVocabulary (internal/metrics).

Error cases

# Condition Tests
E-1 No redis stanza in the infrastructure config Step 1 (merged !3206 (merged)): TestNewRateLimitClient_NotConfigured. Not this MR.
E-2 Redis unreachable or a check times out: books error within the budget, logs through the capped failed-check log, read served TestCheck_ErrorArms (Redis-failure and stalled-client arms), TestCheck_FailedCheckLogCapsAt64PerSecond (the cap)
E-3 Namespace id is uuid.Nil: books error without calling Redis, read served TestCheck_ErrorArms (nil-namespace arm), TestCheck_BooksCounterExactlyOncePerOutcome
E-4 Malformed limit at construction: New panics Step 2 (!3242 (closed), open): TestNew_Validation, TestNew_NilClient. Not this MR.
E-5 period below one second: the loader rejects it Step 4. Not this MR.
E-6 Namespace override key is not a UUID: protovalidate rejects it Step 4. Not this MR.
E-7 mode omitted or empty: observe; out-of-set value rejected at load Step 4. Not this MR.
E-8 Redis failover or flush loses cells: reads as rested Step 2 (!3242 (closed), open): TestLimiter_FlushedCellReadsAsRested. Not this MR.

Security considerations

# Concern Tests
S-1 Credentials and TLS come from the deployment-managed secret mounts through LabKit's infrastructure config; no new credential surface Step 1 (merged !3206 (merged)) / LabKit-owned. Not this MR.
S-2 The limiter key uses the resolved namespace UUID, not a caller-controlled header, principal, or IP; override keys are UUID-validated Step 2 (!3242 (closed), open): TestNamespaceKey, TestLimiter_KeyGrammar; override-key validation: Step 4. Not this MR.
S-3 A refusal reveals only the reached rate: the denial record carries namespace/repository ids, and metric labels carry neither TestCheck_DenialRecordFields (ids ride the record), TestRegisterMetrics_PassesTheCardinalityAudit (the counter's only labels are limiter/outcome; namespace_id stays on internal/metrics' disallowed-label list)
S-4 Fail-open degradation: a Redis outage does not take down the read path TestCheck_ErrorArms (every arm returns no verdict, so the caller serves)

Remaining on the linked issue

#149 covers all four steps of this plan, so this MR is Related to rather than Closes. Remaining after this one: step 2 (!3242 (closed), open) and step 4 (!3230 (merged), open). Step 1 (!3206 (merged)) is merged.

Related to #149

Edited by Moaz Khalifa

Merge request reports

Loading
Loading