Skip to content

Commit 33ddf2a

Browse files
Tomelia1999claude
andcommitted
fix(relaycore): a timeout next to a refused connection is always the 504; pin the new statuses in relay_end (MAG-4481)
A refused connection and a timeout both ranked as "no upstream answered", so the majority pick broke the one-to-one tie at random: the same failure came back 502 on about 33 runs in 40 and 504 on the rest. A timeout now ranks above the other transport failures, and both still lose to any other error. relay_end gains golden cases for the statuses this PR introduced: a node's 503 forwarded, every attempt throttled (429) and a node that never answers (504). Notes brought up to date: relay_end's has_reply and no_answer rows (an upstream's error status is a no_answer with that status), the fully capped chain in RATE-LIMIT-HOLDOFF (the node's 429, no longer a router 503), the REST 5xx section of ERROR-REGISTRY-DESIGN, and the 504 timeout, which names the request's budget rather than the time the attempt took. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 079ffb0 commit 33ddf2a

11 files changed

Lines changed: 204 additions & 12 deletions

‎docs/ERROR-REGISTRY-DESIGN.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -733,7 +733,8 @@ router-made 500. It now skips a 5xx whose body is JSON and whose status the regi
733733
`MayHaveReachedNode` (`rpcInterfaceMessages.ServerErrorIsNodeReply`). `502`/`504`/`522`/`524` keep
734734
the old path: a gateway that failed may already have forwarded the request, so a write's outcome
735735
stays "unclear". Blame and retry are unchanged by this step — the status rows above still decide
736-
them.
736+
them. Since MAG-4481 a read that fails on that old path still reaches the client as the node's own
737+
status and body; only a write whose outcome is unclear gets the router's 500.
737738
738739
### 9.3 Decisions taken in review
739740

‎docs/RATE-LIMIT-HOLDOFF.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,11 @@ another registry, and tests use `NewRegistry` or the jitter-free `NewRegistryWit
5757
batch reply is one node error even when some of its elements executed
5858
(`--batch-node-error-on-any`), so only a refusal of the whole batch at the transport (HTTP
5959
429) lets a batch carrying a write be sent again.
60-
- **A fully capped chain answers 503.** When every attempt was refused for rate, the
61-
client gets 503 Service Unavailable — temporarily unservable, not broken — with no
62-
Retry-After (that stays internal). Any other failure mix keeps its usual shape.
60+
- **A fully capped chain answers with the node's own 429.** When every attempt was refused
61+
for rate, the client gets the upstream's 429 and its body as is, as for any other answer a
62+
node gave (MAG-4481; it was a router-made 503 before). The node's Retry-After is not passed
63+
on (that stays internal). Next to another upstream's error status the other status wins: a
64+
503 beside two 429s is the 503.
6365
- **What counts as a 429.** An HTTP 429 status on any transport, a WebSocket upgrade the
6466
upstream rejected with 429, a gRPC status whose text names a rate limit (or
6567
RESOURCE_EXHAUSTED with a retry delay), and a JSON-RPC error body with code 429 or a

‎docs/RELAY-END-EVENT.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ the router (an HTTP 405, for one); the router's own health and probe relays.
6161
| `stop_reason` | string | always | Why there was no further attempt: `Success`, `Stateful`, `CrossValidation`, `NonRetryableNodeError`, `PermanentProtocolError`, `UnlistedMethodRefused`, `MaxRetriesReached`, `BatchDisabled`, `ErrorToleranceExceeded`, `AllProvidersExhausted`, `FirstMessageFailed`, `BatchSendFailed`, `ProcessingTimeout` (the budget ran out), `CallerGone` (a WebSocket or gRPC client hung up), `CrossValidationGroupsQuiet`. `""` when the relay ended before its state machine named a reason: `selection` is `""`, the cross-validation capacity check refused the request, or a `router_error` stopped it; always `""` for a subscription request. |
6262
| `served_by` | string | always | The upstream whose reply reached the client; `"Cached"` for a cache hit, as the provider-address reply header says. For a subscription request, the upstream its subscription lives on. `""` when the client got an error, and for a subscription request the router answered itself. |
6363
| `status` | number | always | The HTTP status on the router's result. When every attempt failed with a protocol error, it is the status the client gets: the upstream's own status when an upstream answered (a `429` included), `504` when no upstream answered in time (a connect timeout, the request's deadline, or a hung upstream that never answered), and `502` when every attempt failed in transport otherwise (MAG-4218, MAG-4481). `0` when the router returned no result or one without a status; the listener then answers with its own status. A router built with masked errors answers a no-answer failure with `500` while this field keeps `502` or `504`. A `write_unknown` is always `500`, the status the client gets. `0` for a subscription request. |
64-
| `has_reply` | boolean | always | `true` exactly when `outcome` is `ok` or `node_error`: the client got an upstream's or the cache's reply, or, to a subscription request, the router's own answer. |
64+
| `has_reply` | boolean | always | `true` exactly when `outcome` is `ok` or `node_error`: the client got an upstream's or the cache's reply, or, to a subscription request, the router's own answer. `false` on a `no_answer` whose client was sent an upstream's error status and body as is (a `503`, a `429`): the relay failed, and `status` is that upstream's status (MAG-4481). |
6565
| `error_code` | string | always | The error registry name (`protocol/common/error_codes.go`) of why the relay did not end `ok`; see [error_code](#error_code). `""` on `ok`. |
6666
| `error` | string | always | `node_error`: the node's error message. `write_unknown`: the message the client gets ("transaction status unclear: …"). Any other failure: the error the relay ended with. `""` on `ok`. |
6767
| `latency_ms` | number | always | Milliseconds from the router taking the request to the event. A request that parses is timed from `SendParsedRelay` (the parse is not counted); one that does not, from `SendRelay`; a WebSocket frame that does not parse, from its parse. |
@@ -117,7 +117,7 @@ On Cosmos the fields are read, as `tx_code` is, only on a write the spec marks s
117117
| `ok` | An upstream's or the cache's reply that is not a node error | `SendParsedRelay` returns a reply and no error: the first success (stateless, stateful), the quorum winner (cross-validation), or a cache hit |
118118
| `node_error` | A node's error reply, passed through | `SendParsedRelay` returns a node error with no error: `processNonCrossValidationResult` when nothing succeeded, or a cached node error. A node's rate-limit reply is one too. |
119119
| `write_unknown` | "transaction status unclear", HTTP 500 | `SendParsedRelay` returns `errUnknownWriteOutcome` (`writeOutcomeIsUnknown`): a stateful relay where no upstream accepted, and one was still silent when the budget ran out or its connection died after the request went out |
120-
| `no_answer` | An error, after at least one upstream was asked | `SendParsedRelay` returns an error with a dispatched attempt: every attempt failed in transport, timed out or was rate limited, or cross-validation found no quorum |
120+
| `no_answer` | An error, after at least one upstream was asked | `SendParsedRelay` returns an error with a dispatched attempt: every attempt failed in transport, timed out, was rate limited or answered an HTTP error status, or cross-validation found no quorum. When an upstream answered, the client gets its status and body as is, and `status` says which (MAG-4481) |
121121
| `rejected_before_dispatch` | An error; no upstream was asked | `SendRelay` or the WebSocket manager: the request does not parse (unsupported shape, refused batch). `SendParsedRelay` with nothing dispatched: invalid cross-validation headers, the cross-validation capacity check, an empty provider pool, an unavailable pinned provider (the select-provider directive), every endpoint failing consistency pre-validation, or the deadline expiring before dispatch |
122122
| `router_error` | An error, or nothing usable | The router's own machinery failed (`routerFault`): its task loop could not start, the task channel closed without a final instruction, or a relay had no request data. Also `SendParsedRelay` returning neither a reply nor an error, which includes a panic inside it |
123123

‎protocol/common/client_facing_error.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ type ClientFacingError struct {
1616
// TimedOut marks a no-answer that is a timeout: the reply is 504 and names Timeout.
1717
TimedOut bool
1818
// Timeout is the request's processing timeout, filled by the router once the relay has ended.
19+
// It is the budget the request had, not how long the failed attempt took.
1920
Timeout time.Duration
2021
RouterErrorCode uint32 // the registry classification, as metadata
2122
RouterErrorName string

‎protocol/relaycore/client_facing_error.go‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,9 @@ func NoAnswerStatus(cf *common.ClientFacingError) int {
6464

6565
// replyProtocolError chooses the error the client's reply is built from (MAG-4218). An upstream's
6666
// answer beats any other error, a fault beats a throttle (a 503 next to two 429s is the 503), and
67-
// a transport failure is used only when every attempt failed in transport. Within a rank the
67+
// a transport failure is used only when every attempt failed in transport. Among transport
68+
// failures a timeout wins, so a refused connection next to a timeout is always the 504, never a
69+
// 502 on some runs: the majority pick breaks a tie at random (MAG-4481). Within a rank the
6870
// majority pick stands; a higher rank takes the first such error.
6971
func replyProtocolError(picked RelayError, all []RelayError) RelayError {
7072
best, bestRank := picked, replyRank(picked)
@@ -80,16 +82,18 @@ func replyRank(relayError RelayError) int {
8082
cf := clientFacingFromProtocolError(relayError.Err, relayError.LavaError)
8183
switch {
8284
case cf == nil:
83-
return 1 // today's reply
85+
return 2 // today's reply
8486
case cf.UpstreamStatus == http.StatusTooManyRequests:
8587
// The upstream answered, but only to say it is throttling us. Before MAG-4481 a 429
8688
// carried no body and ranked as today's reply, so another upstream's fault won; keeping
8789
// the body must not change that.
88-
return 2
90+
return 3
8991
case cf.UpstreamStatus != 0:
90-
return 3 // the upstream answered
92+
return 4 // the upstream answered
93+
case cf.TimedOut:
94+
return 1 // no upstream answered in time: 504
9195
default:
92-
return 0 // no upstream answered
96+
return 0 // no upstream answered: 502
9397
}
9498
}
9599

‎protocol/relaycore/client_facing_error_test.go‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,46 @@ func TestReplyProtocolError_TransportFailureIsTheLastResort(t *testing.T) {
310310
require.Equal(t, refused.Err, replyProtocolError(refused, []RelayError{refused, refused}).Err)
311311
}
312312

313+
// timeoutErr is a dial or request that ran out of time: no upstream answered, and the reply is 504.
314+
func timeoutErr() error {
315+
return common.NewLavaErrorWrapping(common.LavaErrorContextDeadline, fmt.Errorf("http request failed: %w", context.DeadlineExceeded))
316+
}
317+
318+
// A refused connection next to a timeout is a one-to-one tie between two no-answers, which the
319+
// majority pick breaks at random. The timeout wins, so the client gets 504 on every run, whichever
320+
// arrives first. Before the fix this gave 502 on about 33 runs in 40 and 504 on the rest.
321+
func TestProcessingResult_ATimeoutBeatsARefusedConnection(t *testing.T) {
322+
for _, timeoutFirst := range []bool{true, false} {
323+
timeoutDelay, refusedDelay := time.Millisecond, 2*time.Millisecond
324+
if !timeoutFirst {
325+
timeoutDelay, refusedDelay = refusedDelay, timeoutDelay
326+
}
327+
for i := 0; i < 40; i++ {
328+
rp, _, closer := newTwoProviderProcessor(t)
329+
go SendProtocolError(rp, "lava@a", refusedDelay, refusedErr())
330+
go SendProtocolError(rp, "lava@b", timeoutDelay, timeoutErr())
331+
waitForBoth(t, rp)
332+
333+
result, err := rp.ProcessingResult()
334+
closer()
335+
require.Error(t, err)
336+
require.Equal(t, http.StatusGatewayTimeout, result.StatusCode, "timeout first: %v, run %d", timeoutFirst, i)
337+
require.True(t, result.GetClientFacing().TimedOut)
338+
}
339+
}
340+
}
341+
342+
// Among the no-answers a timeout ranks first, and both still lose to any other error.
343+
func TestReplyProtocolError_ATimeoutBeatsOtherTransportFailures(t *testing.T) {
344+
refused := RelayError{Err: refusedErr(), LavaError: common.LavaErrorConnectionRefused}
345+
timedOut := RelayError{Err: timeoutErr(), LavaError: common.LavaErrorContextDeadline}
346+
other := RelayError{Err: errors.New("no providers"), LavaError: common.LavaErrorNoProviders}
347+
348+
require.Equal(t, timedOut.Err, replyProtocolError(refused, []RelayError{refused, refused, timedOut}).Err)
349+
require.Equal(t, timedOut.Err, replyProtocolError(timedOut, []RelayError{timedOut, refused}).Err)
350+
require.Equal(t, other.Err, replyProtocolError(timedOut, []RelayError{timedOut, other}).Err)
351+
}
352+
313353
func upstream429RelayError(body string) RelayError {
314354
return RelayError{
315355
Err: common.NewLavaErrorWrapping(common.LavaErrorNodeRateLimited, &lavasession.HTTPStatusError{StatusCode: http.StatusTooManyRequests, Body: []byte(body)}),

‎protocol/rpcsmartrouter/relay_end_test.go‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,8 @@ const (
279279
relayEndTxHash = `{"jsonrpc":"2.0","id":1,"result":"0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060"}`
280280
relayEndReverted = `{"jsonrpc":"2.0","id":1,"error":{"code":3,"message":"execution reverted"}}`
281281
relayEndNonceLow = `{"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"nonce too low: next nonce 7, tx nonce 6"}}`
282+
relayEndNodeDown = `{"jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"node is down"}}`
283+
relayEndThrottled = `{"jsonrpc":"2.0","id":1,"error":{"code":429,"message":"Too many requests"}}`
282284
relayEndShortWait = 5 * time.Second
283285
)
284286

@@ -392,6 +394,43 @@ func TestRelayEnd_ExitPaths(t *testing.T) {
392394
body: relayEndRead,
393395
check: func(t *testing.T, _ *common.RelayResult, err error) { require.Error(t, err) },
394396
},
397+
{
398+
// The only node answers 503: the client gets the node's own status (MAG-4481).
399+
name: "read_upstream_error_status",
400+
nodes: func(*testing.T) []relayEndNode {
401+
return []relayEndNode{{"node-a", relayEndReply(503, relayEndNodeDown, 0)}}
402+
},
403+
body: relayEndRead,
404+
check: func(t *testing.T, result *common.RelayResult, err error) {
405+
require.Error(t, err)
406+
require.Equal(t, http.StatusServiceUnavailable, result.StatusCode)
407+
},
408+
},
409+
{
410+
// Every attempt is throttled: the client gets the node's own 429, no longer a router 503
411+
// (MAG-4481).
412+
name: "read_rate_limited",
413+
nodes: func(*testing.T) []relayEndNode {
414+
return []relayEndNode{{"node-a", relayEndReply(429, relayEndThrottled, 0)}}
415+
},
416+
body: relayEndRead,
417+
check: func(t *testing.T, result *common.RelayResult, err error) {
418+
require.Error(t, err)
419+
require.Equal(t, http.StatusTooManyRequests, result.StatusCode)
420+
},
421+
},
422+
{
423+
// The only node takes the request and never answers: 504, no longer a 500 carrying
424+
// "context deadline exceeded" (MAG-4481).
425+
name: "read_no_answer_in_time",
426+
nodes: func(*testing.T) []relayEndNode { return []relayEndNode{{"node-a", relayEndSilent}} },
427+
body: relayEndRead,
428+
timeout: 1500 * time.Millisecond,
429+
check: func(t *testing.T, result *common.RelayResult, err error) {
430+
require.Error(t, err)
431+
require.Equal(t, http.StatusGatewayTimeout, result.StatusCode)
432+
},
433+
},
395434
{
396435
name: "pinned_write",
397436
fanOut: true,

‎protocol/rpcsmartrouter/rpcsmartrouter_server.go‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1510,7 +1510,9 @@ func relayFailureLogAttrs(err error, attrs ...utils.Attribute) []utils.Attribute
15101510
}
15111511

15121512
// withNoAnswerTimeout names the request's processing timeout in a 504 reply, which the relay
1513-
// processor builds without knowing it. Copied rather than mutated, as in withUnclearWriteStatus.
1513+
// processor builds without knowing it. It is the request's budget, not the time the failed attempt
1514+
// took: a connect timeout (1001) that gave up early still reads "within <processing timeout>".
1515+
// Copied rather than mutated, as in withUnclearWriteStatus.
15141516
func (rpcss *RPCSmartRouterServer) withNoAnswerTimeout(result *common.RelayResult, protocolMessage chainlib.ProtocolMessage) *common.RelayResult {
15151517
cf := result.GetClientFacing()
15161518
if cf == nil || !cf.TimedOut || cf.Timeout > 0 {
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
{
2+
"GUID": "7734770",
3+
"api_interface": "jsonrpc",
4+
"attempts": [
5+
{
6+
"batch": 0,
7+
"error_code": "",
8+
"message": "",
9+
"outcome": "timeout",
10+
"returned_to_client": false,
11+
"sent_ms": "<ms>",
12+
"upstream": "node-a"
13+
}
14+
],
15+
"chain": "ETH1",
16+
"error": "context deadline exceeded",
17+
"error_code": "PROTOCOL_CONTEXT_DEADLINE",
18+
"event": "relay_end",
19+
"has_reply": false,
20+
"is_batch": false,
21+
"latency_ms": "<ms>",
22+
"level": "info",
23+
"message": "relay_end",
24+
"method": "eth_getBalance",
25+
"outcome": "no_answer",
26+
"request_bytes": 115,
27+
"schema": 2,
28+
"selection": "stateless",
29+
"served_by": "",
30+
"stateful": false,
31+
"status": 504,
32+
"stop_reason": "ProcessingTimeout"
33+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
{
2+
"GUID": "7073657",
3+
"api_interface": "jsonrpc",
4+
"attempts": [
5+
{
6+
"batch": 0,
7+
"error_code": "NODE_RATE_LIMITED",
8+
"latency_ms": "<ms>",
9+
"message": "HTTP 429 Too Many Requests",
10+
"outcome": "rate_limited",
11+
"retryable": true,
12+
"returned_to_client": false,
13+
"sent_ms": "<ms>",
14+
"upstream": "node-a"
15+
}
16+
],
17+
"chain": "ETH1",
18+
"error": "failed relay, insufficient results ErrMsg: HTTP 429 Too Many Requests {GUID:<GUID>}",
19+
"error_code": "NODE_RATE_LIMITED",
20+
"event": "relay_end",
21+
"has_reply": false,
22+
"is_batch": false,
23+
"latency_ms": "<ms>",
24+
"level": "info",
25+
"message": "relay_end",
26+
"method": "eth_getBalance",
27+
"outcome": "no_answer",
28+
"request_bytes": 115,
29+
"schema": 2,
30+
"selection": "stateless",
31+
"served_by": "",
32+
"stateful": false,
33+
"status": 429,
34+
"stop_reason": "AllProvidersExhausted"
35+
}

0 commit comments

Comments
 (0)