From dabb247a9cf52fba842c8125bdc47263655d8add Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Mon, 26 Oct 2026 13:30:14 -0400 Subject: [PATCH] feat(fabric-api): Bound Looking Glass delivery and stop stalled streams A Looking Glass consumer that stopped reading could hold a request's execution indefinitely. Each event went to stream.Send from the handler goroutine, and gRPC flow control blocks that call until the client reads, so the handler never returned, finished router outcomes waited for it without a bound, and the request's live stream and queue reservation stayed held. A follower relaying for the leader had the same unbounded Send. Nothing capped a stream's output, the gateway listener had no keepalive, no per-replica call or connection cap and a window that grows with bandwidth-delay estimation, and a shutdown signal left service streams running until the manager exited. Every stream now has one writer goroutine. The handler waits at most 2 s for each write and a finished outcome waits at most 2 s for the stream's two-outcome buffer; past either, the request is cancelled and the handler returns CANCELLED. Returning resets the stream, which ends the blocked Send, so the write is aborted at the transport rather than only timed at the producer. A follower relays one event at a time through the same writer and never forwards a call twice. An outcome over 144 KiB is delivered as a ResponseTooLarge failure. The stream keeps 64 KiB for its complete event and 1 KiB for each router still to report; once an outcome does not fit the 5 MiB budget, that router and every router still running fail with the new OutputLimitExceeded code, which also becomes the terminal reason, so every selected router still has exactly one outcome. Each replica refuses RunDiagnostic calls beyond 32 and forwarded calls beyond 16 with QueueFull and a 1 s retry delay, and closes a service identity's connection beyond 64 after its handshake. The listener and a follower's connection to the leader use fixed 64 KiB windows and buffers. Server keepalive pings a silent peer after 4 s and closes it 4 s later, so a blackholed client's work is cancelled within 10 s. A shutdown signal stops the gRPC server at once, cancelling service and operator calls in flight. Tests measure each bound against the contract: a stalled consumer on the leader and through a follower releases its routers, queue, reservation and stream about 2 s after its write blocks; a slow hand-off cancels the request; cancellation during discovery, while queued and while executing releases everything within 2 s; stopping the server and a blackholed connection cancel running routers; 16 streams of maximum-size outcomes stay within 5 MiB each and a bounded number of goroutines; a lost forwarded stream is not forwarded again and runs no router twice; a gateway replaced as lease holder dispatches nothing new; and the call and connection caps refuse and free slots. The stalled-consumer test hangs without this change. Service disable remains a startup setting; its runtime control, metrics and packaged configuration are left to #1047. Fixes #1046 --- cmd/fabric-api/gateway.go | 4 + docs/agents/ARCHITECTURE-FABRIC-API.md | 3 +- docs/fabric-api/configuration.md | 21 + docs/fabric-api/service-contract.md | 14 +- internal/fabric/errcode/errcode.go | 4 + internal/fabric/gateway/debug.go | 2 +- internal/fabric/gateway/runner.go | 12 +- internal/fabric/gateway/service.go | 166 ++++-- internal/fabric/gateway/service_test.go | 17 +- internal/fabric/gateway/stream.go | 219 +++++++ internal/fabric/gateway/stream_test.go | 757 ++++++++++++++++++++++++ 11 files changed, 1166 insertions(+), 53 deletions(-) create mode 100644 internal/fabric/gateway/stream.go create mode 100644 internal/fabric/gateway/stream_test.go diff --git a/cmd/fabric-api/gateway.go b/cmd/fabric-api/gateway.go index ae2538495..139b7ceeb 100644 --- a/cmd/fabric-api/gateway.go +++ b/cmd/fabric-api/gateway.go @@ -303,6 +303,10 @@ func runGateway(parent context.Context, o *gatewayOptions) error { } }() defer gs.Stop() + // A shutdown signal closes every connection at once, so a service + // stream's routers stop within 2 s rather than running on while the + // manager shuts down. + defer context.AfterFunc(ctx, gs.Stop)() slog.Info("starting fabric-api gateway", "version", metadata.Version, "site", o.site, "cluster", o.clusterName, "cell", o.cell, "debug", debugAddr) diff --git a/docs/agents/ARCHITECTURE-FABRIC-API.md b/docs/agents/ARCHITECTURE-FABRIC-API.md index 9a08dafaa..d0885f530 100644 --- a/docs/agents/ARCHITECTURE-FABRIC-API.md +++ b/docs/agents/ARCHITECTURE-FABRIC-API.md @@ -443,7 +443,8 @@ manifest sets yet (see | `internal/fabric/gateway/limit` | `Limits` and `Validate`; `Buckets` (request and packet token buckets, never negative, key families bounded without evicting debt); `Attempts` (duplicate attempt keys, fail closed); `Authority` (uncached Lease check, epoch, 125 s recovery hold, `Watch`) | Buckets, attempt keys, epoch (memory) | | `internal/fabric/gateway` (`discovery.go`) | Pod snapshot with omission reasons, one pod per node, node budget, node-to-certs-pod mapping (`NoCertificatePod`); `Inventory`, the service's one-router-per-node snapshot (newest usable pod, `NotRequested`, `NoSidecar`, unscheduled count, 256-router cap) | No | | `internal/fabric/gateway` (`debug.go`) | Operator debug service, leader forwarding through the election lease | Connection to the leader | -| `internal/fabric/gateway` (`service.go`) | `NewServer`, service `Allowlist`, Looking Glass service authorization and attribution validation, one-hop typed forwarding to the leader, capabilities, and (when `Enabled`) streamed execution with terminal coverage | No | +| `internal/fabric/gateway` (`service.go`) | `NewServer`, service `Allowlist`, Looking Glass service authorization and attribution validation, one-hop typed forwarding to the leader, capabilities, and (when `Enabled`) streamed execution with terminal coverage and its output budget | No | +| `internal/fabric/gateway` (`stream.go`) | Delivery and transport bounds: the single stream writer with its 2 s write bound, per-replica call and service connection caps, fixed windows and keepalive on the listener and the follower's leader connection | No | | `internal/fabric/gateway` (`janitor.go`) | `Janitor.Sweep`, `StaleCounter` | No | | `internal/fabric/gateway` (`metrics.go`) | `fabric_api_gateway_*` and shared `fabric_api_*` collectors | Prometheus collectors | | `internal/fabric/api/v1alpha1` | `FabricQuery` Go types with kubebuilder markers, condition and reason constants, request labels | No | diff --git a/docs/fabric-api/configuration.md b/docs/fabric-api/configuration.md index d69eafd85..d1e938dfc 100644 --- a/docs/fabric-api/configuration.md +++ b/docs/fabric-api/configuration.md @@ -775,6 +775,27 @@ until the job's deadline plus 2 seconds, since the node may still be sending it. The rates and caps are the contract's defaults; only `--cell-slots` and `--cell-queue` change them. +### Stream delivery and transport bounds + +Every gateway replica bounds Looking Glass service delivery, whether or not +`--aggregate-budgets` is set. None of these values is configurable: + +| Bound | Value | Past it | +| -------------------------------------------------------------------------------------------- | ---------------------------------- | ----------------------------------------------------------------------------------------- | +| One write to the consumer, or a finished outcome waiting for the stream's two-outcome buffer | 2 s | The request is cancelled and its stream ends `CANCELLED`; its routers stop | +| One outcome event | 144 KiB | The router's outcome is a `ResponseTooLarge` failure | +| Serialized events of one stream | 5 MiB | That router and every router still running fail `OutputLimitExceeded`, as does `complete` | +| `RunDiagnostic` calls / forwarded calls | 32 / 16 per replica | `QueueFull` with a 1 s retry delay | +| Service identity TLS connections | 64 per replica | The connection is closed after its handshake | +| A silent connection | Pinged after 4 s, closed 4 s later | Its calls are cancelled | + +Every connection to the listener, and a follower's connection to the leader, +uses fixed 64 KiB flow-control windows and buffers. A follower relays one event +at a time under the same 2 s write bound, and never forwards a call twice. A +client may ping no more often than every 5 seconds. On `SIGTERM` the gateway +closes its listener's connections at once, cancelling operator and service +calls in flight. + ### Enabling The deployment manifests do not set these flags yet. Turn them on in this diff --git a/docs/fabric-api/service-contract.md b/docs/fabric-api/service-contract.md index 337272ceb..25c76cf27 100644 --- a/docs/fabric-api/service-contract.md +++ b/docs/fabric-api/service-contract.md @@ -40,10 +40,16 @@ requires the gateway's admission, and capabilities advertise `aggregate-probe-budgets` only while execution is enabled with it. Nodes charge direct operator probes only with `--require-probe-permits`, so enabling execution requires every node to run with it. No deployment sets `Enabled` or -these flags, so a valid `RunDiagnostic` is answered with `ServiceDisabled`. Not yet implemented: the blocked-send bound and -stream-level ownership rules of #1046, and the metrics and packaged -configuration of #1047. Operator and FabricQuery discovery still return pod -candidates, including duplicates. +these flags, so a valid `RunDiagnostic` is answered with `ServiceDisabled`. +The delivery and transport bounds under "Cancellation, delivery, and failure +assumptions" are enforced (#1046): one writer per stream, the 2 s write and +hand-off bound on the leader and on a forwarding follower, the per-outcome and +per-stream output caps, the per-replica call and service connection caps, +fixed 64 KiB windows and buffers, and keepalive on the gateway listener +(`internal/fabric/gateway/stream.go`). A shutdown signal stops the listener at +once. Service disable is a startup setting until #1047 adds its controls, and +the metrics and packaged configuration are #1047's. Operator and FabricQuery +discovery still return pod candidates, including duplicates. ## Service and identity diff --git a/internal/fabric/errcode/errcode.go b/internal/fabric/errcode/errcode.go index 60afbed02..ed28fbac5 100644 --- a/internal/fabric/errcode/errcode.go +++ b/internal/fabric/errcode/errcode.go @@ -96,6 +96,9 @@ const ( // DuplicateRequest means a request ID was reused with identical // arguments; it is never answered with a saved result. DuplicateRequest Code = "DuplicateRequest" + // OutputLimitExceeded means a Looking Glass service stream's output + // budget cannot hold another router's result. + OutputLimitExceeded Code = "OutputLimitExceeded" ) // grpcCodes maps each code to the gRPC status code it travels as. @@ -128,6 +131,7 @@ var grpcCodes = map[Code]codes.Code{ QueueFull: codes.ResourceExhausted, LimiterUnavailable: codes.Unavailable, DuplicateRequest: codes.AlreadyExists, + OutputLimitExceeded: codes.ResourceExhausted, } // MetadataQueryCode is the ErrorInfo metadata key carrying the query diff --git a/internal/fabric/gateway/debug.go b/internal/fabric/gateway/debug.go index 64c9ea59f..7979f78de 100644 --- a/internal/fabric/gateway/debug.go +++ b/internal/fabric/gateway/debug.go @@ -207,7 +207,7 @@ func (d *Debug) conn(addr string) (*grpc.ClientConn, error) { // A forwarded call may already have run on the leader, so it is // never replayed, not even transparently. grpc.WithDisableRetry(), - }, d.DialOptions...) + }, append(leaderDialOptions(), d.DialOptions...)...) c, err := grpc.NewClient(addr, opts...) if err != nil { return nil, err diff --git a/internal/fabric/gateway/runner.go b/internal/fabric/gateway/runner.go index 341936901..621286e20 100644 --- a/internal/fabric/gateway/runner.go +++ b/internal/fabric/gateway/runner.go @@ -238,21 +238,29 @@ func (r *Runner) fanOut(ctx context.Context, project, requestID string, q query. // cancelled when the gateway loses the election. var errOwnershipLost = errors.New("the gateway lost execution ownership") +// errOutputLimit is the cause with which a service request's execution is +// cancelled when its stream's output budget runs out. +var errOutputLimit = errors.New("the stream's output budget is exhausted") + // requestErr reports a failure that ctx's end, or the request's expiration, // caused as the request's own DeadlineExceeded, Cancelled or, when the -// election was lost, OwnershipLost. +// election was lost or the output budget ran out, OwnershipLost or +// OutputLimitExceeded. func requestErr(ctx context.Context, err error, expired bool) error { if err == nil || (ctx.Err() == nil && !expired) { return err } switch errcode.Of(err) { - case errcode.Timeout, errcode.NodeUnreachable, errcode.QueueTimeout: + case errcode.Timeout, errcode.NodeUnreachable, errcode.QueueTimeout, errcode.Cancelled: default: return err } if errors.Is(context.Cause(ctx), errOwnershipLost) { return errcode.Status(errcode.OwnershipLost, "the gateway lost execution ownership before the router finished") } + if errors.Is(context.Cause(ctx), errOutputLimit) { + return errcode.Status(errcode.OutputLimitExceeded, "the stream's output budget ran out before the router finished") + } if expired || errors.Is(ctx.Err(), context.DeadlineExceeded) { return errcode.Status(errcode.DeadlineExceeded, "the request's deadline passed before the router finished") } diff --git a/internal/fabric/gateway/service.go b/internal/fabric/gateway/service.go index 235b7c3ef..df7bbf392 100644 --- a/internal/fabric/gateway/service.go +++ b/internal/fabric/gateway/service.go @@ -52,6 +52,16 @@ const ( // outcomeBuffer is how many finished router outcomes may wait for the // stream's writer. outcomeBuffer = 2 + // maxOutcomeBytes bounds one serialized outcome event; a larger result + // is delivered as a ResponseTooLarge failure. + maxOutcomeBytes = 144 << 10 + // maxCompleteBytes is the output reserved for the terminal event. + maxCompleteBytes = 64 << 10 + // failureReserve is the output reserved for each router still to + // report, enough for its failure outcome. + failureReserve = 1 << 10 + // MaxStreamBytes bounds the serialized events of one stream. + MaxStreamBytes = 5 << 20 ) // Service feature names, as GetCapabilities advertises and a request's @@ -182,17 +192,18 @@ func (s *contextStream) Context() context.Context { return s.ctx } // gateway-only forwarding service on one mTLS listener. Every call, unary or streaming, is authorized per role from // GatewayMethods against a peer certificate re-verified on that call, bounded // by the certificate's expiry, and stripped of forwarding metadata unless -// the gateway identity sent it. opts are appended. +// the gateway identity sent it. Connections, windows and concurrent +// diagnostic calls are bounded per replica (see transportOptions and +// rpcCaps). opts are appended. func NewServer( creds *identity.Credentials, allowlist Allowlist, debug *Debug, service *Service, permits *Permits, opts ...grpc.ServerOption, ) *grpc.Server { auth := &node.Authorizer{Methods: GatewayMethods, Credentials: creds, Allow: allowlist.Check} - gs := grpc.NewServer(append([]grpc.ServerOption{ - grpc.Creds(credentials.NewTLS(creds.ServerConfig(allowlist.Handshake))), + gs := grpc.NewServer(append(append(transportOptions(credentials.NewTLS(creds.ServerConfig(allowlist.Handshake))), grpc.ChainUnaryInterceptor(auth.Unary(), StripForwardingUnary), - grpc.ChainStreamInterceptor(auth.Stream(), StripForwardingStream), - }, opts...)...) + grpc.ChainStreamInterceptor(auth.Stream(), StripForwardingStream, newRPCCaps().stream), + ), opts...)...) fabricv1.RegisterFabricGatewayServiceServer(gs, debug) servicev1.RegisterLookingGlassServiceServer(gs, service) forwardv1.RegisterForwardServiceServer(gs, service.Forwarder()) @@ -234,6 +245,9 @@ type Service struct { Leader LeaderDialer // Now, when set, replaces the wall clock. Now func() time.Time + + // outputLimit, when positive, replaces MaxStreamBytes. + outputLimit int } func (s *Service) now() time.Time { @@ -527,7 +541,8 @@ func checkFeatures(required, served []string) error { } // forward hands a validated request to the leader once, with this replica's -// gateway identity, and relays its events. +// gateway identity, and relays its events under the same write bound as the +// leader's. A forwarded call that fails is never forwarded again. func (s *Service) forward( ctx context.Context, caller identity.ID, req *servicev1.RunDiagnosticRequest, received, deadline time.Time, stream grpc.ServerStreamingServer[servicev1.DiagnosticEvent], @@ -550,18 +565,12 @@ func (s *Service) forward( if err != nil { return err } - for { - ev, err := events.Recv() - if errors.Is(err, io.EOF) { - return nil - } - if err != nil { - return err - } - if err := stream.Send(ev); err != nil { - return err - } + w := newEventWriter(stream.Send) + defer w.close() + if err := relay(events.Recv, w); !errors.Is(err, io.EOF) { + return err } + return nil } // execute runs a validated request on the leader and sends its events: one @@ -570,12 +579,18 @@ func (s *Service) forward( // discovery it confirms the election, charges the cell's and the project's // request tokens, registers the attempt key and opens a live stream; after // discovery it reserves queue capacity for every selected router at once, -// before the snapshot is sent. Events are sent by this goroutine alone; -// finished outcomes wait for it in a buffer of outcomeBuffer, and a failed -// send or the loss of the election cancels every router still running. A -// failure before the snapshot is returned as the call's status; once the -// snapshot is sent the stream ends with complete and status OK, whatever -// the diagnostic's own result. +// before the snapshot is sent. Events are written by one writer; finished +// outcomes wait for it in a buffer of outcomeBuffer. A failed write, or a +// write or a hand-off to the buffer blocked for SendBound, cancels every +// router still running and ends the stream without complete; the deadline, +// the loss of the election and the output budget cancel them too, but the +// stream still ends with complete. An outcome larger than +// maxOutcomeBytes is delivered as a ResponseTooLarge failure, and once the +// stream's output budget cannot hold an outcome, that router and every +// router still running fail with OutputLimitExceeded. A failure before the +// snapshot is returned as the call's status; once the snapshot is sent the +// stream ends with complete and status OK, whatever the diagnostic's own +// result. func (s *Service) execute( ctx context.Context, caller identity.ID, req *servicev1.RunDiagnosticRequest, deadline time.Time, send func(*servicev1.DiagnosticEvent) error, @@ -605,12 +620,12 @@ func (s *Service) execute( } defer closeStream() - // sendCtx ends when the stream does or a send fails; runCtx also ends - // at the deadline or when the election is lost. Outcomes a deadline or - // the loss cuts short still reach the writer, so the consumer can see - // them while the stream lasts. - sendCtx, abort := context.WithCancel(ctx) - defer abort() + // sendCtx ends when the stream does, a write fails or the consumer + // stalls; runCtx also ends at the deadline, when the election is lost or + // when the output budget runs out. Outcomes those cut short still reach + // the writer, so the consumer can see them while the stream lasts. + sendCtx, abort := context.WithCancelCause(ctx) + defer abort(nil) ownedCtx, lose := context.WithCancelCause(sendCtx) defer lose(nil) defer context.AfterFunc(epochCtx, func() { lose(errOwnershipLost) })() @@ -642,11 +657,15 @@ func (s *Service) execute( string(limit.ScopeQueue), time.Second) } defer res.Release() + w := newEventWriter(send) + defer w.close() var seq uint64 + out := streamOutput{limit: s.streamLimit(), pending: selectedCount(inv.Routers)} next := func(ev *servicev1.DiagnosticEvent) error { seq++ ev.RequestId, ev.Sequence = req.GetRequestId(), seq - return send(ev) + out.used += proto.Size(ev) + return w.write(ev) } err = next(&servicev1.DiagnosticEvent{Event: &servicev1.DiagnosticEvent_Snapshot{Snapshot: snapshot}}) if err != nil { @@ -663,20 +682,49 @@ func (s *Service) execute( defer close(outcomes) s.Runner.Stream(runCtx, project, req.GetRequestId(), q, inv.Routers, budgets, deadline, res, func(o Outcome) { + t := time.NewTimer(SendBound) + defer t.Stop() select { case outcomes <- o: case <-sendCtx.Done(): + case <-t.C: + abort(errConsumerStalled) } }) }() + stop := func(err error) error { + abort(err) + for range outcomes { + } + return err + } + // ended ends the stream once sendCtx has: its consumer is gone or + // stalled, so no further event is written. + ended := func() error { + if errors.Is(context.Cause(sendCtx), errConsumerStalled) { + return stop(stalledStatus()) + } + return stop(errcode.Status(errcode.Cancelled, "the stream ended before the request finished")) + } var tally streamCoverage - for o := range outcomes { - tally.add(o) - if err := next(outcomeEvent(o)); err != nil { - abort() - for range outcomes { - } - return err + for { + if sendCtx.Err() != nil { + return ended() + } + var o Outcome + var ok bool + select { + case o, ok = <-outcomes: + case <-sendCtx.Done(): + return ended() + } + if !ok { + break + } + ev := out.fit(o, func() { lose(errOutputLimit) }) + tally.add(ev) + if err := next(outcomeEvent(ev)); err != nil { + return stop(err) } } return next(&servicev1.DiagnosticEvent{Event: &servicev1.DiagnosticEvent_Complete{ @@ -684,6 +732,37 @@ func (s *Service) execute( }}) } +func (s *Service) streamLimit() int { + if s.outputLimit > 0 { + return s.outputLimit + } + return MaxStreamBytes +} + +// streamOutput is a stream's output budget: bytes written so far, and the +// routers still to report, each of which keeps failureReserve of the budget, +// like the terminal event keeps maxCompleteBytes. +type streamOutput struct { + limit, used, pending int +} + +// fit returns o as it can be delivered: a result over maxOutcomeBytes as +// ResponseTooLarge, and a result the remaining budget cannot hold as +// OutputLimitExceeded, calling exhausted so the routers still running stop. +func (b *streamOutput) fit(o Outcome, exhausted func()) Outcome { + b.pending-- + size := proto.Size(outcomeEvent(o)) + if size > maxOutcomeBytes { + o.Observation, o.Err = nil, errcode.Status(errcode.ResponseTooLarge, "router's result exceeds its size bound") + size = proto.Size(outcomeEvent(o)) + } + if b.used+size+b.pending*failureReserve+maxCompleteBytes > b.limit { + exhausted() + o.Observation, o.Err = nil, errcode.Status(errcode.OutputLimitExceeded, "the stream's output budget is exhausted") + } + return o +} + func selectedCount(routers []Node) int { n := 0 for _, r := range routers { @@ -770,6 +849,10 @@ func failureMessage(code errcode.Code) string { return "the gateway lost execution ownership" case errcode.LimiterUnavailable: return "the cell's limiter is unavailable" + case errcode.ResponseTooLarge: + return "router's result exceeds its size bound" + case errcode.OutputLimitExceeded: + return "the stream's output budget is exhausted" } return "router diagnostic failed" } @@ -777,8 +860,8 @@ func failureMessage(code errcode.Code) string { // streamCoverage counts a stream's outcomes. type streamCoverage struct { successful, failed, truncated int - // stopped is the request-level reason, DeadlineExceeded, Cancelled or - // OwnershipLost, that cut a router short, if any. + // stopped is the request-level reason, DeadlineExceeded, Cancelled, + // OwnershipLost or OutputLimitExceeded, that cut a router short, if any. stopped errcode.Code } @@ -792,7 +875,7 @@ func (c *streamCoverage) add(o Outcome) { } c.failed++ switch code := errcode.Of(o.Err); code { - case errcode.DeadlineExceeded, errcode.Cancelled, errcode.OwnershipLost: + case errcode.DeadlineExceeded, errcode.Cancelled, errcode.OwnershipLost, errcode.OutputLimitExceeded: if c.stopped == "" { c.stopped = code } @@ -800,7 +883,8 @@ func (c *streamCoverage) add(o Outcome) { } // complete returns the terminal coverage. A request cut short by its -// deadline, cancellation or the loss of the election reports that first; otherwise no selected router +// deadline, cancellation, the loss of the election or its output budget +// reports that first; otherwise no selected router // is NoNodesAvailable, no success ExecutionFailed, and any failure, // truncation or omission other than NotRequested PartialResults. func (c *streamCoverage) complete(inv Inventory, now time.Time) *servicev1.Complete { diff --git a/internal/fabric/gateway/service_test.go b/internal/fabric/gateway/service_test.go index fb4a889c5..cd5e0c676 100644 --- a/internal/fabric/gateway/service_test.go +++ b/internal/fabric/gateway/service_test.go @@ -128,7 +128,16 @@ func elected() bool { return true } // serveFollower serves a gateway replica that does not lead and whose // election lease names the replica at leaderAddr, and returns its address. -func serveFollower(t *testing.T, creds *identity.Credentials, leaderAddr string) string { +// dial is added to its leader connection's options. +func serveFollower(t *testing.T, creds *identity.Credentials, leaderAddr string, dial ...grpc.DialOption) string { + t.Helper() + f := followerService(t, creds, leaderAddr, dial...) + return serveGateway(t, creds, f.Leader.(*Debug), f) +} + +// followerService is the service of a replica that does not lead and whose +// election lease names the replica at leaderAddr. +func followerService(t *testing.T, creds *identity.Credentials, leaderAddr string, dial ...grpc.DialOption) *Service { t.Helper() host, portStr, _ := net.SplitHostPort(leaderAddr) port, _ := strconv.Atoi(portStr) @@ -143,9 +152,9 @@ func serveFollower(t *testing.T, creds *identity.Credentials, leaderAddr string) ).Build() notElected := func() bool { return false } follower := &Debug{Elected: notElected, Reader: reader, Namespace: DefaultNamespace, - LeaseName: testLeaseName, PodName: "gw-follower", Port: port, Credentials: creds, Cell: testSite} - return serveGateway(t, creds, follower, - &Service{Cell: testSite, Allowlist: testAllowlist, Elected: notElected, Leader: follower}) + LeaseName: testLeaseName, PodName: "gw-follower", Port: port, Credentials: creds, Cell: testSite, + DialOptions: dial} + return &Service{Cell: testSite, Allowlist: testAllowlist, Elected: notElected, Leader: follower} } func TestServiceAuthorization(t *testing.T) { diff --git a/internal/fabric/gateway/stream.go b/internal/fabric/gateway/stream.go new file mode 100644 index 000000000..e966b9993 --- /dev/null +++ b/internal/fabric/gateway/stream.go @@ -0,0 +1,219 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package gateway + +import ( + "errors" + "net" + "sync" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/keepalive" + + forwardv1 "go.datum.net/galactic/api/fabric/forward/v1" + servicev1 "go.datum.net/galactic/api/fabric/service/v1" + "go.datum.net/galactic/internal/fabric/errcode" + "go.datum.net/galactic/internal/fabric/gateway/limit" + "go.datum.net/galactic/internal/fabric/identity" +) + +// Delivery and transport bounds of the Looking Glass service, per gateway +// replica. +const ( + // SendBound bounds how long a finished router outcome may wait to enter + // a stream's buffer, and how long one write to the stream's consumer + // may block. Either running out cancels the request and ends its stream. + SendBound = 2 * time.Second + // MaxServiceRPCs bounds the RunDiagnostic calls one replica serves at + // once. + MaxServiceRPCs = 32 + // MaxForwardRPCs bounds the forwarded calls the leader serves at once. + MaxForwardRPCs = 16 + // MaxServiceConns bounds the TLS connections service identities hold + // open to one replica. + MaxServiceConns = 64 + // transportWindow is every connection's and stream's flow-control + // window and read and write buffer. A fixed window also turns off + // gRPC's bandwidth-delay window growth. + transportWindow = 64 << 10 + // keepaliveTime and keepaliveTimeout bound how long a silent connection + // lives: the server pings a peer it has not heard from for + // keepaliveTime and closes the connection keepaliveTimeout later, so a + // blackholed peer's calls are cancelled within 10 s of its last frame. + keepaliveTime = 4 * time.Second + keepaliveTimeout = 4 * time.Second + // keepaliveMinTime is the most often a client may ping. + keepaliveMinTime = 5 * time.Second +) + +// errConsumerStalled is the cause with which a request is cancelled when its +// consumer stops reading. +var errConsumerStalled = errors.New("the stream's consumer stopped reading") + +// stalledStatus is the status a request ends with when its consumer stopped +// reading. +func stalledStatus() error { + return errcode.Status(errcode.Cancelled, "the stream's consumer did not read within the write bound") +} + +// eventWriter is a stream's only writer. Each write must finish within +// SendBound. A write that does not is left to the transport, which ends it +// once the handler returns and the stream is reset; every later write then +// fails at once. +type eventWriter struct { + events chan *servicev1.DiagnosticEvent + errs chan error + bound time.Duration + stalled bool +} + +// newEventWriter starts a writer that sends through send. Its owner must +// call close once it stops writing. +func newEventWriter(send func(*servicev1.DiagnosticEvent) error) *eventWriter { + w := &eventWriter{events: make(chan *servicev1.DiagnosticEvent), errs: make(chan error, 1), bound: SendBound} + go func() { + for ev := range w.events { + w.errs <- send(ev) + } + }() + return w +} + +// write sends ev and waits for the transport to take it, at most the write +// bound; past it, write fails with stalledStatus. write is not safe for +// concurrent use. +func (w *eventWriter) write(ev *servicev1.DiagnosticEvent) error { + if w.stalled { + return stalledStatus() + } + w.events <- ev + t := time.NewTimer(w.bound) + defer t.Stop() + select { + case err := <-w.errs: + return err + case <-t.C: + w.stalled = true + return stalledStatus() + } +} + +// close stops the writer once its current write, if any, ends. +func (w *eventWriter) close() { close(w.events) } + +// rpcCaps refuses a diagnostic call beyond its method's per-replica cap +// with QueueFull, rather than queueing it. +type rpcCaps map[string]chan struct{} + +func newRPCCaps() rpcCaps { + return rpcCaps{ + servicev1.LookingGlassService_RunDiagnostic_FullMethodName: make(chan struct{}, MaxServiceRPCs), + forwardv1.ForwardService_ForwardDiagnostic_FullMethodName: make(chan struct{}, MaxForwardRPCs), + } +} + +func (c rpcCaps) stream(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + slots, ok := c[info.FullMethod] + if !ok { + return handler(srv, ss) + } + select { + case slots <- struct{}{}: + defer func() { <-slots }() + return handler(srv, ss) + default: + return errcode.Retry(errcode.QueueFull, "this gateway replica is serving its maximum number of diagnostic calls", + string(limit.ScopeQueue), time.Second) + } +} + +// connLimitCreds refuses a service identity's connection once +// MaxServiceConns of them are open, after the TLS handshake identifies it. +type connLimitCreds struct { + credentials.TransportCredentials + slots chan struct{} +} + +func (c *connLimitCreds) ServerHandshake(raw net.Conn) (net.Conn, credentials.AuthInfo, error) { + conn, info, err := c.TransportCredentials.ServerHandshake(raw) + if err != nil { + return conn, info, err + } + tlsInfo, ok := info.(credentials.TLSInfo) + if !ok { + return conn, info, nil + } + if id, err := identity.PeerID(tlsInfo.State); err != nil || id.Role != identity.RoleService { + return conn, info, nil + } + select { + case c.slots <- struct{}{}: + return &releasingConn{Conn: conn, release: sync.OnceFunc(func() { <-c.slots })}, info, nil + default: + _ = conn.Close() + return nil, nil, errors.New("this gateway replica holds its maximum number of service connections") + } +} + +func (c *connLimitCreds) Clone() credentials.TransportCredentials { + return &connLimitCreds{TransportCredentials: c.TransportCredentials.Clone(), slots: c.slots} +} + +// releasingConn frees its connection slot when closed. +type releasingConn struct { + net.Conn + release func() +} + +func (c *releasingConn) Close() error { + c.release() + return c.Conn.Close() +} + +// transportOptions bound every connection to the gateway listener: fixed +// flow-control windows and buffers, keepalive that closes a silent +// connection, and the service connection cap. +func transportOptions(creds credentials.TransportCredentials) []grpc.ServerOption { + return []grpc.ServerOption{ + grpc.Creds(&connLimitCreds{TransportCredentials: creds, slots: make(chan struct{}, MaxServiceConns)}), + grpc.InitialWindowSize(transportWindow), + grpc.InitialConnWindowSize(transportWindow), + grpc.ReadBufferSize(transportWindow), + grpc.WriteBufferSize(transportWindow), + grpc.KeepaliveParams(keepalive.ServerParameters{Time: keepaliveTime, Timeout: keepaliveTimeout}), + grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{MinTime: keepaliveMinTime, PermitWithoutStream: true}), + } +} + +// leaderDialOptions bound a follower's connection to the leader like the +// listener bounds its own: fixed windows, and keepalive that ends a +// forwarded call when the leader goes silent. gRPC raises a client's ping +// interval to at least 10 s. +func leaderDialOptions() []grpc.DialOption { + return []grpc.DialOption{ + grpc.WithInitialWindowSize(transportWindow), + grpc.WithInitialConnWindowSize(transportWindow), + grpc.WithReadBufferSize(transportWindow), + grpc.WithWriteBufferSize(transportWindow), + grpc.WithKeepaliveParams(keepalive.ClientParameters{Time: 10 * time.Second, Timeout: keepaliveTimeout}), + } +} + +// relay hands each event of a forwarded call to the consumer through w. +// It reads the next event only after the last was written, so a follower +// holds at most the event being written and the one gRPC is receiving. +func relay(recv func() (*servicev1.DiagnosticEvent, error), w *eventWriter) error { + for { + ev, err := recv() + if err != nil { + return err + } + if err := w.write(ev); err != nil { + return err + } + } +} diff --git a/internal/fabric/gateway/stream_test.go b/internal/fabric/gateway/stream_test.go new file mode 100644 index 000000000..a09df5b08 --- /dev/null +++ b/internal/fabric/gateway/stream_test.go @@ -0,0 +1,757 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package gateway + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "path/filepath" + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" + coordinationv1 "k8s.io/api/coordination/v1" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" + + forwardv1 "go.datum.net/galactic/api/fabric/forward/v1" + servicev1 "go.datum.net/galactic/api/fabric/service/v1" + fabricv1 "go.datum.net/galactic/api/fabric/v1" + "go.datum.net/galactic/internal/fabric/errcode" + "go.datum.net/galactic/internal/fabric/gateway/limit" + "go.datum.net/galactic/internal/fabric/identity" + "go.datum.net/galactic/internal/fabric/node" + "go.datum.net/galactic/internal/fabric/testpki" +) + +// releaseBound is the contract's local cleanup allowance after a trigger. +const releaseBound = 2 * time.Second + +// idle reports whether svc holds no execution slot, queued job, +// reservation or live stream. +func idle(svc *Service) bool { + e := svc.Runner.Executor + e.mu.Lock() + busy := e.inUse+e.waiting+e.reserved > 0 + e.mu.Unlock() + a := svc.Admission + a.mu.Lock() + defer a.mu.Unlock() + return !busy && a.streams == 0 +} + +// within fails the test unless cond holds within d of since, polled. +func within(t *testing.T, what string, since time.Time, d time.Duration, cond func() bool) { + t.Helper() + for !cond() { + if time.Since(since) > d { + t.Fatalf("%s: not within %s", what, d) + } + time.Sleep(10 * time.Millisecond) + } + t.Logf("%s after %s", what, time.Since(since).Round(time.Millisecond)) +} + +// cancelAnswer runs until its call's context ends and records when. It +// signals started once running. +type cancelAnswer struct { + started chan struct{} + mu sync.Mutex + at time.Time +} + +func newCancelAnswer() *cancelAnswer { return &cancelAnswer{started: make(chan struct{}, 1)} } + +func (c *cancelAnswer) answer(ctx context.Context, _ *fabricv1.ExecuteRequest) (*fabricv1.Observation, error) { + c.started <- struct{}{} + <-ctx.Done() + c.mu.Lock() + c.at = time.Now() + c.mu.Unlock() + return nil, errcode.Status(errcode.Timeout, "cancelled") +} + +func (c *cancelAnswer) cancelled() bool { + c.mu.Lock() + defer c.mu.Unlock() + return !c.at.IsZero() +} + +// bigAnswer answers with an observation of at least size serialized bytes. +func bigAnswer(name string, size int) routerAnswer { + return func(context.Context, *fabricv1.ExecuteRequest) (*fabricv1.Observation, error) { + obs := pingObservation(name, 3) + obs.GetPing().Replies[0].Address = strings.Repeat("a", size) + return obs, nil + } +} + +func routerNames(n int) []string { + out := make([]string, n) + for i := range out { + out[i] = fmt.Sprintf("router-%02d", i) + } + return out +} + +// handlerEnds records when, and with what, each server stream handler +// returned. +type handlerEnds struct { + mu sync.Mutex + ends map[string]error + at map[string]time.Time +} + +func (h *handlerEnds) interceptor( + srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler, +) error { + err := handler(srv, ss) + h.mu.Lock() + if h.ends == nil { + h.ends, h.at = map[string]error{}, map[string]time.Time{} + } + h.ends[info.FullMethod], h.at[info.FullMethod] = err, time.Now() + h.mu.Unlock() + return err +} + +func (h *handlerEnds) ended(method string) (error, bool) { + h.mu.Lock() + defer h.mu.Unlock() + _, ok := h.at[method] + return h.ends[method], ok +} + +// serveStoppable serves svc like serveGateway and also returns the server. +func serveStoppable(t *testing.T, creds *identity.Credentials, svc *Service, opts ...grpc.ServerOption) ( + string, *grpc.Server, +) { + t.Helper() + srv := NewServer(creds, svc.Allowlist, &Debug{Elected: svc.Elected}, svc, noPermits(svc.Elected), opts...) + var lc net.ListenConfig + l, err := lc.Listen(t.Context(), "tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + go func() { _ = srv.Serve(l) }() + t.Cleanup(srv.Stop) + return l.Addr().String(), srv +} + +// dialService connects as the test service identity with a fixed 64 KiB +// receive window, so a client that stops reading stalls the server. +func dialService(t *testing.T, addr string, creds *identity.Credentials) *grpc.ClientConn { + t.Helper() + conn, err := grpc.NewClient(addr, + grpc.WithTransportCredentials(credentials.NewTLS(creds.ClientConfig(identity.Gateway(testSite)))), + grpc.WithInitialWindowSize(transportWindow), grpc.WithInitialConnWindowSize(transportWindow), + ) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = conn.Close() }) + return conn +} + +type testPKI struct { + gateway, service *identity.Credentials +} + +func newTestPKI(t *testing.T) testPKI { + t.Helper() + dir := t.TempDir() + ca := testpki.NewCA(t, testSite) + return testPKI{ + gateway: loadCreds(t, ca, dir, identity.Gateway(testSite)), + service: loadCreds(t, ca, filepath.Join(dir, "svc"), identity.Service(testSite, testService)), + } +} + +// A consumer that stops reading cannot hold the request's execution: once +// a write blocks for SendBound the handler ends, the transport aborts the +// write, and the running routers, queue, reservation and live stream are +// released, on the leader and through a follower alike. +func TestServiceStalledConsumerOverTransport(t *testing.T) { + pki := newTestPKI(t) + runMethod := servicev1.LookingGlassService_RunDiagnostic_FullMethodName + forwardMethod := forwardv1.ForwardService_ForwardDiagnostic_FullMethodName + for _, viaFollower := range []bool{false, true} { + t.Run(fmt.Sprintf("via follower %t", viaFollower), func(t *testing.T) { + names := routerNames(8) + slow := newCancelAnswer() + nodes := &routerNodes{answers: map[string]routerAnswer{}} + for _, n := range names[1:] { + nodes.answers[n] = bigAnswer(n, 100<<10) + } + nodes.answers[names[0]] = slow.answer + leader := newService(t, routerPods(names...), nodes, 8) + var leaderEnds, followerEnds handlerEnds + addr, _ := serveStoppable(t, pki.gateway, leader, grpc.ChainStreamInterceptor(leaderEnds.interceptor)) + ends, method := &leaderEnds, runMethod + if viaFollower { + addr, _ = serveStoppable(t, pki.gateway, followerService(t, pki.gateway, addr), + grpc.ChainStreamInterceptor(followerEnds.interceptor)) + ends = &followerEnds + } + ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) + defer cancel() + stream, err := servicev1.NewLookingGlassServiceClient(dialService(t, addr, pki.service)). + RunDiagnostic(ctx, validRequest(time.Now())) + if err != nil { + t.Fatal(err) + } + if ev, err := stream.Recv(); err != nil || ev.GetSnapshot() == nil { + t.Fatalf("first event %v, %v", ev, err) + } + <-slow.started + // The consumer reads nothing more. The routers answer at once, + // so the write blocks as soon as the window fills: the handler + // ends within SendBound of that, and cleanup within another + // releaseBound. + stalled := time.Now() + bound := SendBound + releaseBound + within(t, "handler ended", stalled, bound, func() bool { _, ok := ends.ended(method); return ok }) + if err, _ := ends.ended(method); status.Code(err) != codes.Canceled { + t.Errorf("handler status %v, want CANCELLED", err) + } + if viaFollower { + within(t, "leader handler ended", stalled, bound+releaseBound, func() bool { + _, ok := leaderEnds.ended(forwardMethod) + return ok + }) + } + within(t, "running router cancelled", stalled, bound+releaseBound, slow.cancelled) + within(t, "execution released", stalled, bound+releaseBound, func() bool { return idle(leader) }) + }) + } +} + +// A finished outcome that cannot enter the stream's buffer within +// SendBound cancels the request, even while each write still finishes +// within its own bound. +func TestServiceStalledHandOff(t *testing.T) { + names := routerNames(8) + slow := newCancelAnswer() + nodes := &routerNodes{answers: map[string]routerAnswer{names[0]: slow.answer}} + svc := newService(t, routerPods(names...), nodes, 8) + stream := &slowStream{ctx: node.WithCaller(t.Context(), identity.Service(testSite, testService)), + delay: SendBound * 3 / 4} + done := make(chan error, 1) + go func() { done <- svc.RunDiagnostic(validRequest(time.Now()), stream) }() + <-slow.started + start := time.Now() + var err error + select { + case err = <-done: + case <-time.After(4 * SendBound): + t.Fatal("a stalled hand-off did not end the request") + } + if errcode.Of(err) != errcode.Cancelled { + t.Errorf("err = %v, want Cancelled", err) + } + within(t, "running router cancelled", start, 4*SendBound, slow.cancelled) + within(t, "execution released", start, 4*SendBound, func() bool { return idle(svc) }) +} + +// slowStream takes delay to send each event. +type slowStream struct { + grpc.ServerStream + ctx context.Context + delay time.Duration +} + +func (s *slowStream) Context() context.Context { return s.ctx } + +func (s *slowStream) Send(*servicev1.DiagnosticEvent) error { + time.Sleep(s.delay) + return nil +} + +// eventSize sums the serialized size of events. +func eventSize(events []*servicev1.DiagnosticEvent) int { + n := 0 + for _, ev := range events { + n += proto.Size(ev) + } + return n +} + +func TestServiceOutputBounds(t *testing.T) { + t.Run("oversized outcome", func(t *testing.T) { + nodes := &routerNodes{answers: map[string]routerAnswer{routerA: bigAnswer(routerA, maxOutcomeBytes)}} + svc := newService(t, routerPods(routerA, routerB), nodes, 8) + events, err := collect(t, svc, validRequest(time.Now())) + if err != nil { + t.Fatal(err) + } + _, outcomes, c := checkGrammar(t, events) + if f := outcomes[routerA].GetFailure(); f.GetReason() != string(errcode.ResponseTooLarge) { + t.Errorf("oversized outcome = %v", outcomes[routerA]) + } + if c.GetReason() != CompletePartialResults || c.GetSuccessful() != 1 { + t.Errorf("complete = %v", c) + } + }) + t.Run("stream budget", func(t *testing.T) { + names := routerNames(6) + nodes := &routerNodes{answers: map[string]routerAnswer{}} + for _, n := range names { + nodes.answers[n] = bigAnswer(n, 100<<10) + } + svc := newService(t, routerPods(names...), nodes, 8) + // Room for the snapshot, the terminal event and two outcomes. + svc.outputLimit = maxCompleteBytes + 230<<10 + events, err := collect(t, svc, validRequest(time.Now())) + if err != nil { + t.Fatal(err) + } + _, outcomes, c := checkGrammar(t, events) + limited := 0 + for _, o := range outcomes { + if o.GetFailure().GetReason() == string(errcode.OutputLimitExceeded) { + limited++ + } + } + if c.GetReason() != string(errcode.OutputLimitExceeded) || c.GetSuccessful() != 2 || limited != 4 { + t.Errorf("complete %v, %d outcomes over the budget: %v", c, limited, outcomes) + } + if n := eventSize(events); n > svc.outputLimit { + t.Errorf("stream wrote %d bytes, over its %d budget", n, svc.outputLimit) + } + }) +} + +// Every live stream at once, each router answering the largest outcome the +// stream accepts, stays within each stream's output budget and a bounded +// number of goroutines. +func TestServiceMaximumOutcomesBounded(t *testing.T) { + const streams, routers = 16, 16 + names := routerNames(routers) + nodes := &routerNodes{answers: map[string]routerAnswer{}} + for _, n := range names { + nodes.answers[n] = bigAnswer(n, maxOutcomeBytes-4<<10) + } + svc := newService(t, routerPods(names...), nodes, 8) + l := roomyLimits() + l.Streams, l.ProjectStreams = streams, 1 + withAdmission(t, svc, l) + svc.Runner.QueueWait = 20 * time.Second + + base := runtime.NumGoroutine() + var peak atomic.Int64 + sampling, stopSampling := context.WithCancel(t.Context()) + go func() { + for sampling.Err() == nil { + if n := int64(runtime.NumGoroutine()); n > peak.Load() { + peak.Store(n) + } + time.Sleep(time.Millisecond) + } + }() + var wg sync.WaitGroup + results := make([][]*servicev1.DiagnosticEvent, streams) + errs := make([]error, streams) + for i := range streams { + wg.Go(func() { + results[i], errs[i] = collectWithin(t, svc, requestFor(fmt.Sprintf("project-%02d", i), i, nil), time.Minute) + }) + } + wg.Wait() + stopSampling() + for i := range streams { + if errs[i] != nil { + t.Fatalf("stream %d: %v", i, errs[i]) + } + _, _, c := checkGrammar(t, results[i]) + if c.GetReason() != CompleteSucceeded || c.GetSuccessful() != routers { + t.Errorf("stream %d: complete %v", i, c) + } + if n := eventSize(results[i]); n > MaxStreamBytes { + t.Errorf("stream %d wrote %d bytes", i, n) + } + } + // Per stream: its handler, writer and producer, one goroutine per + // router, and a small allowance for the runtime and test harness. + if bound := int64(base + streams*(routers+4) + 32); peak.Load() > bound { + t.Errorf("peak goroutines %d, over %d", peak.Load(), bound) + } + if !idle(svc) { + t.Error("execution not released") + } +} + +// collectWithin is collect with its own timeout, safe off the test +// goroutine. +func collectWithin(t *testing.T, svc *Service, req *runReq, d time.Duration) ([]*servicev1.DiagnosticEvent, error) { + events, done := run(t, svc, req, 0) + var out []*servicev1.DiagnosticEvent + timeout := time.After(d) + for { + select { + case ev, ok := <-events: + if !ok { + return out, <-done + } + out = append(out, ev) + case <-timeout: + return out, errors.New("stream did not finish") + } + } +} + +// Caller cancellation during discovery, while queued and while executing +// releases the request's work within releaseBound. +func TestServiceCancellationBounds(t *testing.T) { + caller := identity.Service(testSite, testService) + t.Run("discovery", func(t *testing.T) { + svc := newService(t, routerPods(routerA), &routerNodes{}, 8) + listing := make(chan struct{}, 1) + svc.Discoverer.Reader = stallReader{Reader: svc.Discoverer.Reader, listing: listing} + ctx, cancel := context.WithCancel(node.WithCaller(t.Context(), caller)) + done := make(chan error, 1) + go func() { + stream := &chanStream{ctx: ctx, events: make(chan *servicev1.DiagnosticEvent, 8)} + done <- svc.RunDiagnostic(validRequest(time.Now()), stream) + }() + <-listing + start := time.Now() + cancel() + var err error + within(t, "request ended", start, releaseBound, func() bool { + select { + case err = <-done: + return true + default: + return false + } + }) + if errcode.Of(err) != errcode.Cancelled { + t.Errorf("err = %v", err) + } + within(t, "execution released", start, releaseBound, func() bool { return idle(svc) }) + }) + t.Run("queued and executing", func(t *testing.T) { + a, b := newCancelAnswer(), newCancelAnswer() + nodes := &routerNodes{answers: map[string]routerAnswer{routerA: a.answer, routerB: b.answer}} + svc := newService(t, routerPods(routerA, routerB), nodes, 1) + svc.Runner.QueueWait = time.Minute + ctx, cancel := context.WithCancel(node.WithCaller(t.Context(), caller)) + stream := &chanStream{ctx: ctx, events: make(chan *servicev1.DiagnosticEvent, 8)} + done := make(chan error, 1) + go func() { done <- svc.RunDiagnostic(validRequest(time.Now()), stream) }() + // One router holds the only slot; the other queues behind it. + running, queued := a, b + select { + case <-a.started: + case <-b.started: + running, queued = b, a + } + within(t, "second router queued", time.Now(), releaseBound, + func() bool { return svc.Runner.Executor.Depth() == 1 }) + start := time.Now() + cancel() + within(t, "request ended", start, releaseBound, func() bool { return len(done) == 1 }) + within(t, "running router cancelled", start, releaseBound, running.cancelled) + within(t, "execution released", start, releaseBound, func() bool { return idle(svc) }) + if len(queued.started) != 0 { + t.Error("the queued router ran after cancellation") + } + }) +} + +// Stopping the gateway server cancels a running service request's routers +// within releaseBound. +func TestGatewayStopCancelsServiceWork(t *testing.T) { + pki := newTestPKI(t) + running := newCancelAnswer() + svc := newService(t, routerPods(routerA), &routerNodes{answers: map[string]routerAnswer{routerA: running.answer}}, 8) + addr, srv := serveStoppable(t, pki.gateway, svc) + stream, err := servicev1.NewLookingGlassServiceClient(dialService(t, addr, pki.service)). + RunDiagnostic(t.Context(), validRequest(time.Now())) + if err != nil { + t.Fatal(err) + } + if _, err := stream.Recv(); err != nil { + t.Fatal(err) + } + <-running.started + start := time.Now() + srv.Stop() + within(t, "running router cancelled", start, releaseBound, running.cancelled) + within(t, "execution released", start, releaseBound, func() bool { return idle(svc) }) +} + +// blackhole relays TCP between a client and the gateway until frozen, then +// drops every byte in both directions without closing either side. +type blackhole struct { + frozen atomic.Bool +} + +func (b *blackhole) serve(t *testing.T, target string) string { + t.Helper() + var lc net.ListenConfig + l, err := lc.Listen(t.Context(), "tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = l.Close() }) + go func() { + for { + in, err := l.Accept() + if err != nil { + return + } + var d net.Dialer + out, err := d.DialContext(t.Context(), "tcp", target) + if err != nil { + _ = in.Close() + continue + } + t.Cleanup(func() { _ = in.Close(); _ = out.Close() }) + go b.pipe(in, out) + go b.pipe(out, in) + } + }() + return l.Addr().String() +} + +func (b *blackhole) pipe(dst io.Writer, src io.Reader) { + buf := make([]byte, 32<<10) + for { + n, err := src.Read(buf) + if err != nil { + return + } + if !b.frozen.Load() { + if _, err := dst.Write(buf[:n]); err != nil { + return + } + } + } +} + +// A connection that goes silent is detected by keepalive within 10 s, and +// its request's routers are cancelled within releaseBound after that. +func TestServiceBlackholedConnection(t *testing.T) { + pki := newTestPKI(t) + running := newCancelAnswer() + svc := newService(t, routerPods(routerA), &routerNodes{answers: map[string]routerAnswer{routerA: running.answer}}, 8) + addr, _ := serveStoppable(t, pki.gateway, svc) + var hole blackhole + proxied := hole.serve(t, addr) + ctx, cancel := context.WithTimeout(t.Context(), time.Minute) + defer cancel() + stream, err := servicev1.NewLookingGlassServiceClient(dialService(t, proxied, pki.service)). + RunDiagnostic(ctx, validRequest(time.Now().Add(30*time.Second))) + if err != nil { + t.Fatal(err) + } + if _, err := stream.Recv(); err != nil { + t.Fatal(err) + } + <-running.started + start := time.Now() + hole.frozen.Store(true) + within(t, "running router cancelled", start, 10*time.Second+releaseBound, running.cancelled) + within(t, "execution released", start, 10*time.Second+releaseBound, func() bool { return idle(svc) }) +} + +// A forwarded stream the leader loses is never forwarded again, and no +// router runs twice. +func TestForwardedStreamIsNotReplayed(t *testing.T) { + pki := newTestPKI(t) + running := newCancelAnswer() + nodes := &routerNodes{answers: map[string]routerAnswer{routerA: running.answer}} + leader := newService(t, routerPods(routerA, routerB), nodes, 8) + leaderAddr, leaderSrv := serveStoppable(t, pki.gateway, leader) + var forwards atomic.Int32 + count := func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, + streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { + if method == forwardv1.ForwardService_ForwardDiagnostic_FullMethodName { + forwards.Add(1) + } + return streamer(ctx, desc, cc, method, opts...) + } + addr := serveFollower(t, pki.gateway, leaderAddr, grpc.WithStreamInterceptor(count)) + stream, err := servicev1.NewLookingGlassServiceClient(dialService(t, addr, pki.service)). + RunDiagnostic(t.Context(), validRequest(time.Now())) + if err != nil { + t.Fatal(err) + } + if ev, err := stream.Recv(); err != nil || ev.GetSnapshot() == nil { + t.Fatalf("first event %v, %v", ev, err) + } + <-running.started + leaderSrv.Stop() + for { + _, err := stream.Recv() + if err == nil { + continue + } + if errors.Is(err, io.EOF) { + t.Fatal("the interrupted stream ended as if delivered") + } + break + } + within(t, "leader's router cancelled", time.Now(), releaseBound, running.cancelled) + if n := forwards.Load(); n != 1 { + t.Errorf("forwarded %d times", n) + } + nodes.mu.Lock() + defer nodes.mu.Unlock() + for n, c := range nodes.calls { + if c > 1 { + t.Errorf("%s ran %d times", n, c) + } + } +} + +// handOff makes another process the election lease's holder. +func handOff(t *testing.T, c client.Client) { + t.Helper() + var lease coordinationv1.Lease + if err := c.Get(t.Context(), client.ObjectKey{Namespace: DefaultNamespace, Name: testLease}, &lease); err != nil { + t.Fatal(err) + } + lease.Spec.HolderIdentity = ptr.To("gateway-1_other") + if err := c.Update(t.Context(), &lease); err != nil { + t.Fatal(err) + } +} + +// A gateway that missed its own replacement, as a paused process would, +// dispatches nothing once the lease names another holder: its queued +// router never runs, the stream ends with OwnershipLost, and it admits no +// new request. +func TestStaleOwnerDispatchesNothing(t *testing.T) { + release := make(chan struct{}) + started := make(chan struct{}, 2) + nodes := &routerNodes{answers: map[string]routerAnswer{ + routerA: blockAnswer(routerA, release, started), routerB: blockAnswer(routerB, release, started), + }} + svc := newService(t, routerPods(routerA, routerB), nodes, 1) + svc.Runner.QueueWait = time.Minute + lease := newSwitchableLease(t) + adm, err := NewAdmission(roomyLimits(), &limit.Authority{ + Reader: lease, Namespace: DefaultNamespace, Name: testLease, Identity: testHolder, Hold: time.Nanosecond, + }) + if err != nil { + t.Fatal(err) + } + activate(t, adm) + svc.Admission, svc.Runner.Admission, svc.Runner.Executor = adm, adm, NewExecutor(1, 0, 0) + + events, done := run(t, svc, requestFor("project-a", 1, nil), 0) + <-started + // The router that did not start waits behind the only slot. + queued := routerB + nodes.mu.Lock() + if nodes.calls[routerB] == 1 { + queued = routerA + } + nodes.mu.Unlock() + handOff(t, lease.Client) + close(release) + var got []*servicev1.DiagnosticEvent + for ev := range events { + got = append(got, ev) + } + if err := <-done; err != nil { + t.Fatal(err) + } + _, outcomes, c := checkGrammar(t, got) + if c.GetReason() != string(errcode.OwnershipLost) || + outcomes[queued].GetFailure().GetReason() != string(errcode.OwnershipLost) { + t.Errorf("outcomes %v, complete %v", outcomes, c) + } + if _, err := collect(t, svc, requestFor("project-a", 2, nil)); errcode.Of(err) != errcode.OwnershipLost { + t.Errorf("new request on the stale owner: %v", err) + } + if nodes.total() != 1 { + t.Errorf("calls after the hand-off: %v", nodes.calls) + } +} + +func TestRPCCaps(t *testing.T) { + caps := newRPCCaps() + for method, capacity := range map[string]int{ + servicev1.LookingGlassService_RunDiagnostic_FullMethodName: MaxServiceRPCs, + forwardv1.ForwardService_ForwardDiagnostic_FullMethodName: MaxForwardRPCs, + } { + hold, entered := make(chan struct{}), make(chan struct{}, capacity) + var wg sync.WaitGroup + for range capacity { + wg.Go(func() { + _ = caps.stream(nil, nil, &grpc.StreamServerInfo{FullMethod: method}, func(any, grpc.ServerStream) error { + entered <- struct{}{} + <-hold + return nil + }) + }) + } + for range capacity { + <-entered + } + err := caps.stream(nil, nil, &grpc.StreamServerInfo{FullMethod: method}, + func(any, grpc.ServerStream) error { return nil }) + wantRetry(t, err, errcode.QueueFull, string(limit.ScopeQueue)) + close(hold) + wg.Wait() + if err := caps.stream(nil, nil, &grpc.StreamServerInfo{FullMethod: method}, + func(any, grpc.ServerStream) error { return nil }); err != nil { + t.Errorf("%s after release: %v", method, err) + } + } + // Other methods are not capped. + if err := caps.stream(nil, nil, &grpc.StreamServerInfo{FullMethod: "/other/Method"}, + func(any, grpc.ServerStream) error { return nil }); err != nil { + t.Error(err) + } +} + +// Service identities hold at most MaxServiceConns connections to a +// replica; other identities are not counted, and a closed connection frees +// its slot. +func TestServiceConnectionCap(t *testing.T) { + pki := newTestPKI(t) + svc := newService(t, nil, &routerNodes{}, 8) + addr, _ := serveStoppable(t, pki.gateway, svc) + capabilities := func(conn *grpc.ClientConn) error { + _, err := servicev1.NewLookingGlassServiceClient(conn).GetCapabilities(t.Context(), + &servicev1.GetCapabilitiesRequest{ApiMajor: ServiceAPIMajor, Cell: testSite}) + return err + } + conns := make([]*grpc.ClientConn, 0, MaxServiceConns) + for i := range MaxServiceConns { + conn := dialService(t, addr, pki.service) + if err := capabilities(conn); err != nil { + t.Fatalf("connection %d: %v", i, err) + } + conns = append(conns, conn) + } + if err := capabilities(dialService(t, addr, pki.service)); status.Code(err) != codes.Unavailable { + t.Errorf("connection over the cap: %v", err) + } + // The gateway identity is not a service connection. + if _, err := fabricv1.NewFabricGatewayServiceClient(dialAs(t, addr, pki.gateway)). + ListNodes(t.Context(), &fabricv1.ListNodesRequest{}); status.Code(err) == codes.Unavailable { + t.Errorf("gateway connection refused: %v", err) + } + _ = conns[0].Close() + within(t, "slot freed", time.Now(), releaseBound, func() bool { + return capabilities(dialService(t, addr, pki.service)) == nil + }) +}