Skip to content

serve: wait for the agent calls' handlers before the store closes - #258

Open
avi-papineni wants to merge 2 commits into
mainfrom
serve/drain-before-pool-close
Open

avi-papineni wants to merge 2 commits into
mainfrom
serve/drain-before-pool-close

Conversation

@avi-papineni

Copy link
Copy Markdown
Contributor

Today's shutdown sequence, and why the offline mark failed

cmd/innerwall/serve.go, on the signal context ending (signal.NotifyContext in main.go; a second signal is swallowed by it):

  1. A 10-second stopCtx is taken; grpcServer.GracefulStop() runs on its own goroutine and httpServer.Shutdown(stopCtx) drains the operator listener (Close if it runs out).
  2. Sync streams never end on their own, so GracefulStop always runs to the deadline and grpcServer.Stop() is called.
  3. Stop closes every transport and cancels every call, but returns once the connections are gone, without waiting for the handlers (grpc-go waits for handlers only in GracefulStop or with WaitForHandlers).
  4. serve returns, and its defer st.Close() closes the pool.

Meanwhile each sync handler, woken by its cancelled stream, runs its deferred exit path in internal/gateway/sync.go: it leaves the session registry and writes SYNC_STATE_OFFLINE through SetSyncState. That write already uses a detached context (context.Background() with offlineWriteTimeout, five seconds), so a cancelled context is not the problem; it races the pool close in step 4, and a write that reaches for a connection after the close fails with closed pool ("marking workload offline"). The workload then reads as it did while connected until its agent next connects.

The new sequence and its bound

Steps 1–2 are unchanged. After step 2, Stop runs on its own goroutine and serve waits again on the GracefulStop goroutine. Still running, that goroutine returns only after every handler has returned, deferred exit path included (grpc-go's own handler count, taken before each handler starts). It waits at most handlerExitGrace, five seconds, the same as the offline write's own bound. Only then does serve return and close the store. A handler still running at the end of that wait is logged once at warning level (agent calls still running at the end of shutdown; closing the store, so what they still write fails), and its writes fail as they do today.

  • Bound: a stop with agents connected takes at most 10 s + 5 s instead of 10 s. A shutdown where every call ends within the graceful window is unchanged.
  • Stop is on its own goroutine because, once every connection is gone, GracefulStop waits for handlers while holding the server lock that Stop takes, so a stuck handler cannot hold shutdown past the bound.
  • A second signal still changes nothing.
  • Nothing is added to the gateway. No new state, durable or in-process. The offline mark, the wire contract, the schema and the agent are unchanged.

Other writers checked: flow reports (ReportFlows), enrollment and renewal are gRPC handlers and are covered by the same wait. Operator requests get the existing ten-second Shutdown. The retention job and the policy announcement listener run on the serve context and write nothing once it has ended: each returns silently on ctx.Err().

Test

TestServeShutdownMarksStreamsOffline (cmd/innerwall/serve_shutdown_integration_test.go) runs serve as the binary builds it, with its log captured. It connects four real agent sync daemons and waits until each workload reads synced with its snapshot instant recorded. Then it stops serve with the streams open. Once serve has returned, every workload must read offline with a last-seen instant between the stop and the return, and the log must carry neither marking workload offline nor closed pool (it must carry control plane serving, so an empty capture cannot pass). The store is given pool_max_conns=2 for four streams, so the marks queue for a connection as the streams end, the moment a pool closed under them refuses them. Every wait is on a condition with a deadline. serve now takes the log's writer as a parameter, and runServe passes standard error as before.

The first commit adds the test alone, so its CI run shows the test failing without the fix. The second commit is the fix.

docs/reference/innerwall-cli.md (serve) now states the order and the bound. There is also a CHANGELOG entry.

Verified by the project's CI only; nothing was built or run locally.

Fixes #113.


Generated by Claude Code

TestServeShutdownMarksStreamsOffline runs the control plane as `innerwall
serve` builds it, connects four agents, stops it with their sync streams
open, and requires that by the time serve returns every workload reads
offline with a last-seen instant from the shutdown and the log carries no
failed offline mark. The store is given two connections for four
streams, so the marks queue for a connection as the streams end.

serve takes the log's writer as a parameter so the test can read it;
runServe passes standard error as before.

This commit adds the test alone and is expected to fail: serve returns,
and closes the store, before the stream handlers have written their
marks (#113). The next commit fixes the order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
On a signal, serve ran GracefulStop on its own goroutine and waited up to
ten seconds for it. Sync streams never end on their own, so that wait
always ran out and serve called Stop, which ends every call but returns
without waiting for their handlers. serve then returned, and its
deferred store close ran while the sync handlers were writing their
workloads' offline marks on their way out; a mark that reached for a
connection after the close failed with "closed pool". The mark itself
already uses a detached context with its own five-second bound, so the
order was the whole cause.

GracefulStop, still running after Stop, returns only once every handler
has returned, its deferred exit path included. serve now waits on it
again after Stop, for at most five seconds, before returning; a handler
still running then is logged once at warning level and its writes fail
as before. Stop runs on its own goroutine, since it takes the lock that
GracefulStop holds while waiting for handlers. A stop with agents
connected is bounded at fifteen seconds instead of ten; a second signal
still changes nothing.

The serve reference states the order and the bound, and the changelog
records the change.

Fixes #113.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

No ADR contradictions found (diff-anchored review).

Scope

The diff touches only cmd/innerwall/serve.go, cmd/innerwall/serve_grace_integration_test.go, a new cmd/innerwall/serve_shutdown_integration_test.go, CHANGELOG.md, and docs/reference/innerwall-cli.md. It does not touch docs/adr/ or CLAUDE.md, so this is a diff-anchored review rather than a full-corpus audit.

The change reorders the control plane's shutdown sequence: after GracefulStop times out and Stop ends the remaining connections, serve now waits up to handlerExitGrace (5s) more for every agent-call handler — sync-stream exit path included — to return before it lets defer st.Close() close the store. This fixes a race where a sync handler's offline-mark write (SetSyncState in internal/gateway/sync.go, unmodified by this diff) reached a closed pool.

ADRs checked

  • ADR-0002 (persistent streams, no polling in steady state, full-jitter backoff) — unaffected. No new polling is introduced; time.NewTimer(handlerExitGrace) is a one-shot local shutdown bound, not a control-plane poll, and reconnect/backoff behavior is untouched.
  • ADR-0017 (stateless replicas, Postgres as the only durable state, signing-key custody as the sole exception) — unaffected. The added wait is in-process and ephemeral (a goroutine and a channel), not durable state; nothing new is added to Postgres or held across restarts, consistent with "Nothing is added to the gateway. No new state, durable or in-process" in the PR description.
  • ADR-0023 (workload retirement; offline/sync-state semantics on the registry row) — unaffected. The change makes the existing offline mark land reliably on shutdown; it does not alter retirement's refusal paths, the stream-termination lever, or the registry schema.
  • ADR-0011 (agent fail-static, no self-update) — not implicated; this is control-plane shutdown sequencing, not agent code.
  • ADR-0015 (wire contract) — no proto or wire-contract change; the fix is purely in serve's goroutine sequencing.
  • ADR-0014 / README.md doc rules — the docs/reference/innerwall-cli.md update describing the new ~15s shutdown bound matches the code change (10s shutdownGrace + 5s handlerExitGrace), and the CHANGELOG entry accurately describes the before/after behavior without comparisons to other products or origin-story references.

Other checks

  • No ORM/query-builder/runtime SQL, no Makefile logic, no operator-handler domain logic, no certificate or label-grammar changes, no generated-file edits.
  • No dangling references: the new code/doc comments cite issue #113 (a plain tracker ID, permitted) and no ADR number; no new ADR or heading reference was introduced that doesn't exist.
  • No document is left inconsistent with the record it belongs to: ARCHITECTURE.md does not describe shutdown sequencing today and this PR doesn't claim it does; the one reference doc that does describe the sequence (docs/reference/innerwall-cli.md) was updated in the same diff to match.

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.

gateway: store pool closes before sync handlers finish on shutdown — "marking workload offline" fails with closed pool

2 participants