Skip to content

fix(watch): do not drop events when a read carries multiple responses - #224

Merged
AlinsRan merged 7 commits into
masterfrom
fix/read-watch-keep-events
Jul 28, 2026
Merged

fix(watch): do not drop events when a read carries multiple responses#224
AlinsRan merged 7 commits into
masterfrom
fix/read-watch-keep-events

Conversation

@AlinsRan

@AlinsRan AlinsRan commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

Problem

read_watch() splits one body read into several watch responses, decodes the events of each into all_events, and then attaches all_events to body — which points at the last decoded response. The attach was guarded by #all_events > 1:

if #all_events > 1 then
    body.result.events = all_events
end

So a read holding [response with 1 event, response without events] returns the last response as is, and the event is silently lost. The caller cannot detect it.

Today etcd never produces that layout, because the only event-less responses are created and canceled and neither trails an event response. It does as soon as the watch is created with progress_notify: a notification can be coalesced right behind an event response on the same TCP read.

apache/apisix needs progress_notify to advance start_revision safely (apache/apisix#13067), so this has to be fixed first — otherwise the same class of silent event loss is reintroduced inside the library.

Fix

Attach the events whenever any were collected (> 0).

Also guard on body.result, which is nil when the last response is an error body with an http code below 500. That path is reachable today too and > 1 would already index nil there, so this is a strict improvement rather than a new behaviour.

Compatibility

No behaviour change for anything that exists today:

  • single-chunk reads never reach this line (#chunks == 1 returns early for event-less responses)
  • [notify, event response] order: body already is the event response, so the assignment is a no-op
  • [event, canceled]: both spellings end in the same compacted full-reload path on the apisix side

Test

t/v3/watch.t drives the client against a fake watch endpoint that writes an event response followed by a progress notification in a single body chunk, and asserts the event survives. A real etcd cannot be pushed into producing that coalescing reliably.

Not run locally — CI covers it.

Follow-up

A v1.10.7 release is needed before apache/apisix can pin it and merge its side.

Summary by CodeRabbit

  • Bug Fixes

    • Fixed v3 watch streaming to retain collected events even when multiple watch responses are coalesced into a single HTTP body chunk alongside progress updates.
  • Tests

    • Added a watchdir test to confirm coalesced watch responses preserve the expected single event and report the correct final progress revision, with no error log entries.
    • Broadened the TLS verification failure expectation to accept either “self-signed” or “self signed”.
  • Chores

    • Updated CI runner and modernized the Go toolchain setup, including installing a pinned goreman version via the local toolchain.

read_watch() splits one body read into several watch responses, decodes the
events of each of them into all_events, and then attaches all_events to
`body`, which points at the last decoded response. The attach was guarded by
`#all_events > 1`, so a read holding [response with 1 event, response without
events] returned the last response as is and the event was lost, silently and
unrecoverably for the caller.

Today etcd never produces that layout because the only event-less responses
are `created` and `canceled`, which never trail an event response. It does as
soon as the watch is created with progress_notify, which apache/apisix needs
to advance start_revision safely (apache/apisix#13067).

Attach the events whenever any were collected. Also guard on body.result,
which is nil when the last response is an error body with an http code below
500 - reachable before this change too, and a nil index in the watch loop.
@coderabbitai

coderabbitai Bot commented Jul 20, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

You’ve reached a temporary PR review limit under our Fair Usage Limits Policy.

Your recent review volume is higher than typical usage, so adaptive limits are currently applied.

Next review available in: 9 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f573e7c0-935e-43c5-8139-f7c5d4d03174

📥 Commits

Reviewing files that changed from the base of the PR and between c7e0e1d and 73865df.

📒 Files selected for processing (1)
  • t/v3/watch.t
📝 Walkthrough

Walkthrough

The v3 watch response merger now preserves events from coalesced responses. A regression test covers an event response followed by a progress response, the TLS test accepts alternate certificate wording, and the CI build environment updates its runner and Go tooling.

Changes

Watch response coalescing

Layer / File(s) Summary
Merge coalesced watch responses and test the result
lib/resty/etcd/v3.lua, t/v3/watch.t
Collected events are attached when at least one event exists and the final response has a result. The test serves concatenated watch responses and verifies revision 9, one event, and the expected key/value.

CI and TLS test maintenance

Layer / File(s) Summary
Update CI build environment
.github/workflows/ci.yml
The build job now runs on Ubuntu 22.04, uses Go 1.22 with setup-go v5, and installs goreman at version v0.3.15 with go install.
Broaden TLS error matching
t/v3/tls.t
The certificate verification expectation accepts both self-signed and self signed wording.

Estimated code review effort: 2 (Simple) | ~10 minutes

Sequence Diagram(s)

sequenceDiagram
  participant WatchTest
  participant FakeNginx
  participant EtcdClient
  participant WatchMerger
  WatchTest->>EtcdClient: call watchdir("/test")
  EtcdClient->>FakeNginx: request /v3/watch
  FakeNginx-->>EtcdClient: concatenated event and progress JSON fragments
  EtcdClient->>WatchMerger: decode and merge watch responses
  WatchMerger-->>WatchTest: revision 9 with one preserved event
Loading
🚥 Pre-merge checks | ✅ 6
✅ Passed checks (6 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the watch-event loss fix when one read contains multiple responses.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
E2e Test Quality Review ✅ Passed PASS: The new Test::Nginx case is readable, independent, and exercises the full client→HTTP upstream path for the coalesced-watch regression; fake upstream is justified here.
Security Check ✅ Passed Reviewed the workflow, watch merge fix, and tests; found no secret leakage, auth bypass, ownership, TLS, or persistence issues.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/read-watch-keep-events

Comment @coderabbitai help to get the list of available commands.

AlinsRan added 2 commits July 27, 2026 13:02
The ubuntu-20.04 hosted runner image has been retired, so jobs pinned to
it queue indefinitely with no runner to pick them up. Move to ubuntu-22.04.
goreman's transitive dependency golang.org/x/sys v0.46.0 now imports the
stdlib "slices" package (Go >= 1.21), so building it under the pinned Go
1.17 fails at the install step. Bump the toolchain to 1.22.

Since 'go get' no longer installs binaries on Go >= 1.18, switch to
'go install github.com/mattn/goreman@latest'.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.github/workflows/ci.yml:
- Around line 38-42: Update the goreman installation step in the workflow to pin
github.com/mattn/goreman to a release compatible with Go 1.22, or raise the
setup-go version to match the module’s declared requirement. Keep the setup-go
and goreman versions consistent so installation does not trigger an unintended
toolchain download.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 208b83e0-07cf-48cd-911b-7e5b2b3c34d5

📥 Commits

Reviewing files that changed from the base of the PR and between fa940dd and 4ab60af.

📒 Files selected for processing (1)
  • .github/workflows/ci.yml

Comment thread .github/workflows/ci.yml

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes a v3 watch edge case where multiple newline-delimited watch responses arrive in a single HTTP body read and events from earlier responses could be silently lost when the last response is event-less (e.g., progress notifications).

Changes:

  • Preserve collected watch events by attaching them whenever any events were decoded (and avoid indexing nil when the last response is an error body without result).
  • Add a Test::Nginx case that simulates an event response immediately followed by a progress notification in the same body chunk.
  • Refresh CI environment (Ubuntu 22.04, newer setup-go, and goreman installation method).

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
lib/resty/etcd/v3.lua Ensures watch events aren’t dropped when a single read contains multiple watch responses and the last response has no events.
t/v3/watch.t Adds regression coverage for coalesced watch responses (event + progress notify in one read).
.github/workflows/ci.yml Updates CI runner/tooling and switches goreman installation to go install.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread .github/workflows/ci.yml Outdated
AlinsRan added 4 commits July 27, 2026 14:22
The new t/v3/watch.t TEST 1 had no '--- request' section, so Test::Nginx
had no request to send to the /t location and bailed out with
'Request line should be non-empty' before the assertions ran.
OpenSSL 3.x reworded the X509 verify error from 'self signed certificate'
to 'self-signed certificate' (hyphen). Broaden the TEST 2 pattern to
'self[ -]signed' so it matches both the 1.1.x and 3.x spellings.
Addresses review feedback (CodeRabbit/Copilot): 'go install goreman@latest'
is non-deterministic, and goreman >= v0.3.19 declares 'go 1.25' in its module,
so Go's default GOTOOLCHAIN=auto would silently fetch a 1.25 toolchain and
defeat the setup-go 1.22 pin.

Pin to v0.3.15 (module 'go 1.19', golang.org/x/sys v0.6.0) which builds with
the 1.22 toolchain, and set GOTOOLCHAIN=local so a future pin bump that needs
a newer toolchain fails loudly instead of downloading one.
The fix's premise is that the response holding events is not necessarily the
last one in a coalesced read, so cover both orderings and an interleaving,
not just [event, progress]:
- TEST 2: [progress, event]  -> event is the last response
- TEST 3: [event, progress, event] -> both events survive, in order

Also document why TEST 1 reports the trailing progress notification's
revision while still delivering the earlier event.
@AlinsRan AlinsRan self-assigned this Jul 28, 2026
@AlinsRan
AlinsRan merged commit 9225cc8 into master Jul 28, 2026
6 checks passed
@AlinsRan
AlinsRan deleted the fix/read-watch-keep-events branch July 28, 2026 06:25
@AlinsRan AlinsRan mentioned this pull request Jul 28, 2026
AlinsRan added a commit to AlinsRan/apisix that referenced this pull request Jul 29, 2026
1.10.7 ships the read_watch coalescing fix (api7/lua-resty-etcd#224) that
progress_notify depends on: when etcd coalesces an event response and a
progress notification into a single read, events are no longer dropped.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants