Skip to content

chore: webhook reasons - #7294

Merged
fracasula merged 3 commits into
masterfrom
refactor/typed-stat-reason
Aug 25, 2026
Merged

fracasula merged 3 commits into
masterfrom
refactor/typed-stat-reason

Conversation

@fracasula

@fracasula fracasula commented Aug 20, 2026 •

Copy link
Copy Markdown
Collaborator

Companion PRs

What

gwTypes.StatReporter reported the reason a request failed as a plain string, and reported a drop with no reason at all. Both now carry a gwtypes.StatReason: a sealed interface over a closed set of declared values, which a consumer can switch over exhaustively instead of matching on message text.

Why

StatReporter is the seam another service implements to receive the outcome of a request this gateway handled — rudder-ingestion-svc runs the webhook package in-process and implements it. A string reason forces that implementer to match on message text, which breaks silently the moment a message is reworded. RequestDropped() was worse: it reported the fact of a drop and nothing else, so a consumer could not tell a rate limit from anything else, and could not alert on a source losing data to its limit.

The reason values also become Prometheus labels, and three call sites fed a raw err.Error() straight into one — unbounded cardinality on gateway.write_key_failed_requests.

The type

gateway/types/reason.go declares StatReason, sealed by an unexported protected() method. A caller outside the package can hold a reason and read its Value(), but cannot bring a new one into existence, so the set is closed by the compiler rather than by convention.

Every reason is built through an unexported newReason, which registers it in two indexes. Reasons() returns the whole set, so a consumer can assert in its own tests that it still handles all of them — a reason added here then surfaces there as a failing test rather than as an unattributed series in production. rudder-ingestion-svc's companion PR does exactly that, and it caught four unmapped reasons during this work.

StatReasonForMessage resolves one of this gateway's own error messages back to the reason declared for it. Several internal errors are built as errors.New(response.X), so the message is already the bounded identifier; this maps it back to the declared value rather than letting the message reach a label. It reports false for anything else, which the caller reports under a catch-all and logs.

Changes

RequestFailed and RequestDropped take a StatReason. SourceStat follows, along with RequestEventsFailed and EventsFailed, since they share the same reason field.

Drops now carry their own reason in a field separate from the failure reason. One SourceStat is reused across every request for a source tag within a batch, so a batch containing both a drop and a failure would otherwise have one clobber the other.

auth.NewWebhookAuth's onFailure callback gains a StatReason parameter. The existing errorMessage stays: it is the wire message the caller sees, which is a different thing from the reason reported on a metric, and conflating the two is what made a single string look sufficient. handleFailureStats likewise takes the reason from its caller instead of re-deriving it from the message; its remaining switch only picks the stat's shape.

The webhook package reports its own errors on webhook_num_errors, and that reason was a string too, with three callers passing err.Error() and the rest passing ad-hoc literals. countWebhookErrors and recordWebhookErrors now take a StatReason, and the batch transformer carries the reason beside the error as it builds it rather than reading it back off the message afterwards. failRequest and markResponseFail keep their string parameter, since that one is the message shown to the caller, but it is renamed from reason to errorMessage so the two are not confused again.

The three err.Error() sites on SourceStat are handled by what each one actually carries. getJobDataFromRequest's error path and the message validator's both resolve through StatReasonForMessage, falling back to ReasonRequestProcessingFailed and ReasonValidationFailed and logging the error when they cannot. The marshalling site has no bounded message at all and reports ReasonMarshalEventBatchFailed, with the error logged as it already was.

Metric impact

Every reason's Value() matches the string its site reported before, so existing series keep their values — with these exceptions.

gateway.write_key_dropped_requests gains a reason label. Adding a label is additive, so sum by(...) queries are unaffected, but the series now split by reason.

The marshalling site reports marshalling event batch failed instead of the marshal error's text, and the validator site reports validation failed for any message not declared here. Both were unbounded before, which is the cardinality fix; a stable query against either is unlikely to have existed.

