Draft: feat(ratelimit): GCRA limiter and test double (S05-B plan: 2/4)

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

What

Step 2 of the S05-B rate-limiting plan: the internal/ratelimit package — a GCRA limiter over go-redis/redis_rate/v10 with namespace keying, per-namespace overrides, mode-resolved decisions (observe/warn/enforce), a 500 ms check budget, and the fail-open error contract — plus ratelimittest.FakeLimiter, the scriptable in-memory NamespaceRateLimiter double for consumer tests.

Telemetry (check counter, denial record, samplers) is Step 3; the rate_limit config block is Step 4. No consumer mounts the limiter here.

New dependency: github.com/go-redis/redis_rate/v10 v10.0.1

Per go-libraries.md:

  • Why: ADR-004 mandates GCRA over Redis for rate limiting. redis_rate is the go-redis ecosystem's GCRA implementation (TAT-based; a refused request is costless, the property S05-B's GCRA section relies on). The Container Registry reference implementation embeds its own gcra.lua, but that script is a token bucket despite the name — it refills and zeroes on refusal — so CR's code is not the GCRA the ADR names; redis_rate is.
  • Fit: works over the repo's pinned redis/go-redis/v9 UniversalClient; reads the Redis server clock via TIME, so client clock skew does not distort the TAT.
  • Version: v10.0.1, the latest v10 the module proxy reports, pinned in the plan so this MR reviews the API the plan read.

Size justification (guardrail 18)

~1,090 reviewable LOC: source ~270 (ratelimit.go, key.go, ratelimittest/fake.go), tests ~2:1, matching the repo's measured ratio for foundation packages (internal/cache/counter shipped 176 source / 478 test). The step stays whole: the only extractable seam, ratelimittest, is the double this package's own tests and the first consumer's arm test both drive, so extracting it would spread one package over two MRs without shrinking either review.

Split by file group: limiter source 168, key grammar 8, test double 52, unit tests 306, integration tests 402, fake tests 56, testutil 35, CI + docs

  • go.mod/go.sum ~66.

Spec coverage

Spec: docs/specs/S05-b-rate-limiting.md Plan: docs/plans/2026-10-05-s05b-rate-limiting.md, Step 2 (internal/ratelimit limiter and test double). Rows naming another step are owned by this plan's other steps; this MR does not cover them.

Acceptance criteria

# Criterion Tests
AC-1 NewRateLimitClient builds the purpose client and returns redis.New's error unwrapped Step 1 (!3206 (merged)).
AC-2 Fail-fast defaults, override replacement, and zero-valued fields keep the default; a check whose client times out books error with the read served; a check against a stalled client returns within the check budget Client-level defaults, replacement, and timeout: Step 1 (!3206 (merged)). Check-level timeout arm: Step 3 (observe_test.go). Check budget: TestLimiter_Check_StalledClientReturnsWithinBudget, TestLimiter_Check_CallerDeadlineWins (unit).
AC-3 The ratelimit, cache, and jobs clients register on one registerer without collision Step 1 (!3206 (merged)).
AC-4 A rested key admits burst requests at once and refuses the next TestLimiter_BurstAdmitsExactlyBurst (integration)
AC-5 Sustained traffic at rate/period is admitted, and admission resumes as the window recovers TestLimiter_SustainedRate_RecoversAfterBurst (integration)
AC-6 A refused request does not advance the key's recovery TestLimiter_RefusalsDoNotAdvanceRecovery (integration)
AC-7 Check resolves each mode into the admission-check decision TestLimiter_ModeDecisionTable (integration, one arm per mode); TestResolveDecision (unit, including the unknown-Mode fallback)
AC-8 The check counter books success/denied/error exactly once per check Step 3 (observe_test.go).
AC-9 A Redis error, a check timeout, or uuid.Nil books error, logs, and the read is served; no 500 Step 3 (the booking and the capped log). This MR supplies the guard: TestLimiter_Check_NilNamespace returns ErrNilNamespace without reaching Redis, and both budget arms return an error and no decision.
AC-10 Standalone, Sentinel, and Cluster The package's enrollment in .redis-integration-base (.gitlab-ci.yml, same commit) runs ratelimit_integration_test.go on the three-topology matrix.
AC-11 Keys match rate:ar:ratelimit:namespace:<namespace-uuid>, one isolated cell per namespace TestLimiter_KeyGrammar (integration, including a second arm drawing on the same cell); TestNamespaceKey (unit)
AC-12 ratelimittest.FakeLimiter replays its scripted verdicts without Redis TestFakeLimiter_ReplaysScriptedVerdicts, TestFakeLimiter_LimitReturnsConfiguredLimit, TestNewFakeLimiter_PanicsWithoutVerdicts (unit)
AC-13 A namespace_overrides entry replaces rate/burst for its namespace; a namespace with no entry uses the base values TestLimiter_LimitFor (unit: override, no-entry, and no-overrides arms)
AC-14 An omitted mode converts to observe, and the loader rejects a period below one second Step 4 (internal/config/ratelimit_test.go).
AC-15 Denial-record fields, and the 64-bucket sampler caps the record and the failed-check log Step 3 (observe_test.go).

Error cases

# Condition Tests
E-1 No redis stanza in the infrastructure config Step 1 (!3206 (merged)).
E-2 Redis unreachable or a check times out TestLimiter_Check_StalledClientReturnsWithinBudget, TestLimiter_Check_CallerDeadlineWins (unit) bound the check and return an error with no decision, so the caller serves. The error booking, the capped log, and the served read: Step 3.
E-3 Namespace id is uuid.Nil TestLimiter_Check_NilNamespace (unit: returns ErrNilNamespace and never calls Redis). The error booking: Step 3.
E-4 Malformed limit at construction TestNew_Validation (non-positive rate, period, burst), TestNew_NilClient (unit panic backstops)
E-5 period below one second Step 4 (loader).
E-6 Namespace override key is not a UUID Step 4 (protovalidate map-key rule).
E-7 mode omitted or empty Step 4 (conversion selects observe).
E-8 Redis failover or flush loses limiter cells TestLimiter_FlushedCellReadsAsRested (integration: the lost cell admits one fresh burst, once)

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 Dependency-owned (LabKit redis.WithInfraConfig); this MR adds no credential handling.
S-2 The limiter key uses the namespace UUID resolved by the request, never a caller-controlled header, principal id, or IP address; override keys are UUID-validated before they reach the limiter TestNamespaceKey (unit) and TestLimiter_KeyGrammar (integration) pin the key grammar. The override-key UUID validation is Step 4.
S-3 A refusal reveals only that the namespace's configured rate was reached; metric labels carry neither namespace nor repository id Step 3 (observability). This MR's Result carries a decision and a remaining count, no principal, namespace, or repository value.
S-4 Fail-open degradation is deliberate; a Redis outage does not take down the read path TestLimiter_Check_NilNamespace, TestLimiter_Check_StalledClientReturnsWithinBudget, TestLimiter_Check_CallerDeadlineWins (unit: every error path returns no decision, so the caller serves). The error booking and the capped log: Step 3.

Notes

  • TestLimiter_LimitReturnsConfiguredShape pins the Limit() accessor's round trip; no spec row names it.
  • The two spec amendments above are pinned by tests: TestNew_NilClient for the nil-client panic, TestResolveDecision for the unknown-Mode fallback.

Plan and spec amendments

  • Spec (S05-b-rate-limiting.md): New's contract now names the nil-client panic (the code has always had it; the spec named only non-positive rate/period/burst), and the mode-resolution paragraph records that an unknown Mode resolves as observe — defensive, since the proto in set makes it unreachable through config.
  • Plan: Step 2's Files entry now lists docs/dev/ratelimit.md, the docs/dev/README.md index row this step ships, and the no-ratelimittest-in-prod depguard rule with its negative-control probe and assertion-loop entry; Step 4's Files entry gains the internal/ratelimit/ratelimit.go bullet that flips New's doc comment back to present tense when the loader lands — Step 2 lands it in future tense because the proto validation and loader this stack introduces do not exist yet.

Testing

  • Unit: uuid.Nil guard, override replacement, constructor panic backstops (nil client, non-positive values), mode-decision table, stalled-client check returns within checkBudget, fake replay.
  • Integration (--tags=integration): burst admission, sustained-rate recovery, refusal-no-advance, key grammar, and the per-mode decision table against real Redis on the Standalone/Sentinel/Cluster matrix; the package is enrolled in .redis-integration-base and .changes-redis-ci in the same commit.
  • Integration-tagged lint run locally per guardrail 7: golangci-lint run --build-tags=integration --max-same-issues=0 --max-issues-per-linter=0 --uniq-by-line=false ./internal/ratelimit/... — clean.

e2e and user docs

  • e2e (guardrail 12): no scenario added — this increment mounts no consumer, so no externally observable behavior changes; the 429 rows belong to the mount in #1181's plan.
  • docs/user/** (guardrail 24): unaffected — every surface here is inert until #1181's mount; no request is refused, warned, or headered, and the published Rate limits sentence ("Limits are configured and measured, but requests are not blocked") stands unchanged.

Related to #1181

Edited by Moaz Khalifa

Merge request reports

Loading
Loading