Repository navigation
feat(go)!: redesign HTTP serving API with genkithttp and genkithttp/exp - #7443
Merged
Merged
Conversation
Contributor
There was a problem hiding this comment.
Code Review
This pull request migrates HTTP serving from the core genkit package and the plugins/server plugin to the new framework-agnostic genkithttp and genkithttp/exp packages, introducing a new Mux, NewHandler, and ListenAndServe utility. It also adds typed ContextKeys for request-scoped context propagation. A security issue was identified in the new CORS middleware, where reflecting the Origin header when AllowCredentials is enabled with a wildcard origin configuration allows unauthorized credentialed cross-origin requests.
genkit-bot
reviewed
Dec 3, 2026
genkit-bot
left a comment
Contributor
There was a problem hiding this comment.
A few comments
Details
Run d268058f-08c3-4e98-b020-47db9721100b · Cloud Run logs · Dashboard
apascal07
force-pushed
the
ap/go-v2-http-api
branch
from
December 4, 2026 21:42
096d1c4 to
c956841
Compare
genkit.ContextKey is the only typed context key; core keeps ActionContext,
WithActionContext, and FromContext. ContextKey.WithValue also stores the
value's JSON form in the action context under the key's name, so a template
reads it as {{@name}} (for example {{@auth.uid}} behind
firebase.AuthMiddleware), as it did with context providers. NewContextKey
panics on an empty name, and ContextKey.Name is no longer exported.
firebase.AuthMiddleware logs each rejected request before it writes the
Genkit error body.
…router genkithttp serves one action per handler and leaves routing, CORS, auth, and server lifecycle to the application's router and middleware. Its exported surface is NewHandler with WithMaxBodyBytes and WithOnError, WriteError for middleware, the X-Genkit-* header names, and DefaultAllowedHeaders and DefaultExposedHeaders for configuring a CORS library. The request decoder, result and SSE writers, and stream negotiation are unexported. An explicit ?stream=<bool> decides streaming, and an Accept entry with q=0 does not ask for a stream. genkithttp/exp holds the experimental parts. AgentRoutes(path, agent) returns an agent's turn route and the companion routes it supports as []Route, which mounts on net/http, Chi, Gin, or Echo; it takes any value with the companion action accessors. WithStreamManager and WithStreamTimeout enable durable streaming for a NewHandler route, so the stable package does not depend on core/x/streaming. A detached durable run reports its failure through WithOnError once, with the original request. Samples and tests mount handlers on http.ServeMux and serve with http.ListenAndServe.
README, package docs, and MIGRATION.md show flows mounted with genkithttp.NewHandler and agents with genkithttpx.AgentRoutes on a standard router, durable streaming through genkithttpx.WithStreamManager, and CORS through the router's middleware with the Genkit header lists.
…er a timeout A durable run executes on its own goroutine, outside net/http's per-request recovery, so a panic in the action ended the process. The handler now turns it into an ErrPanic error that the client and WithOnError receive. A run that hits WithStreamTimeout ends with its context done, and a store that honors the context (such as the Firestore stream manager) then rejected the terminal write, so reconnecting clients waited without an end. The end is now recorded on a fresh 10-second deadline that keeps the request's values, and a failure to record it is logged.
The action context is the one place request values live, as in JS: HTTP
middleware adds to it with core.WithActionContextValue, the Dev UI and CLI
--context fill it with JSON, flows read it with core.FromContext, and
Dotprompt templates read it as {{@name}}. WithActionContextValue copies the
map, so middleware can each add a value without changing the parent context.
Prompt rendering gives templates the JSON form of a struct value, so
{{@auth.uid}} reads a field by its JSON name. Requests that render no
template do no conversion.
firebase.AuthFromContext replaces firebase.AuthKey. It returns the verified
token on a served request and decodes a Dev UI auth object the way the Admin
SDK decodes a token, with custom claims in Token.Claims.
Values that only Go code reads use plain context.WithValue.
The handler takes its stream manager from core/exp (corex), where durable streaming lives, and genkithttpx.WithStreamManager is the one way to enable it. genkitx.WithStreamManager configured genkit.Handler, which genkithttp replaces, so it is removed along with its genkitbridge hook. genkithttp/exp is package genkithttpx, the name it is imported as, like the other experimental packages.
A failed reconnect went back to the top of the session loop, which started register and readLoop on the closed connection, so each failed attempt spawned a goroutine and logged errors. The session now waits in a backoff loop until a dial succeeds. The backoff shifted reconnectBaseDelay by the unbounded attempt count, which overflows into a negative delay at attempt 35, about three minutes into a CLI outage, after which retries did not wait. reconnectDelay stops the shift at the cap.
apascal07
force-pushed
the
ap/go-v2-http-api
branch
from
December 4, 2026 22:42
2470397 to
1b798fb
Compare
Every failed request logged at ERROR, so malformed JSON, a wrong method, or a lookup of an unknown snapshot each produced an error log line in production. A public 4xx error, one made with status.PublicErrorf, is a deliberate rejection of the request and now logs at DEBUG. Every other error stays at ERROR, including 4xx errors that are not public: a model provider reports a revoked server API key as UNAUTHENTICATED and a quota limit as RESOURCE_EXHAUSTED, and those are the server's problem. WithOnError still receives every error.
… reader core.FromContext is core.ActionContextFromContext. The old name did not say which context it returns, and genkit.FromContext returns a *Genkit. core.ActionContextValue[T] reads one action context value as a T. HTTP middleware stores Go values, but the Dev UI and CLI --context store decoded JSON, so a value that is not already a T is converted through JSON. Flows no longer need a type switch with a JSON fallback for each value they read.
core.ActionContextFromContext, core.WithActionContext, and the core.ActionContext type are removed. Middleware adds a value with core.WithActionContextValue and flows read one with core.ActionContextValue[T]; ActionContextValue[any] returns a value as stored. The removed reader returned the stored map, so a flow that wrote to it changed the values its caller's context held. The map lives in internal/actionctx for the code that fills or lists it: the reflection servers and prompt rendering.
…nterop Refines the Genkit Go v2 HTTP serving API before release so lifecycle hooks, error wire fidelity, distributed tracing, request validation, and durable streaming semantics are sound from v2.0. - Return concrete *genkithttp.Handler from NewHandler with Action() and Shutdown(ctx), and export WithHeartbeat. - Defer SSE header commit until first chunk, heartbeat, or result so pre-stream validation, auth, and snapshot errors return HTTP 4xx. - Preserve status.Error.Details on public and dev wire errors; redact them on non-public production errors; handle WriteError(w, nil). - Require Content-Type: application/json for non-empty POST bodies (415) and reject unknown envelope fields and trailing JSON tokens (400). - Extract W3C traceparent/tracestate in NewHandler and include them in DefaultAllowedHeaders. - Move HeaderStreamID out of stable genkithttp into genkithttp/exp alongside HeaderLastEventID; add RouteKind and concrete *Handler on genkithttpx.Route. - Upgrade durable streaming: scope stream keys per action, reject X-Genkit-Stream-Id with 501 when disabled, start WithStreamTimeout only on disconnect, support Last-Event-ID chunk resume, persist chunks asynchronously with warning logs, fix InMemoryStreamManager >100-chunk subscribe deadlock, and drain detached runs in Handler.Shutdown. - Update firebase.AuthMiddleware: export NewAuthMiddleware, simplify AuthPolicy, expose custom claims to Dotprompt, log public 4xx at debug, and send WWW-Authenticate: Bearer on 401. - Cache Dotprompt action context template conversions per snapshot. - Fix JS streamFlow SSE parsing to ignore comments and non-data lines. - Fix researcher sample shutdown on stdin EOF and update docs/samples.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Redesigns Genkit Go v2 HTTP serving on standard
net/http, targeting the v2 branch (ap/go-v2). Two packages replacegenkit.Handler,genkit.HandlerFunc,plugins/server, thegenkit/exproute builders, andcore.ContextProvider: stablegenkithttpand experimentalgenkithttp/exp(packagegenkithttpx). Genkit serves actions; routing, CORS, auth, and server lifecycle stay with the application's router and its middleware, so Chi, Gin, Echo, andhttp.ServeMuxall mount Genkit routes without adapters. Also fixes the v1 wire protocol bugs and updates the JSstreamFlowclient SSE parser to handle comment and metadata lines.One concrete handler per action, mounted on any router
Before:
After:
NewHandlerreturns a concrete*genkithttp.Handler(implementinghttp.Handler) withAction()andShutdown(ctx)for draining detached durable-streaming runs afterhttp.Server.Shutdown.AgentRoutesreturns the turn route plus the companion routes the agent supports (/getSnapshot,/waitForSnapshot,/abort) as[]Route, each carrying aKind(RouteKindTurn,RouteKindGetSnapshot,RouteKindWaitForSnapshot,RouteKindAbort) and a*genkithttp.Handler.Pattern()gives"POST /path"for ServeMux and Chi; Gin and Echo readMethodandPath. It takes an interface rather than*aix.Agent[S], so one loop mounts agents with different state types. Filter byrt.Kindto leave a companion route out.Middleware and the action context replace
ContextProviderThe action context stays the one place request values live, as in JS: middleware adds to it, the Dev UI and CLI
--contextfill it with JSON, flows readcore.ActionContextValue[T](ctx, name), and templates read{{@name}}.WithActionContextValuecopies the map, so chained middleware never overwrites or aliases a parent's values.ActionContextValueconverts a Dev UI JSON object to a struct and a JSON number to anint. Prompt rendering caches the JSON form of struct values once per immutable context snapshot so Go's Handlebars engine resolves fields by JSON name ({{@auth.uid}}), and requests that render no template pay zero conversion cost.firebase.AuthMiddleware,firebase.NewAuthMiddleware, andfirebase.AuthFromContextreplacefirebase.ContextProvider.AuthMiddlewareexposes both standard token fields and custom claims ({{@auth.email}}, etc.) to Dotprompt templates matching Dev UI runs, setsWWW-Authenticate: Beareron 401 responses, and logs public 4xx rejections at DEBUG. Values only Go code reads use plaincontext.WithValue.Durable streaming stays experimental
WithStreamManager,WithStreamTimeout,HeaderStreamID, andHeaderLastEventIDlive ingenkithttp/expbecauseStreamManagercomes fromcore/exp(corex); the stablegenkithttppackage exposes no experimental types or headers.StreamManagercannot cross-replay another action's stream. SendingX-Genkit-Stream-Idto a handler with noStreamManagerreturns HTTP501 UNIMPLEMENTEDinstead of re-running the action; sending it on a non-streaming request returns400.id:lines (StreamEvent.Index); reconnecting clients can sendLast-Event-IDto skip already-received chunks (400on invalid values).InMemoryStreamManager.Subscribesizes its replay buffer to hold all buffered chunks plus the terminal event, avoiding deadlocks above 100 chunks, andClose()is idempotent.WithStreamTimeout(default10m) starts only when the client disconnects, so connected clients are not cut off. Chunks persist asynchronously in FIFO order (logging storage errors atWARN) and drain before recordingDone/Erroron a fresh 10s deadline. Panics on the detached goroutine becomeErrPanic,WithOnErroris called once, andHandler.Shutdown(ctx)waits for active detached runs to finish.Wire protocol fixes
ContentLength == -1), capped at 10 MiB by default (WithMaxBodyBytes,413past it). Non-empty POST bodies requireContent-Type: application/json(415otherwise); malformed JSON, unknown top-level envelope fields, and trailing JSON tokens get400. Non-POSTgets405withAllow: POST.?stream=<bool>decides (400when invalid); otherwiseAccept: text/event-streamasks for a stream unlessq=0.ConnectionorTransfer-Encodingheaders (RFC 9113), flushing through wrappedResponseWriters viahttp.ResponseController, and keepalives every 15s (WithHeartbeat,0disables). SSE headers commit on the first chunk, heartbeat, or final result, so pre-stream schema, auth, and unknown-snapshot failures return real HTTP 4xx JSON responses instead of 200 OK SSE frames. The JSstreamFlowclient parser ignores SSE comments (: keepalive) and metadata lines (id:,event:,retry:) and exits cleanly on stream EOF.X-Genkit-Trace-IdandX-Genkit-Span-Idare set on unary and SSE responses, incoming W3Ctraceparent/tracestateheaders are extracted when no outer middleware has extracted a span context, andDefaultAllowedHeadersincludestraceparentandtracestate.status.Error.Detailsare preserved on public errors (and inGENKIT_ENV=dev) and redacted along with internal messages on non-public production errors.WithOnErrorreceives the original error and request in both cases. Public 4xx errors log at DEBUG; all other errors log at ERROR.API surface
What is deliberately left out
Each of these can be added in a minor release; none can be removed after v2 ships.
ServeMuxalready matches method and exact path, andhttp.StripPrefixcovers base paths.github.com/rs/cors;DefaultAllowedHeadersandDefaultExposedHeadersconfigure them for the Genkit and W3C trace headers.ListenAndServehelper. Graceful shutdown of long SSE streams depends on the deploy target;http.ServerandHandler.Shutdownleave that to the application.genkit.Initcatches no signals, so a plainhttp.ListenAndServeends on Ctrl+C.ActionContextValue[any]returns one value as stored.ActionContextValue[T]with a name constant covers what a key type would, and plaincontext.WithValuecovers values only Go reads.AllAgentRoutesorAllFlowRoutes. What to expose is the app's choice, andgenkitx.ListAgentsincludes remote-agent proxies, which would serve as an open relay calling other services with the app's credentials.