Skip to content

feat(node)!: drain running views on shutdown - #2417

Merged
mbrandenburger merged 4 commits into
hyperledger-labs:mainfrom
mbrandenburger:feat/2410-drain-on-shutdown
Nov 1, 2026
Merged

mbrandenburger merged 4 commits into
hyperledger-labs:mainfrom
mbrandenburger:feat/2410-drain-on-shutdown

Conversation

@mbrandenburger

@mbrandenburger mbrandenburger commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

Fixes #2410.

Problem

Node.Stop cancelled a context and returned at once. The web, gRPC and operations servers and the KVS stopped in one goroutine, the Fabric network provider in another, the comm service in a third, and nothing ordered them, so the KVS could close under a component still using it. /readyz did not change while the node stopped, so a load balancer kept sending traffic, and running views and view-API calls were cut off. Proof tests on main (since replaced by the tests in this PR) showed that Node.Stop returned before any SDK tore down, that no SDK's Stop() was ever called, and that a second SDK's teardown found the KVS closed.

Changes

Order (pkg/node, node/start)

  • Node.Stop drains through the node.Drainer in the node registry (fsc.shutdown.drainTimeout, default 30s, logging every 5s), cancels the node context, then calls Stop() on every SDK in reverse install order (fsc.shutdown.teardownTimeout, default 30s) and logs the total time.
  • A second Stop or signal skips the rest of the drain. node start uses its own signal.Notify channel, because signal.NotifyContext reports only the first signal.

Running views (platform/view/services/view)

  • The view manager implements Drain, Draining, Track, TryTrack, OnDrain and IsParty. It counts InitiateView and its variants, view-API commands from the moment the gate admits them, and responders from the moment the P2P service admits them. TryTrack checks for a drain and counts in one step, so a drain that starts concurrently either refuses new work or waits for it. While draining it logs every 5s how many views still run. A count with an idle channel replaces a sync.WaitGroup, which panicked when a view started while Drain waited (a stress test reproduced it).
  • Every initiator context follows one shutdown context of the manager through context.AfterFunc. At the deadline Drain cancels it with view.ErrCancelledByShutdown and waits at most one more second, so the view service still answers the cancelled views before the servers stop. DeleteContext only unregisters a context and does not cancel it, so work a view leaves running keeps its caller's context. The returned error joins ErrCancelledByShutdown with the view's own error.
  • New gauge fsc_shutdown_draining.

Readiness and refusing new work (platform/view/sdk/dig, web/server, p2p, view API)

  • server.ReadinessGate and Readyz(m, gates...): 503 {"status":"not ready","reason":"draining"}. /healthz stays 200.
  • The fsc.grpc server enables its health service and turns NOT_SERVING when the drain starts (GRPCServer.SetNotServing).
  • A drainGate around the view service refuses new commands with Unavailable. A view cancelled by shutdown ends with Aborted. The HTTP binding maps them to 503 / close 1013 and 409 / close 1011 with the reason protos.AbortedByShutdownMessage. The Go HTTP client maps both back to gRPC statuses, for ProcessCommand and for streams.
  • The P2P service rejects a first message with draining: node is draining unless its sender already takes part in the responder context (p2p.DrainState, p2p.WithDrainState). The draining rejection uses the existing reject path and its per-peer bounds.

Teardown (platform/view/sdk/dig, platform/fabric/sdk/dig)

  • startServe returns a stop function. viewsdk.SDK.Stop stops the servers, then comm, then the KVS. Comm runs on a context of its own that only Stop ends, so responders cancelled with the node context can still reply. The exported Serve keeps its signature and behaviour.
  • The Fabric SDK stops its network provider in Stop() and then calls the wrapped Stop(). Fabric-x needs no change: it embeds the Fabric SDK and its own providers only keep the context.

Failover (platform/view/services/comm)

  • New optional host.RetiringHost. The WebSocket multiplexed provider's Retire(peerID) moves the cached websockets to a peer out of the lookup map. Their open sub-connections keep working, KillAll still closes them, and the next stream dials again.
  • P2PNode retires the host's connections to a peer when one of its sessions gets a rejection (status ERROR, empty caller) starting with draining: .

