Repository navigation
[ISSUE #7693] Fix false offline timeout during HTTP long-polling holds - #7727
Conversation
Aias00
left a comment
There was a problem hiding this comment.
The diagnosis is right — a 60 s hold with a 20 s liveness threshold does mark a healthy gateway OFFLINE, and refreshing during the hold is a reasonable fix. But the lifecycle rework introduces a leak in clientsMap, and since cleanup is the whole point of this PR I would rather fix it here.
1. A client can become unreachable in clientsMap (the unconditional removal was dropped)
The old timeout task called namespaceClients.remove(LongPollingClient.this) before responding, so a client always left the queue. That line is gone, and removal now happens only inside cleanUp(), which sendResponse reaches only after winning the CAS (:582).
If isCompleted was already set by onError/onComplete/onTimeout before run() executed — the async request starts in the servlet thread and run() is queued on the single scheduler thread, so a disconnect inside that window is enough — then:
- the listener callback sets
isCompleted = trueand callscleanUp(), which removesthisfrom a queue it is not in yet (no-op); run()then schedules the timeout and the heartbeat future and addsthisto the queue;- the timeout task fires,
sendResponsesees the CAS already held and returns withoutcleanUp(), sothisstays in the queue for the lifetime of the process.
The result is a slow leak, plus a dead entry that every DataChangeTask will keep iterating. Two cheap fixes, either is enough: check isCompleted.get() at the top of run() (and complete the context), and/or call cleanUp() in the already-completed branch of sendResponse — it is idempotent.
2. The refresh cadence is not configurable
DEFAULT_HEARTBEAT_INTERVAL_MS (10 s) is only reachable through the test constructor; the production path always builds the listener with httpSyncProperties. The 10 s value is implicitly coupled to InstanceCheckService's 20 s instanceHeartBeatTimeOut — if that default ever changes, this silently becomes wrong. Please expose it as an HttpSyncProperties field (with the same default) so the relationship is visible and tunable.
3. One scheduler for everything
refreshLiveness runs on the same single-threaded scheduler that also serves refreshLocalCache, the hold timeouts and every DataChangeTask, and it now runs once per held client per interval. Any listener of InstanceInfoReportEvent that does I/O on the publishing thread would stall the whole long-polling machinery. InstanceCheckService is in-memory today, so this is latent rather than broken, but a separate scheduler for liveness (or documenting the "publish must be cheap" contract) would bound the blast radius.
4. Smaller things
shouldReportInstance("")returns true, so a client whoseX-Real-Portheader is missing still reports an instance with a blank port — and now re-reports it every interval instead of once per request. #7776 drops those reports at the service, but if that does not land the bogus identity becomes permanent rather than transient. Worth aligning the two.getHeartbeatFuture()/getAsyncTimeoutFuture()/isCompleted()exist only for the tests, and the tests reach them (and the constructor) by name via reflection. That works, but renaming anything silently breaks five tests; using the accessors directly instead ofgetDeclaredMethodstrings would keep the compiler on your side.- The 100 ms-interval test (
testScheduledHeartbeatRefreshesLivenessAutomatically) waits 1200 ms for 2 publishes; it should be stable, but it is the kind of test that flakes on a loaded CI runner. Consider asserting on the future's schedule rather than on wall-clock counts. testFalseOfflineTimeoutReproductionasserts the bug (OFFLINE) and is really documentation. The comment header future-proofs it, but it will start failing if the threshold changes; renaming it to make the intent explicit would help.
CI: no workflow run on this branch (no checks reported), so the 53 tests mentioned in the PR body have not run in CI. Please get pr_build green as part of the revision.
I have not reviewed the design question of whether the admin should be beating on the gateway's behalf — given that the independent beat channel already exists but is optional in deployments, refreshing during a hold is defensible. Say so explicitly in the PR body so the maintainers can weigh the alternative (treating an active hold as liveness inside InstanceCheckService).
| // cancel scheduler | ||
| if (Objects.nonNull(asyncTimeoutFuture)) { | ||
| asyncTimeoutFuture.cancel(false); | ||
| if (!isCompleted.compareAndSet(false, true)) { |
There was a problem hiding this comment.
The old code removed the client from clientsMap unconditionally in the timeout task; removal now only happens via cleanUp() after this CAS succeeds. If onError/onComplete fired before run() added the client, isCompleted is already true, the listener's cleanUp() removed nothing, run() adds the client anyway, and this branch returns without cleaning up — the client then stays in the queue forever. Calling cleanUp() here (it is idempotent) or checking isCompleted at the top of run() closes it.
| BlockingQueue<LongPollingClient> namespaceClients = clientsMap.getOrDefault(namespaceId, new ArrayBlockingQueue<>(1024)); | ||
| BlockingQueue<LongPollingClient> namespaceClients = clientsMap.computeIfAbsent( | ||
| namespaceId, k -> new ArrayBlockingQueue<>(1024)); | ||
| this.asyncTimeoutFuture = scheduler.schedule(() -> { |
There was a problem hiding this comment.
Nit: run() schedules both futures and enqueues the client without checking isCompleted, which is what makes the race described on sendResponse possible. An early if (isCompleted.get()) { cleanUp(); return; } here would also avoid scheduling a heartbeat for a client that is already gone.
d02734b to
c845870
Compare
|
Thank you for the thorough and invaluable review! I have updated the implementation to address all your points in the latest commit:
|
Aias00
left a comment
There was a problem hiding this comment.
Approving the code. c845870a fixes the leak I was worried about and does it at the point where the race actually is:
sendResponseon CAS failure now callscleanUp(). Previously the losing thread just returned, leaving the client inclientsMapfor the lifetime of the listener; every subsequentnotifyChangedwould then poll and try to write to an already-completedAsyncContext. Cleaning up on the losing path is the correct fix, and it is safe to run concurrently with the winner'scleanUp()because the method is idempotent (cancel on a finished future is a no-op,removeon the queue is a no-op).run()early-returns whenisCompletedis already set. That closes the window where a submit-after-completion started a freshscheduleWithFixedDelayon a client that would never clean it up.- Separate
livenessScheduler. Sharing one single-thread pool between the long-poll timeout tasks and the per-client liveness heartbeat was the reason a slow liveness refresh could delay every pending poll's response. Splitting the pools removes the head-of-line blocking; keepingsetRemoveOnCancelPolicy(true)on both is what stops every completed poll from leaving a cancelled task in the queue for the full timeout window. destroy()/DisposableBean. Both pools were created per instance and never shut down, so a context restart leaked two threads each time.@PreDestroyplusDisposableBeanis belt-and-braces but harmless (doubleshutdown()is idempotent).heartbeatIntervalnow comes fromHttpSyncPropertiesinstead of a constructor parameter, with a 10 s fallback when the property is absent or ≤ 0. I checked that the removedpublic static final long DEFAULT_HEARTBEAT_INTERVAL_MShas zero references anywhere in the repo, so dropping it does not break a caller — but it was public, so it is worth a line in the description.shouldReportInstancealso rejects a blank port. Good defensive addition: a blank port used to pass the check and then register an instance atnull/empty.
Non-blocking observations:
- In
run(),Objects.nonNull(livenessScheduler) ? livenessScheduler : scheduleris dead code — the constructor guaranteeslivenessScheduleris non-null (it falls back to its own pool). Fine to keep as defence, but a reader will wonder which branch can be taken. - The 10 s fallback is now a bare literal inside
run(). It used to be the namedDEFAULT_HEARTBEAT_INTERVAL_MS; keeping a private constant with the same name would preserve the intent without restoring the public API. getClientsMap()is package-private and exists for the tests. That is acceptable, but it also hands production code in the same package a mutable map; a narrower test hook (e.g.int pendingClientCount(String namespaceId)) would leak less.LongPollingClient.run()readsisCompletedwithout synchronisation before doing work — that is a fast-path check only, and every mutation still goes through thecompareAndSet, so it does not introduce a correctness hole. Worth a comment so nobody "strengthens" it into a lock.
Two merge blockers, neither of them in the change itself:
mergeStateStatusisDIRTY/mergeable: CONFLICTING. Please rebase onto currentmaster.- No CI has run on
c845870a.gh pr checksreports no checks on this head andactions/runs?head_sha=c845870ais empty, so the force-push did not start a workflow. After the rebase the push should trigger the normal set; if it does not, ask a maintainer to approve the run.
|
Heads-up: this branch now has merge conflicts with The conflict is in the long-polling listener area you touch: Please rebase onto |
c845870 to
275b621
Compare
|
Thank you for the thorough review and approval! I have rebased the branch onto current main, resolved all merge conflicts, restored the private DEFAULT_HEARTBEAT_INTERVAL_MS constant, and added the fast-path inline comment for isCompleted. All 65 unit tests and Checkstyle audits pass cleanly with 0 violations locally. |
Aias00
left a comment
There was a problem hiding this comment.
LGTM on the approach: a held long-polling connection can outlive the 20s liveness timeout, so refreshing the instance report from the server side removes the false-offline window. The isCompleted CAS also fixes the double-response race between the timeout task and DataChangeTask.
Verified:
computeIfAbsentreplaces the previousgetOrDefault+put, which could drop a concurrently registered queue.- Removing the client from the queue moved into
cleanUp(), which is now called fromsendResponse, the timeout path and all threeAsyncListenercallbacks. setRemoveOnCancelPolicy(true)prevents cancelled timeout and heartbeat futures from piling up.
Two nits:
shouldReportInstanceused to require a numeric positive port (NumberUtils.toInt(port, -1) > 0). The new check accepts any non-blank value except"0", so a malformed or negative port header now produces an instance report. ConsiderNumberUtils.toInt(clientPort, 0) > 0.heartbeatIntervalMsis computed in the constructor butrefreshLivenessre-derives the interval fromhttpSyncProperties; use the field to keep a single source of truth.
|
@DrDread746 This PR is approved, but 2 checks are red: I inspected these lanes today and they fail for infrastructure reasons rather than on the diff — the Please rebase onto |
|
Thank you for inspecting the CI logs and confirming the approval! Since the local code is fully rebased and up to date, could you please trigger a re-run of those two failed jobs (shenyu-integrated-test-http and shenyu-integrated-test-combination) when you get a chance? Appreciate your help! |
|
@DrDread746 — a correction to the note I left here yesterday. The failures on this branch all predate the fix, so nothing in your change is implicated.
That means the red checks recorded here are stale. A push — an empty commit or a rebase, whichever is easier — re-runs them against the current baseline. I would not spend time reading the old logs. |
…late scheduler, make interval configurable
275b621 to
de10a6c
Compare
|
Thank you for the update! I have rebased onto the latest master containing the CI fixes and force-pushed. Looking forward to the fresh CI run turning green! |
Description
Fixes #7693
During HTTP long-polling sync (
HttpLongPollingDataChangedListener), held requests (>20s) without configuration changes causedInstanceCheckServiceto falsely classify active gateway instances asOFFLINE.Key Changes
HttpLongPollingDataChangedListenernow schedules a periodic heartbeat refresh (usingHttpSyncProperties.getHeartbeatInterval(), default 10s) while long-polling requests are held.livenessScheduler(shenyu-http-long-polling-liveness-) withsetRemoveOnCancelPolicy(true)and@PreDestroyteardown to isolate liveness event publishing from core long-polling execution.jakarta.servlet.AsyncListenertoLongPollingClientand an earlyisCompleted.get()guard to execute immediate, idempotent resource cleanup (cleanUp()) on request completion, timeout, or unexpected disconnects, eliminatingclientsMapmemory leaks.shouldReportInstance()to reject null, empty, whitespace-only, or"0"ports.Design Rationale Note
Refreshing liveness during long-poll holds was chosen because it maintains zero runtime overhead on
InstanceCheckServiceand preserves existing health check logic without modifying control plane thresholds.Test Coverage
HttpLongPollingDataChangedListenerTestto eliminate string-based reflection in favor of package-private accessors.