On webhook_num_errors, the three sites that reported a raw error now report source transformer adapter, source transformer url and one of the declared build reasons — again replacing unbounded text. The literal reasons those sites already used keep their values (in out mismatch, batch response error, marshal error, enqueueInGateway failed). One value does change deliberately: a payload the gateway refused for rate limiting reported the wire message max requests limit reached and now reports rate limit, so a rate limit reads the same on every metric that names one.

Two pairs of reasons describe the same condition with different strings, because the sites reporting them always did: invalid write key / invalidWriteKey, and failed to read writekey from query params / NoWriteKeyInQueryParams. They are kept distinct so existing series keep their values, and flagged in the code as worth collapsing in a change that is allowed to move them.

Compatibility

This is a compile-time break for anything implementing StatReporter, which is the intended safety net: an implementer cannot bump this dependency and silently keep reporting nothing. There are no gomock mocks of the interface to regenerate. Inside this repo the only implementer is gateway/internal/stats.SourceStat; outside it, rudder-ingestion-svc, whose companion PR lands with this one.

Verification

go vet ./... clean. go test ./gateway/... passes, including the full ./gateway/ ginkgo suite. golangci-lint reports 0 issues and actionlint is clean. The verify.yml gates pass: go mod tidy leaves go.mod unchanged, make mocks produces no diff, and make fmt touches only the files in this PR.

Linear Ticket

< Fixes PIPE-3310 >

Security

  • The code changed/added as part of this pull request won't create any security issues with how the software is being used.

@codecov

codecov Bot commented Aug 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 71.66667% with 34 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.09%. Comparing base (f2655fb) to head (5af3421).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
gateway/webhook/webhook.go 47.22% 19 Missing ⚠️
gateway/handle.go 60.86% 8 Missing and 1 partial ⚠️
gateway/webhook/webhookTransformer.go 0.00% 3 Missing ⚠️
gateway/handle_lifecycle.go 0.00% 1 Missing and 1 partial ⚠️
gateway/types/reason.go 91.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #7294      +/-   ##
==========================================
- Coverage   80.12%   80.09%   -0.03%     
==========================================
  Files         601      602       +1     
  Lines       67217    67246      +29     
==========================================
+ Hits        53857    53863       +6     
- Misses      10184    10197      +13     
- Partials     3176     3186      +10     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@fracasula
fracasula marked this pull request as ready for review August 20, 2026 17:03
@fracasula
fracasula merged commit c298d59 into master Aug 25, 2026
117 of 119 checks passed
@fracasula
fracasula deleted the refactor/typed-stat-reason branch August 25, 2026 07:38
mihir20 pushed a commit that referenced this pull request Aug 31, 2026
# Companion PRs

* `rudder-ingestion-svc` on `refactor/gateway-request-metrics`
* This PR merges first: ingestion-svc cannot build against it until it
is tagged.
  * rudderlabs/rudder-ingestion-svc#693
* `rudderstack-operator` on `refactor/ingestion-svc-request-metrics`
  * rudderlabs/rudderstack-operator#1617

## What

`gwTypes.StatReporter` reported the reason a request failed as a plain
`string`, and reported a drop with no reason at all. Both now carry a
`gwtypes.StatReason`: a sealed interface over a closed set of declared
values, which a consumer can switch over exhaustively instead of
matching on message text.

## Why

`StatReporter` is the seam another service implements to receive the
outcome of a request this gateway handled — rudder-ingestion-svc runs
the webhook package in-process and implements it. A `string` reason
forces that implementer to match on message text, which breaks silently
the moment a message is reworded. `RequestDropped()` was worse: it
reported the fact of a drop and nothing else, so a consumer could not
tell a rate limit from anything else, and could not alert on a source
losing data to its limit.

The reason values also become Prometheus labels, and three call sites
fed a raw `err.Error()` straight into one — unbounded cardinality on
`gateway.write_key_failed_requests`.

## The type

`gateway/types/reason.go` declares `StatReason`, sealed by an unexported
`protected()` method. A caller outside the package can hold a reason and
read its `Value()`, but cannot bring a new one into existence, so the
set is closed by the compiler rather than by convention.

