Skip to content

[ISSUE #7693] Fix false offline timeout during HTTP long-polling holds - #7727

Merged
Aias00 merged 3 commits into
apache:masterfrom
DrDread746:fix-http-longpolling-liveness-timeout
Oct 28, 2026
Merged

Aias00 merged 3 commits into
apache:masterfrom
DrDread746:fix-http-longpolling-liveness-timeout

Conversation

@DrDread746

@DrDread746 DrDread746 commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fixes #7693

During HTTP long-polling sync (HttpLongPollingDataChangedListener), held requests (>20s) without configuration changes caused InstanceCheckService to falsely classify active gateway instances as OFFLINE.

Key Changes

  1. Periodic Liveness Refresh: HttpLongPollingDataChangedListener now schedules a periodic heartbeat refresh (using HttpSyncProperties.getHeartbeatInterval(), default 10s) while long-polling requests are held.
  2. Scheduler Isolation: Introduced a dedicated livenessScheduler (shenyu-http-long-polling-liveness-) with setRemoveOnCancelPolicy(true) and @PreDestroy teardown to isolate liveness event publishing from core long-polling execution.
  3. Clean Lifecycle & Disconnect Handling: Added jakarta.servlet.AsyncListener to LongPollingClient and an early isCompleted.get() guard to execute immediate, idempotent resource cleanup (cleanUp()) on request completion, timeout, or unexpected disconnects, eliminating clientsMap memory leaks.
  4. Blank Port Filtering: Updated 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 InstanceCheckService and preserves existing health check logic without modifying control plane thresholds.

Test Coverage

  • Refactored HttpLongPollingDataChangedListenerTest to eliminate string-based reflection in favor of package-private accessors.
  • Replaced wall-clock timing delays with deterministic assertions on scheduled future parameters.
  • Verified all 53 unit tests pass and Checkstyle reports 0 violations locally.

@Aias00 Aias00 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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:

  1. the listener callback sets isCompleted = true and calls cleanUp(), which removes this from a queue it is not in yet (no-op);
  2. run() then schedules the timeout and the heartbeat future and adds this to the queue;
  3. the timeout task fires, sendResponse sees the CAS already held and returns without cleanUp(), so this stays 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 whose X-Real-Port header 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 of getDeclaredMethod strings 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.
  • testFalseOfflineTimeoutReproduction asserts 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)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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(() -> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@DrDread746
DrDread746 force-pushed the fix-http-longpolling-liveness-timeout branch from d02734b to c845870 Compare October 18, 2026 06:13
@DrDread746

DrDread746 commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Thank you for the thorough and invaluable review! I have updated the implementation to address all your points in the latest commit:

  1. clientsMap Leak: Added an isCompleted.get() guard at the top of run() before queueing, and ensured cleanUp() is unconditionally/idempotently invoked so stale clients cannot stay stuck in clientsMap.
  2. Configurable Cadence: Exposed heartbeatInterval in HttpSyncProperties (defaulting to 10s) so liveness reporting is tunable via configuration.
  3. Scheduler Isolation: Created a dedicated livenessScheduler (shenyu-http-long-polling-liveness-) with setRemoveOnCancelPolicy(true) and @PreDestroy container cleanup to decouple liveness event publishing from long-polling task execution.
  4. Blank Port Filtering: Updated shouldReportInstance() to reject null, blank, or whitespace-only ports alongside "0".
  5. Test Refactoring: Removed reflection in favor of package-private accessors, replaced wall-clock Thread.sleep assertions with scheduled future assertions, and renamed the reproduction test to documentationReproduceFalseOfflineTimeoutBeforeFix.
  6. Design Rationale Note: Noted in the PR description that refreshing during long-poll holds preserves zero runtime overhead on InstanceCheckService without altering global health check logic.

Aias00
Aias00 previously approved these changes Oct 21, 2026

@Aias00 Aias00 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approving the code. c845870a fixes the leak I was worried about and does it at the point where the race actually is:

  • sendResponse on CAS failure now calls cleanUp(). Previously the losing thread just returned, leaving the client in clientsMap for the lifetime of the listener; every subsequent notifyChanged would then poll and try to write to an already-completed AsyncContext. Cleaning up on the losing path is the correct fix, and it is safe to run concurrently with the winner's cleanUp() because the method is idempotent (cancel on a finished future is a no-op, remove on the queue is a no-op).
  • run() early-returns when isCompleted is already set. That closes the window where a submit-after-completion started a fresh scheduleWithFixedDelay on 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; keeping setRemoveOnCancelPolicy(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. @PreDestroy plus DisposableBean is belt-and-braces but harmless (double shutdown() is idempotent).
  • heartbeatInterval now comes from HttpSyncProperties instead of a constructor parameter, with a 10 s fallback when the property is absent or ≤ 0. I checked that the removed public static final long DEFAULT_HEARTBEAT_INTERVAL_MS has 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.
  • shouldReportInstance also rejects a blank port. Good defensive addition: a blank port used to pass the check and then register an instance at null/empty.

Non-blocking observations:

  1. In run(), Objects.nonNull(livenessScheduler) ? livenessScheduler : scheduler is dead code — the constructor guarantees livenessScheduler is non-null (it falls back to its own pool). Fine to keep as defence, but a reader will wonder which branch can be taken.
  2. The 10 s fallback is now a bare literal inside run(). It used to be the named DEFAULT_HEARTBEAT_INTERVAL_MS; keeping a private constant with the same name would preserve the intent without restoring the public API.
  3. 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.
  4. LongPollingClient.run() reads isCompleted without synchronisation before doing work — that is a fast-path check only, and every mutation still goes through the compareAndSet, 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:

  • mergeStateStatus is DIRTY / mergeable: CONFLICTING. Please rebase onto current master.
  • No CI has run on c845870a. gh pr checks reports no checks on this head and actions/runs?head_sha=c845870a is 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.

@Aias00

Aias00 commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

Heads-up: this branch now has merge conflicts with master (mergeStateStatus: DIRTY), so CI cannot validate it against the current base.

The conflict is in the long-polling listener area you touch:
shenyu-admin/.../config/properties/HttpSyncProperties.java and .../listener/http/HttpLongPollingDataChangedListener.java.

Please rebase onto master and confirm the offline-timeout fix still applies to the current listener implementation. I will re-review once pushed.

@DrDread746
DrDread746 force-pushed the fix-http-longpolling-liveness-timeout branch from c845870 to 275b621 Compare October 21, 2026 14:48
@DrDread746

Copy link
Copy Markdown
Contributor Author

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 Aias00 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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:

  • computeIfAbsent replaces the previous getOrDefault + put, which could drop a concurrently registered queue.
  • Removing the client from the queue moved into cleanUp(), which is now called from sendResponse, the timeout path and all three AsyncListener callbacks.
  • setRemoveOnCancelPolicy(true) prevents cancelled timeout and heartbeat futures from piling up.

Two nits:

  1. shouldReportInstance used 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. Consider NumberUtils.toInt(clientPort, 0) > 0.
  2. heartbeatIntervalMs is computed in the constructor but refreshLiveness re-derives the interval from httpSyncProperties; use the field to keep a single source of truth.

@Aias00

Aias00 commented Oct 24, 2026

Copy link
Copy Markdown
Contributor

@DrDread746 This PR is approved, but 2 checks are red: build (shenyu-integrated-test-combination), build (shenyu-integrated-test-http).

I inspected these lanes today and they fail for infrastructure reasons rather than on the diff — the integrated-test jobs die while starting their containers (Elasticsearch /_cat/health returning 000 until the job is cancelled), and the http lane also hits the known CachePluginTest.testMemoryModle / testRedisModle flake. The same jobs are red on master and on unrelated PRs right now.

Please rebase onto master and push (or ask for a re-run) so the checks execute again. If a case is still failing on a fresh run, paste the test name and I'll look properly.

@DrDread746

Copy link
Copy Markdown
Contributor Author

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!

@Aias00

Aias00 commented Oct 25, 2026

Copy link
Copy Markdown
Contributor

@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.

master went green at a8080ae: the SubscribeTest fixture isolation (#8092), the MQTT session scoping (#8093) and the pr_build dependency fix (#8075) all landed, and the latest ci.yml, integrated-test.yml and CodeQL runs on master are all success.

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.

@DrDread746
DrDread746 force-pushed the fix-http-longpolling-liveness-timeout branch from 275b621 to de10a6c Compare October 25, 2026 04:58
@DrDread746

Copy link
Copy Markdown
Contributor Author

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!

@Aias00
Aias00 merged commit 4a1a08b into apache:master Oct 28, 2026
55 checks passed
@Aias00 Aias00 added this to the 2.7.2 milestone Nov 13, 2026
@DrDread746
DrDread746 deleted the fix-http-longpolling-liveness-timeout branch November 16, 2026 12:53
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.

[BUG] HTTP long-polling gateways can be marked offline during a healthy poll

2 participants