Integration harness

  • fsc.Topology.Shutdown renders fsc.shutdown into every test node (5s drain, 10s teardown), so existing suites keep stopping well within StopEventuallyTimeout.

Deviations from the issue

  • No Drainer type assertion on SDKs. Every wrapper SDK embeds the commondig.SDK interface, among them Panurus's token/sdk/dig.SDK, Fabric-x, vfsdk and the libp2p support SDK. Go promotes only the interface's methods through such an embedding, so Drain on the Fabric SDK would never reach pkg/node and the drain would silently not happen on a Panurus node. pkg/node looks the Drainer up in the registry instead, where the view manager already is. No SDK has to implement or pass anything through.
  • Drain hook stays a registry lookup; the fsc-drainers dig group is left to Version every FSC store and add the migrate command #2412. As discussed in the #2410 comment, the group needs pkg/node to reach the dig container, the same mechanism StoreOpener needs, so it is designed there once. The registry lookup already drains nested SDKs without a pass-through. It takes the first Drainer only, which is enough while the view manager is the only one.
  • Retire the websocket instead of dropStreams. StreamHash includes the session and context IDs, so a new session never reuses a cached P2P stream. On WebSocket, the only transport with replicas, a new stream is a sub-connection of the cached websocket to the same replica, so dropping streams would not fail over. Retiring the websocket does.
  • Metric fsc_shutdown_draining, not fsc_draining. The Prometheus provider derives an empty subsystem from the package path. Changing that rule would rename any metric that sets only a namespace, so the gauge sets subsystem shutdown explicitly.
  • No admit function. fix(view): reply to unknown views without loops #2415 merged the admission checks inline in dispatch; the draining check is a branch there.
  • Health service comes from the existing HealthCheckEnabled of commongrpc rather than a second health.NewServer().
  • Not added: the integration spec "returns Aborted for a view cancelled after it submitted". It needs drainTimeout: 2s on the replicated network that every spec of that Describe shares. The Aborted path is covered by unit tests (TestManagerDrain_CancelsInitiatorsAtDeadline, TestProcessCommandAborted, TestProcessCommandHandlerDrainStatuses).

Breaking changes

  • A view-API call whose view the shutdown cancelled ends with gRPC Aborted (HTTP 409, WebSocket close 1011 with the reason) rather than an error response. Clients that read only CommandResponse.err see a call error instead. The Go client reports it as a status error on both transports.
  • The fsc.grpc listener always registers grpc.health.v1.Health. An embedder that registers it on that listener itself must stop: gRPC reports the duplicate registration through grpclog.Fatalf, so the process exits at startup. No exported Go signature changes. New exported names: node.Drainer, view.ErrCancelledByShutdown, Manager.Drain/Draining/Track/TryTrack/OnDrain/IsParty, p2p.DrainState, p2p.WithDrainState, p2p.DrainingPrefix, comm.DrainingPrefix, server.ReadinessGate, viewsdk.ErrDraining, viewgrpcserver.ErrAbortedByShutdown, protos.AbortedByShutdownMessage, host.RetiringHost, MultiplexedProvider.Retire, GRPCServer.SetNotServing.

Panurus

Checked against LFDT-Panurus/panurus main: its token SDK embeds dig2.SDK, so the registry lookup finds the drain, and its existing Stop() (drift-check sweepers, then p.SDK.Stop()) now runs at shutdown in the right order. It constructs neither view.Metrics nor view.Manager directly and uses no changed signature.

Behaviour worth reviewing

  • A peer that knows a context ID but has not joined it is refused while draining, as the issue requires. A third party that an initiator asks to contact this node in the middle of a protocol during the drain is therefore refused.
  • Views the application starts itself with InitiateView during the drain are not refused; they run and are waited for.
  • A Stop() still running at the teardown timeout is logged and left running. teardownTimeout: 0 returns while the SDKs, the KVS included, still stop.
  • The fsc.grpc listener always serves grpc.health.v1.Health; an application that registers it there itself exits at startup, because gRPC reports the duplicate registration as fatal.
  • drainTimeout should cover the longest view, typically the finality timeout. With the defaults Node.Stop may block up to 60s; Kubernetes needs terminationGracePeriodSeconds >= preStop + drainTimeout + teardownTimeout + 5s.

Tests

  • go test -race over every package of the root module passes.
  • make integration-tests-fsc-stoprestart passes 4/4, with the new spec "finishes a running view when its responder stops gracefully" on WebSocket and libp2p.
  • make integration-tests-fabric-faultrecovery-replication passes 9/9, with the new spec "keeps committing through a rolling restart of one replica" (every committed tx settles on both replicas, at most one failed submission per restart).
  • make checks (golangci-lint and go fix) clean.
  • Not run locally: fabric-faultrecovery, fabric-faultrecovery-postgres-outage, fabricx-faultrecovery.

Docs

New docs/platform/view/services/shutdown.md (order, clients, peers, load balancers, Kubernetes manifest, SDK authors). Updated docs/configuration.md (fsc.shutdown, /readyz, health service), view-service-http.md (503, 409, 1013), monitoring_metrics.md, comm/readme.md (draining and the redial), docs/agents/architecture.md (lifecycle) and docs/upgrade/v0.26-to-v0.27.md.

On SIGTERM, SIGINT or `Node.Stop` a node now lets running views finish before it stops, and stops its components in an order where none outlives what it uses. Before, `Node.Stop` cancelled a context and returned, and the web, gRPC and operations servers, the KVS, the Fabric network provider and the comm service each tore down in a goroutine of their own, so the KVS could close under a component still using it.

The shutdown runs in four steps:
- Drain. `/readyz` answers 503 with reason `draining`, the gRPC health service reports `NOT_SERVING` and `fsc_shutdown_draining` is 1. A new view-API command gets gRPC `Unavailable` (HTTP 503, WebSocket close 1013). A new P2P protocol gets `draining: node is draining`, unless the sender already takes part in the responder context it names.
- Wait for running views, for at most `fsc.shutdown.drainTimeout` (default 30s). At the deadline, initiator views still running are cancelled with `view.ErrCancelledByShutdown`, which the view API returns as gRPC `Aborted` (HTTP 409), since such a view may have submitted a transaction that still commits.
- Cancel the node context.
- Call `Stop()` on every SDK in reverse install order, within `fsc.shutdown.teardownTimeout` (default 30s). The Fabric SDK stops its networks, then the view SDK stops its servers, the comm service and the KVS.

A second signal or `Stop` call skips the rest of the drain.

`pkg/node` finds the drain as a `node.Drainer` in the node's registry, where the view SDK registers the view manager. Wrapper SDKs embed the `commondig.SDK` interface, so a method on the SDK itself would not reach `pkg/node` through them. No method is added to an SDK interface.

The view manager counts initiator views, views the view service runs and responders from the moment the P2P service admits their first message.

An initiator whose session gets a `draining: ` reply retires its cached WebSocket connections to that peer through the new optional `host.RetiringHost`. Open sessions keep their connection, and the next session dials again, so a load balancer can route it to another replica.

Breaking for view-API clients: a view cancelled by shutdown ends the call with gRPC `Aborted` (HTTP 409) rather than an error response. The Go client reports it as a status error on both transports.

docs/platform/view/services/shutdown.md describes the order, what clients and peers see, load balancers and Kubernetes settings. docs/upgrade/v0.26-to-v0.27.md lists the operator and developer changes.

Fixes hyperledger-labs#2410

Signed-off-by: Marcus Brandenburger <bur@zurich.ibm.com>
@github-actions

github-actions Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Hey @mbrandenburger 👋 thanks for the PR!
I'm your friendly PR Helper Bot 🤖 and I'll be riding shotgun on this one, keeping track of your PR's status to help you get it approved and merged.

This comment updates automatically as you push changes -- think of it as your PR's live scoreboard!
Here's the latest:


PR Checks

✅ DCO Sign-off -- All commits have valid sign-offs. Nice work!


❌ GPG Signature -- Heads up! The following commits don't have a verified GPG signature:

  • 25e432a feat(node)!: drain running views on shutdown
  • b5ae1e8 fixup! feat(node)!: drain running views on shutdown
  • 05fb909 fixup! feat(node)!: drain running views on shutdown
  • 8cdc881 amend! feat(node)!: drain running views on shutdown

You'll need to sign your commits with GPG (e.g. git commit -S). See the Signing Guide for a step-by-step walkthrough.


✅ Merge Conflicts -- No merge conflicts detected. Smooth sailing!