Every reason is built through an unexported `newReason`, which registers
it in two indexes. `Reasons()` returns the whole set, so a consumer can
assert in its own tests that it still handles all of them — a reason
added here then surfaces there as a failing test rather than as an
unattributed series in production. rudder-ingestion-svc's companion PR
does exactly that, and it caught four unmapped reasons during this work.

`StatReasonForMessage` resolves one of this gateway's own error messages
back to the reason declared for it. Several internal errors are built as
`errors.New(response.X)`, so the message is already the bounded
identifier; this maps it back to the declared value rather than letting
the message reach a label. It reports false for anything else, which the
caller reports under a catch-all and logs.

## Changes

`RequestFailed` and `RequestDropped` take a `StatReason`. `SourceStat`
follows, along with `RequestEventsFailed` and `EventsFailed`, since they
share the same reason field.

Drops now carry their own reason in a field separate from the failure
reason. One `SourceStat` is reused across every request for a source tag
within a batch, so a batch containing both a drop and a failure would
otherwise have one clobber the other.

`auth.NewWebhookAuth`'s `onFailure` callback gains a `StatReason`
parameter. The existing `errorMessage` stays: it is the wire message the
caller sees, which is a different thing from the reason reported on a
metric, and conflating the two is what made a single string look
sufficient. `handleFailureStats` likewise takes the reason from its
caller instead of re-deriving it from the message; its remaining switch
only picks the stat's shape.

The webhook package reports its own errors on `webhook_num_errors`, and
that reason was a string too, with three callers passing `err.Error()`
and the rest passing ad-hoc literals. `countWebhookErrors` and
`recordWebhookErrors` now take a `StatReason`, and the batch transformer
carries the reason beside the error as it builds it rather than reading
it back off the message afterwards. `failRequest` and `markResponseFail`
keep their string parameter, since that one is the message shown to the
caller, but it is renamed from `reason` to `errorMessage` so the two are
not confused again.

The three `err.Error()` sites on `SourceStat` are handled by what each
one actually carries. `getJobDataFromRequest`'s error path and the
message validator's both resolve through `StatReasonForMessage`, falling
back to `ReasonRequestProcessingFailed` and `ReasonValidationFailed` and
logging the error when they cannot. The marshalling site has no bounded
message at all and reports `ReasonMarshalEventBatchFailed`, with the
error logged as it already was.

## Metric impact

Every reason's `Value()` matches the string its site reported before, so
existing series keep their values — with these exceptions.

`gateway.write_key_dropped_requests` gains a `reason` label. Adding a
label is additive, so `sum by(...)` queries are unaffected, but the
series now split by reason.

The marshalling site reports `marshalling event batch failed` instead of
the marshal error's text, and the validator site reports `validation
failed` for any message not declared here. Both were unbounded before,
which is the cardinality fix; a stable query against either is unlikely
to have existed.

On `webhook_num_errors`, the three sites that reported a raw error now
report `source transformer adapter`, `source transformer url` and one of
the declared build reasons — again replacing unbounded text. The literal
reasons those sites already used keep their values (`in out mismatch`,
`batch response error`, `marshal error`, `enqueueInGateway failed`). One
value does change deliberately: a payload the gateway refused for rate
limiting reported the wire message `max requests limit reached` and now
reports `rate limit`, so a rate limit reads the same on every metric
that names one.

Two pairs of reasons describe the same condition with different strings,
because the sites reporting them always did: `invalid write key` /
`invalidWriteKey`, and `failed to read writekey from query params` /
`NoWriteKeyInQueryParams`. They are kept distinct so existing series
keep their values, and flagged in the code as worth collapsing in a
change that is allowed to move them.

## Compatibility

This is a compile-time break for anything implementing `StatReporter`,
which is the intended safety net: an implementer cannot bump this
dependency and silently keep reporting nothing. There are no gomock
mocks of the interface to regenerate. Inside this repo the only
implementer is `gateway/internal/stats.SourceStat`; outside it,
rudder-ingestion-svc, whose companion PR lands with this one.

## Verification

`go vet ./...` clean. `go test ./gateway/...` passes, including the full
`./gateway/` ginkgo suite. `golangci-lint` reports 0 issues and
`actionlint` is clean. The `verify.yml` gates pass: `go mod tidy` leaves
`go.mod` unchanged, `make mocks` produces no diff, and `make fmt`
touches only the files in this PR.

## Linear Ticket

< Fixes
[PIPE-3310](https://linear.app/rudderstack/issue/PIPE-3310/rudder-server-webhook-reasons)
>

## Security

- [x] The code changed/added as part of this pull request won't create
any security issues with how the software is being used.
This was referenced Aug 31, 2026
itsmihir pushed a commit that referenced this pull request Aug 31, 2026
🤖 I have created a release *beep* *boop*
---


##
[1.85.0-rc.1](v1.84.0...v1.85.0-rc.1)
(2026-08-31)


### Features

* backend config v2 resolver with stub mapper
([#7275](#7275))
([267b973](267b973))
* **warehouse:** clickhouse v2 connection and schema
([#7301](#7301))
([2eb1fa6](2eb1fa6))
* **warehouse:** clickhouse v2 ddl operations
([#7302](#7302))
([f2887c5](f2887c5))
* **warehouse:** clickhouse v2 loading
([#7303](#7303))
([3e48618](3e48618))
* **warehouse:** enable the clickhouse v2 driver behind a flag
([#7311](#7311))
([3ce1da5](3ce1da5))


### Bug Fixes

* race conditions while counting initial pending events can cause wrong
counting
([#7292](#7292))
([3efa718](3efa718))
* replay destinations not using the config corresponding to their
connected source type
([#7307](#7307))
([ee7aa93](ee7aa93))
* **router:** abort router-transform on proactive invalid_grant instead
of retrying (INT-6779)
([#7175](#7175))
([4d7348d](4d7348d))
* tracking plan merged config is cached without its event type
([#7314](#7314))
([624dd5c](624dd5c))


### Miscellaneous

* setattr/delattr hardening
([#7291](#7291))
([2855af4](2855af4))
* sync release v1.84.0 to main branch
([#7306](#7306))
([fa102b7](fa102b7))
* webhook reasons
([#7294](#7294))
([c298d59](c298d59))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: rudderstack-github-actions[bot] <236995729+rudderstack-github-actions[bot]@users.noreply.github.com>
itsmihir pushed a commit that referenced this pull request Sep 1, 2026
🤖 I have created a release *beep* *boop*
---


##
[1.85.0](v1.84.0...v1.85.0)
(2026-08-31)


### Features

* backend config v2 resolver with stub mapper
([#7275](#7275))
([267b973](267b973))
* **warehouse:** clickhouse v2 connection and schema
([#7301](#7301))
([2eb1fa6](2eb1fa6))
* **warehouse:** clickhouse v2 ddl operations
([#7302](#7302))
([f2887c5](f2887c5))
* **warehouse:** clickhouse v2 loading
([#7303](#7303))
([3e48618](3e48618))
* **warehouse:** enable the clickhouse v2 driver behind a flag
([#7311](#7311))
([3ce1da5](3ce1da5))


### Bug Fixes

* race conditions while counting initial pending events can cause wrong
counting
([#7292](#7292))
([3efa718](3efa718))
* replay destinations not using the config corresponding to their
connected source type
([#7307](#7307))
([ee7aa93](ee7aa93))
* **router:** abort router-transform on proactive invalid_grant instead
of retrying (INT-6779)
([#7175](#7175))
([4d7348d](4d7348d))
* tracking plan merged config is cached without its event type
([#7314](#7314))
([624dd5c](624dd5c))


### Miscellaneous

* setattr/delattr hardening
([#7291](#7291))
([2855af4](2855af4))
* sync release v1.84.0 to main branch
([#7306](#7306))
([fa102b7](fa102b7))
* webhook reasons
([#7294](#7294))
([c298d59](c298d59))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: rudderstack-github-actions[bot] <236995729+rudderstack-github-actions[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants