Skip to content

handlers: do not append an error envelope to a response already streaming - #4938

Open
nishthaGupta wants to merge 1 commit into
distribution:mainfrom
nishthaGupta:handlers-no-error-envelope-after-response-started
Open

nishthaGupta wants to merge 1 commit into
distribution:mainfrom
nishthaGupta:handlers-no-error-envelope-after-response-started

Conversation

@nishthaGupta

Copy link
Copy Markdown

Fixes #4937

Problem

When a handler fails part way through writing the response body, the dispatcher still calls errcode.ServeJSON in its deferred error handling (registry/handlers/app.go). The status line and headers are already sent, so net/http discards the second WriteHeader and logs http: superfluous response.WriteHeader call, but the JSON is still encoded onto the connection. The client ends up with a truncated payload plus an error object appended to it, under the original status and a Content-Length that is never reached.

It also makes the request log inaccurate. errcode.ServeJSON sets Content-Type: application/json and calls WriteHeader(500), and while net/http ignores both, instrumentedResponseWriter records them, so GetResponseLogger reports http.response.status=500 http.response.contenttype=application/json for a response the client received as 200 application/octet-stream.

This shows up in proxy (pull-through cache) mode when an upstream read fails mid-layer. On one deployment over a week, 67 requests had written more than 100 KB of layer data before the envelope went out, the largest 71 MB.

Fix

Skip the envelope once body bytes have been written, and log the errors instead. written > 0 comes from http.response.written, which instrumentedResponseWriter already exposes via Context.Value, so no new plumbing is needed.

Header-only writes are deliberately unaffected: a handler that sets its own status but writes no body can still have an envelope appended, which is the existing behaviour that layer upload range errors depend on.

This does not change which requests succeed or fail. A response that reached this path was already truncated. It stops the registry writing JSON onto the tail of that truncated body, and it keeps the logged status and content type describing what was actually sent.

Diff

--- a/registry/handlers/app.go
+++ b/registry/handlers/app.go
@@ -720,7 +720,17 @@ func (app *App) dispatcher(dispatch dispatchFunc) http.Handler {
 			// own errors if they need different behavior (such as range errors
 			// for layer upload).
 			if context.Errors.Len() > 0 {
-				_ = errcode.ServeJSON(w, context.Errors)
+				if responseStarted(context) {
+					// The handler already began streaming the response body,
+					// which happens when a read fails part way through, so the
+					// error envelope cannot be delivered: net/http discards the
+					// second WriteHeader and the JSON would be appended to the
+					// partial payload the client is still reading. Record the
+					// error instead of corrupting the response.
+					dcontext.GetLogger(context).Errorf("error after response body started, not serving error envelope: %v", context.Errors)
+				} else {
+					_ = errcode.ServeJSON(w, context.Errors)
+				}
 				app.logError(context, context.Errors)
 			} else if status, ok := context.Value("http.response.status").(int); ok && status >= 200 && status <= 399 {
 				dcontext.GetResponseLogger(context).Infof("response completed")
@@ -793,6 +803,15 @@ func (app *App) dispatcher(dispatch dispatchFunc) http.Handler {
 	})
 }

+// responseStarted reports whether any response body bytes have already been
+// written for this request. Header-only writes do not count: a handler that
+// sets its own status but no body can still have an error envelope appended,
+// which is the existing behaviour for layer upload range errors.
+func responseStarted(ctx context.Context) bool {
+	written, ok := ctx.Value("http.response.written").(int64)
+	return ok && written > 0
+}
+
 type errCodeKey struct{}

Tests

TestDispatcherErrorEnvelopeAfterResponseStarted in registry/handlers/app_test.go covers both branches: a handler that writes partial content keeps its body and status, and a handler that writes nothing still gets the envelope. It reuses the existing inmemory driver plus memorycache scaffolding already used by TestAppDispatcher, and adds io to the test imports.

Notes for reviewers

  • Reading http.response.written through Context.Value keeps the change to one file and matches how the surrounding code reads http.response.status. Happy to switch to asserting on the ResponseWriter if you would rather not depend on the context key here.
  • This is a client-visible behaviour change in the failure path, so it may warrant a release note.

Verifying the test catches it

With only the test applied and app.go left as-is on main:

--- FAIL: TestDispatcherErrorEnvelopeAfterResponseStarted/response_already_started
    app_test.go:347: error envelope leaked into a started response:
      "partial blob{\"errors\":[{\"code\":\"UNKNOWN\",\"message\":\"unknown error\",\"detail\":\"upstream read failed\"}]}\n"
      != "partial blob"

With the fix, both subtests pass and the full ./registry/handlers/ package is green.

…ming

When a handler fails part way through writing the response body, the
dispatcher still called errcode.ServeJSON. The status line and headers are
already on the wire at that point, so net/http discards the second
WriteHeader and logs "superfluous response.WriteHeader call", but the JSON
is still encoded onto the connection. The client receives a truncated
payload with an error object appended to it, under the original status and
a Content-Length it never reaches.

It also makes the request log inaccurate: errcode.ServeJSON sets
Content-Type: application/json and calls WriteHeader(500), and while
net/http ignores both, instrumentedResponseWriter records them, so
GetResponseLogger reports status 500 and content type application/json for
a response the client received as 200 application/octet-stream.

Skip the envelope once body bytes have been written and log the errors
instead. Header-only writes are unaffected, so a handler that sets its own
status but writes no body still gets an envelope, which is the existing
behaviour for layer upload range errors.

This does not change which requests succeed or fail. A response that
reaches this path was already truncated. It stops the registry writing JSON
onto the tail of that truncated body, and keeps the logged status and
content type describing what was actually sent.

Signed-off-by: Nishtha Gupta <[email protected]>
@milosgajdos

milosgajdos commented Sep 21, 2026 •

Copy link
Copy Markdown
Member

Hey @nishthaGupta can you rebase?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Error envelope is appended to a response body that has already started streaming

2 participants