-
Notifications
You must be signed in to change notification settings - Fork 59
fix(multipart): handle typed nil readers consistently #90
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sylvesterkaczmarek
wants to merge
9
commits into
openai:main
Choose a base branch
from
sylvesterkaczmarek:fix/apiform-typed-nil-reader
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+221
−9
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
b262215
fix(apiform): handle typed nil readers before interface dispatch
sylvesterkaczmarek 6dec6c7
test(apiform): cover typed nil readers
sylvesterkaczmarek e6eeec6
fix(apiform): unwrap reader interfaces before nil checks
jbeckwith-oai 002eae1
Merge branch 'main' into fix/apiform-typed-nil-reader
jbeckwith-oai 2805fed
Merge branch 'main' into fix/apiform-typed-nil-reader
jbeckwith-oai 4673ec5
fix: classify typed nil readers as scalar multipart fields
sylvesterkaczmarek 1875918
test: preserve retries and redirects for typed nil multipart fields
sylvesterkaczmarek 3dc0aae
chore: keep multipart body diff focused
sylvesterkaczmarek 1c59bac
test: cover typed nil reader beside known upload
sylvesterkaczmarek File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| package apiform | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "io" | ||
| "mime/multipart" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| type panicOnRead struct{} | ||
|
|
||
| func (*panicOnRead) Read([]byte) (int, error) { | ||
| panic("Read called on typed nil receiver") | ||
| } | ||
|
|
||
| func TestMarshalTreatsTypedNilReaderAsEmptyField(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| var concrete *panicOnRead | ||
| var reader io.Reader = concrete | ||
| tests := map[string]any{ | ||
| "concrete pointer in any map": map[string]any{"file": concrete}, | ||
| "pointer in reader map": map[string]io.Reader{"file": reader}, | ||
| "nil reader interface": map[string]io.Reader{"file": nil}, | ||
| } | ||
|
|
||
| for name, value := range tests { | ||
| t.Run(name, func(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| var buf bytes.Buffer | ||
| writer := multipart.NewWriter(&buf) | ||
| require.NoError(t, writer.SetBoundary("xxx")) | ||
|
|
||
| require.NotPanics(t, func() { | ||
| require.NoError(t, Marshal(value, writer)) | ||
| require.NoError(t, writer.Close()) | ||
| }) | ||
|
|
||
| require.Equal(t, | ||
| "--xxx\r\nContent-Disposition: form-data; name=\"file\"\r\n\r\n\r\n--xxx--\r\n", | ||
| buf.String(), | ||
| ) | ||
| }) | ||
| } | ||
| } |
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| package cmd | ||
|
|
||
| import ( | ||
| "context" | ||
| "io" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "os" | ||
| "path/filepath" | ||
| "strings" | ||
| "sync/atomic" | ||
| "testing" | ||
|
|
||
| "github.com/openai/openai-cli/internal/apiform" | ||
| "github.com/openai/openai-go/v3" | ||
| "github.com/openai/openai-go/v3/option" | ||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func typedNilMultipartReader() io.Reader { | ||
| var reader *strings.Reader | ||
| return reader | ||
| } | ||
|
|
||
| func TestInspectMultipartBodyTreatsTypedNilReaderAsScalar(t *testing.T) { | ||
| info := inspectMultipartBody(map[string]any{"file": typedNilMultipartReader()}) | ||
|
|
||
| require.False(t, info.hasUpload) | ||
| require.True(t, info.knownLength) | ||
| } | ||
|
|
||
| func TestMultipartRequestOptionsRetryTypedNilReaderAsScalar(t *testing.T) { | ||
| var requestCount atomic.Int32 | ||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| requestCount.Add(1) | ||
| if !assert.NoError(t, r.ParseMultipartForm(1<<20)) { | ||
| http.Error(w, "invalid multipart form", http.StatusBadRequest) | ||
| return | ||
| } | ||
| assert.Equal(t, []string{""}, r.MultipartForm.Value["file"]) | ||
| assert.Empty(t, r.MultipartForm.File["file"]) | ||
| assert.Positive(t, r.ContentLength) | ||
|
|
||
| w.Header().Set("Content-Type", "application/json") | ||
| if requestCount.Load() == 1 { | ||
| w.Header().Set("Retry-After", "0") | ||
| w.WriteHeader(http.StatusTooManyRequests) | ||
| _, _ = io.WriteString(w, `{"error":{"message":"retry me","type":"rate_limit_error"}}`) | ||
| return | ||
| } | ||
| _, _ = io.WriteString(w, `{"id":"video_123","object":"video","status":"queued"}`) | ||
| })) | ||
| t.Cleanup(server.Close) | ||
|
|
||
| options, err := multipartRequestOptions(map[string]any{ | ||
| "file": typedNilMultipartReader(), | ||
| "prompt": "hello", | ||
| }, apiform.FormatBrackets) | ||
| require.NoError(t, err) | ||
| client := openai.NewClient( | ||
| option.WithAPIKey("test-key"), | ||
| option.WithBaseURL(server.URL+"/"), | ||
| ) | ||
|
|
||
| _, err = client.Videos.New(context.Background(), openai.VideoNewParams{}, options...) | ||
| require.NoError(t, err) | ||
| require.Equal(t, int32(2), requestCount.Load()) | ||
| } | ||
|
|
||
| func TestMultipartRequestOptionsReplayTypedNilReaderAcrossRedirects(t *testing.T) { | ||
| for _, status := range []int{http.StatusTemporaryRedirect, http.StatusPermanentRedirect} { | ||
| t.Run(http.StatusText(status), func(t *testing.T) { | ||
| var requestCount atomic.Int32 | ||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| requestCount.Add(1) | ||
| if r.URL.Path != "/redirected" { | ||
| http.Redirect(w, r, "/redirected", status) | ||
| return | ||
| } | ||
|
|
||
| if !assert.NoError(t, r.ParseMultipartForm(1<<20)) { | ||
| http.Error(w, "invalid multipart form", http.StatusBadRequest) | ||
| return | ||
| } | ||
| assert.Equal(t, []string{""}, r.MultipartForm.Value["file"]) | ||
| assert.Empty(t, r.MultipartForm.File["file"]) | ||
| assert.Positive(t, r.ContentLength) | ||
| w.Header().Set("Content-Type", "application/json") | ||
| _, _ = io.WriteString(w, `{"id":"video_123","object":"video","status":"queued"}`) | ||
| })) | ||
| t.Cleanup(server.Close) | ||
|
|
||
| options, err := multipartRequestOptions(map[string]any{ | ||
| "file": typedNilMultipartReader(), | ||
| "prompt": "hello", | ||
| }, apiform.FormatBrackets) | ||
| require.NoError(t, err) | ||
| client := openai.NewClient( | ||
| option.WithAPIKey("test-key"), | ||
| option.WithBaseURL(server.URL+"/"), | ||
| ) | ||
|
|
||
| _, err = client.Videos.New(context.Background(), openai.VideoNewParams{}, options...) | ||
| require.NoError(t, err) | ||
| require.Equal(t, int32(2), requestCount.Load()) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestMultipartRequestOptionsKnownUploadAllowsTypedNilReaderField(t *testing.T) { | ||
| path := filepath.Join(t.TempDir(), "payload.txt") | ||
| require.NoError(t, os.WriteFile(path, []byte("payload"), 0o600)) | ||
| upload, err := openFileUpload(path) | ||
| require.NoError(t, err) | ||
|
|
||
| var requestCount atomic.Int32 | ||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| requestCount.Add(1) | ||
| assert.Positive(t, r.ContentLength) | ||
| if !assert.NoError(t, r.ParseMultipartForm(1<<20)) { | ||
| http.Error(w, "invalid multipart form", http.StatusBadRequest) | ||
| return | ||
| } | ||
| assert.Equal(t, []string{""}, r.MultipartForm.Value["optional"]) | ||
| assert.Len(t, r.MultipartForm.File["file"], 1) | ||
| w.Header().Set("Content-Type", "application/json") | ||
| _, _ = io.WriteString(w, `{"id":"file_123","object":"file","bytes":7,"filename":"payload.txt","purpose":"assistants"}`) | ||
| })) | ||
| t.Cleanup(server.Close) | ||
|
|
||
| options, err := multipartRequestOptions(map[string]any{ | ||
| "file": upload, | ||
| "optional": typedNilMultipartReader(), | ||
| "purpose": "assistants", | ||
| }, apiform.FormatBrackets) | ||
| require.NoError(t, err) | ||
| client := openai.NewClient( | ||
| option.WithAPIKey("test-key"), | ||
| option.WithBaseURL(server.URL+"/"), | ||
| ) | ||
|
|
||
| _, err = client.Files.New(context.Background(), openai.FileNewParams{}, options...) | ||
| require.NoError(t, err) | ||
| require.Equal(t, int32(1), requestCount.Load()) | ||
| } |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[P2] Apply the same typed-nil semantics before choosing multipart transport. This branch correctly serializes a typed-nil reader as an empty scalar field, but
pkg/cmd/multipartbody.go:inspectMultipartBodystill sees the non-nilio.Readerinterface and marks it ashasUpload. As a result,multipartRequestOptionsunnecessarily selects one-shot streaming, appliesoption.WithMaxRetries(0), and rejects otherwise replayable 307/308 redirects. I verified the mismatch end to end with a synthetic HTTP 429 response: the empty-field request made one attempt and failed instead of retrying. Please update the upload classifier to recognize typed-nil readers as scalars and add a request-level retry regression.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed. The transport classifier now applies the same typed-nil reader semantics as the encoder, so typed-nil readers stay on the buffered scalar path instead of being treated as uploads. I also updated the known-length framing path so a typed-nil optional reader can coexist with a real file upload.
Added request-level regressions covering the reported 429 retry case, replay across both 307 and 308 redirects, buffered Content-Length, the empty scalar-field representation, and a known-length file upload alongside a typed-nil reader.
Fresh CI, CodeQL and Castiron runs are currently action_required pending maintainer approval.