✅ Issue Link -- Linked to #2410 (assigned to you).


⏳ All checks must pass before this PR can be reviewed. You've got this!

@github-actions github-actions Bot added the status: needs revision The pull request requires changes from the author before it can be reviewed or merged label Oct 30, 2026
@mbrandenburger mbrandenburger added this to the 26Q4 milestone Oct 30, 2026
Signed-off-by: Marcus Brandenburger <bur@zurich.ibm.com>
Signed-off-by: Marcus Brandenburger <bur@zurich.ibm.com>

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

thank you @mbrandenburger , i have left a comment

Comment on lines +385 to +386
// The SDK reports NOT_SERVING while the node drains.
HealthCheckEnabled: 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.

HealthCheckEnabled: true here means fsc.grpc always registers grpc.health.v1.Health. That is the right default for the drain, but it is a second breaking change for embedders, and the commit body's "Breaking" paragraph mentions only the Aborted change — could you add it there too, since that text becomes the release note?

Also, the upgrade guide says a second registration "panics at startup". It is actually worse: gRPC reports duplicate registration through grpclog.Fatalf, so the process exits and the app cannot recover or defer around it:

FATA [grpc] [core] grpc: Server.RegisterService found duplicate service registration for "grpc.health.v1.Health"

Suggest "exits at startup" rather than "panics at startup" in docs/upgrade/v0.26-to-v0.27.md and docs/configuration.md, so readers don't plan to recover from it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good catch, updated.

@SaidAltury-ibm
SaidAltury-ibm self-requested a review November 1, 2026 09:08

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

see my comment

feat(node)!: drain running views on shutdown

On SIGTERM, SIGINT or `Node.Stop` a node now lets running views finish before it stops, and stops its components in an order where none outlives what it uses. Before, `Node.Stop` cancelled a context and returned, and the web, gRPC and operations servers, the KVS, the Fabric network provider and the comm service each tore down in a goroutine of their own, so the KVS could close under a component still using it.

The shutdown runs in four steps:
- Drain. `/readyz` answers 503 with reason `draining`, the gRPC health service reports `NOT_SERVING` and `fsc_shutdown_draining` is 1. A new view-API command gets gRPC `Unavailable` (HTTP 503, WebSocket close 1013). A new P2P protocol gets `draining: node is draining`, unless the sender already takes part in the responder context it names.
- Wait for running views, for at most `fsc.shutdown.drainTimeout` (default 30s). At the deadline, initiator views still running are cancelled with `view.ErrCancelledByShutdown`, which the view API returns as gRPC `Aborted` (HTTP 409), since such a view may have submitted a transaction that still commits.
- Cancel the node context.
- Call `Stop()` on every SDK in reverse install order, within `fsc.shutdown.teardownTimeout` (default 30s). The Fabric SDK stops its networks, then the view SDK stops its servers, the comm service and the KVS.

A second signal or `Stop` call skips the rest of the drain.

`pkg/node` finds the drain as a `node.Drainer` in the node's registry, where the view SDK registers the view manager. Wrapper SDKs embed the `commondig.SDK` interface, so a method on the SDK itself would not reach `pkg/node` through them. No method is added to an SDK interface.

The view manager counts initiator views, view-API commands and responders from the moment they are admitted, checking for a drain and counting in one step. A view's context is cancelled only at the drain deadline, not when the view returns. The comm service runs until the view SDK's `Stop`, after the servers, so responders cancelled with the node context can still reply.

An initiator whose session gets a `draining: ` reply retires its cached WebSocket connections to that peer through the new optional `host.RetiringHost`. Open sessions keep their connection, and the next session dials again, so a load balancer can route it to another replica.

Breaking changes:
- View-API clients: a view cancelled by shutdown ends the call with gRPC `Aborted` (HTTP 409, WebSocket close 1011) rather than an error response. The Go client reports it as a status error on both transports.
- Embedders: the `fsc.grpc` listener always registers the gRPC health service (`grpc.health.v1.Health`), which reports `NOT_SERVING` while the node drains. An application that registers it on that listener itself must stop: gRPC reports the duplicate registration as fatal and the process exits at startup.

docs/platform/view/services/shutdown.md describes the order, what clients and peers see, load balancers and Kubernetes settings. docs/upgrade/v0.26-to-v0.27.md lists the operator and developer changes.

Fixes hyperledger-labs#2410

Signed-off-by: Marcus Brandenburger <bur@zurich.ibm.com>
@mbrandenburger
mbrandenburger enabled auto-merge (squash) November 1, 2026 09:17
@mergify

mergify Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

@mbrandenburger
mbrandenburger merged commit 539b146 into hyperledger-labs:main Nov 1, 2026
@mbrandenburger
mbrandenburger deleted the feat/2410-drain-on-shutdown branch November 1, 2026 09:19
mbrandenburger added a commit to mbrandenburger/fabric-smart-client that referenced this pull request Nov 5, 2026
v0.27.0 is tagged at hyperledger-labs#2415, so everything merged after it ships in v0.28.0. The drain on shutdown (hyperledger-labs#2417) merged after the tag but was documented in the v0.26 to v0.27 guide; its operator section, metric, developer note and checklist rows move to the v0.27 to v0.28 guide, and the v0.26 to v0.27 guide is back to its state at the tag.

The v0.27 to v0.28 guide gains what it left out:
- the view service symbols removed in hyperledger-labs#2426
- the websocket keepalive (hyperledger-labs#2428)
- channel keys on transactions sent between nodes and their routing to the local network, with driver.Channel.ChannelKey, RequireChannelKey and NewTransactionFromEnvelopeBytesOn (hyperledger-labs#2466)
- Fabric-x proposal responses without namespaces being refused, and session IDs kept apart per sender (hyperledger-labs#2419)
- views that stop waiting for a reply when their context ends, and session.ReadMessageWithContext (hyperledger-labs#2471)
- the vault keeping a Valid status on a Busy write (hyperledger-labs#2420)
- node migrate --forget-opener, exit 12 with --check --contract, which stores node migrate reaches, and the limits of queryTimeout and migrationLockTimeout

It also corrects claims that did not match the code: which endorse transactions stay JSON after the contract step (keyless Fabric rows convert), that stores keep bytes they cannot convert, gob metadata the protobuf form cannot carry, SQLite locking during a step, the error a recipient responder without a signer sends, how nwo starts nodes, the connection state component on Fabric-x, and the default channel RequestRecipientIdentity verifies on. Fabric-only and Fabric-x-only items are marked as such, and the warning about new stores during a mixed-version window is stated once.

Signed-off-by: Marcus Brandenburger <bur@zurich.ibm.com>
mbrandenburger added a commit that referenced this pull request Nov 5, 2026
v0.27.0 is tagged at #2415, so everything merged after it ships in v0.28.0. The drain on shutdown (#2417) merged after the tag but was documented in the v0.26 to v0.27 guide; its operator section, metric, developer note and checklist rows move to the v0.27 to v0.28 guide, and the v0.26 to v0.27 guide is back to its state at the tag.

The v0.27 to v0.28 guide gains what it left out:
- the view service symbols removed in #2426
- the websocket keepalive (#2428)
- channel keys on transactions sent between nodes and their routing to the local network, with driver.Channel.ChannelKey, RequireChannelKey and NewTransactionFromEnvelopeBytesOn (#2466)
- Fabric-x proposal responses without namespaces being refused, and session IDs kept apart per sender (#2419)
- views that stop waiting for a reply when their context ends, and session.ReadMessageWithContext (#2471)
- the vault keeping a Valid status on a Busy write (#2420)
- node migrate --forget-opener, exit 12 with --check --contract, which stores node migrate reaches, and the limits of queryTimeout and migrationLockTimeout

It also corrects claims that did not match the code: which endorse transactions stay JSON after the contract step (keyless Fabric rows convert), that stores keep bytes they cannot convert, gob metadata the protobuf form cannot carry, SQLite locking during a step, the error a recipient responder without a signer sends, how nwo starts nodes, the connection state component on Fabric-x, and the default channel RequestRecipientIdentity verifies on. Fabric-only and Fabric-x-only items are marked as such, and the warning about new stores during a mixed-version window is stated once.

Signed-off-by: Marcus Brandenburger <bur@zurich.ibm.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

breaking status: needs revision The pull request requires changes from the author before it can be reviewed or merged

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Drain running views on shutdown and stop components in order

2 participants