Skip to content

fix: wait for HTTP handlers before closing cache - #258

Merged
ovaistariq merged 6 commits into
mainfrom
perfloop-pr-open-j14dqbnsm5
Oct 21, 2026
Merged

ovaistariq merged 6 commits into
mainfrom
perfloop-pr-open-j14dqbnsm5

Conversation

@perfloop

@perfloop perfloop Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

TAG closes HTTP handler admission before graceful shutdown and waits for every admitted handler through synchronous cache cleanup. If the 30-second drain expires, it cancels request contexts and closes connections, but Stop waits for handlers before returning so main's deferred embedded-cache close follows. Requests finishing within grace keep their normal response and post-success invalidation. Shutdown-racing S3 routes receive XML ServiceUnavailable; operational and unmatched routes retain plain HTTP 503. No S3 API or configuration changes.

An atomic stop/count state closes admission and tracks in-flight handlers. Connection tracking and admission wrappers are composed once for each registered route at setup, preserving their order without rebuilding the Mux middleware chain on every match.

This condition holds with this change and does not hold at 628616fd9e19fac473837eb45eb46115e3d33313: After SIGTERM, TAG does not close its embedded cache until every admitted foreground HTTP handler and its synchronous consistency cleanup has exited, including when the drain expires..

The six expiry/startup tests fail their lifecycle assertions on the starting revision and pass on the intermediate implementation and final source:

  • TestStopWaitsForActiveDeleteCleanupAfterDrainExpiry holds a successful DELETE's second cache delete across drain expiry and checks that the close marker does not precede cleanup and handler exit.
  • TestStopCancelsForwardingAfterDrainExpiry verifies expiry cancels a held origin-bound DELETE and joins its handler; it waits up to five seconds for the origin to observe cancellation.
  • TestStopJoinsDisconnectedHTTP2DeleteCleanup returns HTTP/2 204, disconnects the stream while invalidation is blocked, and verifies Stop still joins cleanup.
  • TestStopCancelsIncompletePutBodyAfterDrainExpiry holds a partial PUT body and verifies request cancellation and handler exit before close.
  • TestStartUsesHandlerLifetimeBarrier exercises the actual Start path with a blocked handler and verifies Stop waits.
  • TestStopBeforeStartPreventsHTTPAndHTTPSListen verifies Stop-before-Start prevents both HTTP and HTTPS listeners.

TestStopDrainsActiveDeleteWithinGrace passes on all three revisions and verifies the 204 response and both cache invalidations. TestStopRejectsRequestsAfterClosingAdmission fails on the starting revision with 204 and dependency calls. The intermediate implementation returns HTTP 503 without calls but uses text/plain; final asserts XML ServiceUnavailable, keeps the no-call check, and confirms /health remains plain 503. TestServerSetupAppliesAdmissionMiddleware passes on base, intermediate, and final source; it checks that a full S3 limit still serves /health and sheds an object GET with XML SlowDown.

The handler unit and race suites, static build, embedded-cache integration tests, vet, formatting, and parallel BenchmarkServerHTTPHandler smoke run passed. The existing BenchmarkHandlerWarmedEmbeddedCacheHit uses Server.Router() and bypasses the Start/Stop lifetime gate. The new native benchmark exercises the actual http.Server handler on /health; it does not measure S3/cache throughput. make bench-warp was not run because it requires Tigris credentials and a live upstream. make test and make lint-ci remain for target CI.

The cache-ordering unit tests use a recording memory-cache client. A separate Go subprocess harness, not included in this PR, sends SIGTERM to a child test process that calls TAG's Server.Stop with a real single-node embedded cache and a held origin response. It does not launch the tag binary. The harness uses a 2-second test drain to expose expiry; production remains at 30 seconds. It establishes ordering for this constructed schedule, not backend-corruption rates or production incidence. Kubernetes also grants 30 seconds for termination and may stop the process while uncooperative cleanup is still running; there is no fixed completion guarantee in that case.


Generated by Perfloop.


Note

Medium Risk
Changes core shutdown and request admission behavior under SIGTERM; mis-tuned pod termination grace could still kill the process during long cleanup, but the fix reduces cache-use-after-close risk during rollouts.

Overview
TAG now tracks admitted HTTP handlers through shutdown so the embedded cache is not closed while synchronous handler work (including post-response cache invalidation) is still running.

Server.Stop closes handler admission first, runs the usual HTTP drain (30s in production), and if the drain expires cancels request contexts and force-closes connections—but still blocks until every admitted handler exits before returning. Late S3 traffic gets XML ServiceUnavailable; /health and other operational paths keep a plain HTTP 503.

Routing middleware is wrapped once per route at setup (connection tracking + admission) instead of Router.Use, avoiding mux rebuilding middleware on every match. Docs (README, docs/deploy.md) describe the drain window and how Kubernetes terminationGracePeriodSeconds relates to handler cleanup.

Coverage adds extensive shutdown lifecycle tests (DELETE cleanup past drain, HTTP/2 disconnect, partial PUT cancel, admission after stop) plus a small benchmark on the real http.Server handler stack.

Reviewed by Cursor Bugbot for commit 7c0573c. Bugbot is set up for automated code reviews on this repo. Configure here.

@greptile-apps

greptile-apps Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no actionable new issues were found.

Summary

TAG now waits for admitted HTTP handlers and their synchronous cleanup before allowing the embedded cache to close.

  • TAG waits for admitted HTTP handlers before closing the embedded cache.
  • Registered routes keep their admission checks without rebuilding middleware chains.

Reviews (3) · Last reviewed commit: "Merge branch 'main' into perfloop-pr-ope..." · Reviewed by Greptile

Comment thread handlers/shutdown_test.go Resolved
perfloop-agent and others added 3 commits October 16, 2026 07:48
Warn once when Stop waits past the drain deadline for in-flight handlers.

Resolve handlers/server.go against #259 by keeping this branch's NewServer
(which already moved the http.Server literal and adds BaseContext) plus
#259's comment. Adapt #259's stop-before-start test to check that the
server handler dispatches to the router instead of comparing identity,
since the router is now wrapped by the handler lifecycle barrier.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NGTev5ePU5jHubGtdoUfK6
ovaistariq added a commit that referenced this pull request Oct 21, 2026
Rebase #256 over #237/#239/#240 and #258: keep main's populateBlockMode
split, RangeBlockSpan publication, lazyCommitWriter range serve and the
32-slot parquet footer prefetch semaphore, with every detached spawn still
admitted through serviceWorkers.

A footer prefetch that serviceWorkers refuses during Stop now releases its
admission slot and dedup marker exactly as a finished scan would, so a
shutdown-time refusal cannot leak one of the 32 permits.

Service.Stop logs one Warn when its unbounded join passes 30s (main's drain
timeout) with the outstanding task count, and one Info with the elapsed
wait when the join then completes, mirroring warnHandlerJoinPastDeadline.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NGTev5ePU5jHubGtdoUfK6
@ovaistariq
ovaistariq merged commit 854839c into main Oct 21, 2026
9 checks passed
@ovaistariq
ovaistariq deleted the perfloop-pr-open-j14dqbnsm5 branch October 21, 2026 18:37
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 21, 2026
@tigrisdata-argocd-bot

Copy link
Copy Markdown

🎉 This PR is included in version 1.22.3 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants