Skip to content

feat(examples): add OpenAI-compatible benchmark sample - #686

Open
FamousDirector wants to merge 6 commits into
mainfrom
jcameron/feat/load-tester-openai-benchmark-controls
Open

feat(examples): add OpenAI-compatible benchmark sample#686
FamousDirector wants to merge 6 commits into
mainfrom
jcameron/feat/load-tester-openai-benchmark-controls

Conversation

@FamousDirector

@FamousDirector FamousDirector commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

TL;DR

Add a controllable OpenAI-compatible function sample for SDK and load-test benchmarking.

Additional Details

  • Adds Chat Completions, Responses, Completions, Embeddings, and Models endpoints.
  • Keeps benchmark controls header-only: queue delay, TTFT, ITL, jitter, chunk shape, output count, injected failures, stream stops, and concurrency limits.
  • Adds OpenAI-shaped errors, output limits, SSE lifecycle coverage, and a public OpenAI Python client compatibility check.
  • Updates the existing load tester Go builder to match its Go 1.23 module declaration.
  • Image and file APIs remain out of scope for this benchmark target.

For the Reviewer

Review benchmark header validation and stream termination behavior in the sample server. The client check exercises strict response validation through the public OpenAI Python SDK.

For QA

  • go test ./...
  • go vet ./...
  • go test -race ./...
  • docker build -t openai-compatible-sample:pr-test .
  • OpenAI Python SDK check against the local Go server and the built container

QA Needed: No. Sample-only change with automated and local SDK coverage.

Issues

NO-REF

Checklist

  • I am familiar with the Contributing Guidelines.
  • I have signed off my commits for Developer Certificate of Origin compliance.
  • New or existing tests cover these changes.
  • The documentation is up to date with these changes.

Summary by CodeRabbit

  • New Features
    • Added an OpenAI-compatible sample server supporting Responses, Chat Completions, Completions, Embeddings, and model endpoints.
    • Added configurable streaming behavior, latency simulation, errors, limits, and concurrency controls.
    • Added containerized deployment support for the sample server.
    • Added an SSE load test with calibration and sustained-load profiles.
    • Added an OpenAI Python client compatibility check.
  • Documentation
    • Expanded sample and load-test documentation with setup, configuration, compatibility checks, and benchmark examples.
  • Tests
    • Added comprehensive endpoint, streaming, validation, error-handling, and concurrency coverage.

Add controllable OpenAI endpoints for SDK and load testing.

NO-REF

Signed-off-by: jcameron <jcameron@nvidia.com>
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds an OpenAI-compatible Go HTTP server with JSON and SSE endpoints, validation tests, compatibility checks, Docker packaging, documentation, and a k6 Responses SSE load test.

Changes

OpenAI-compatible sample

Layer / File(s) Summary
Server contracts and request handling
examples/function-samples/openai-compatible-sample/http-server/...
Defines API payloads, routes, tuning controls, response construction, streaming behavior, and deterministic embeddings.
Streaming and endpoint validation
examples/function-samples/openai-compatible-sample/http-server/main_test.go
Tests JSON responses, SSE output, header controls, invalid inputs, injected failures, concurrency limits, models, completions, and embeddings.
Compatibility checks and sample packaging
examples/function-samples/openai-compatible-sample/..., examples/README.md, examples/function-samples/load-tester-supreme/...
Adds Docker packaging, usage documentation, an OpenAI Python compatibility check, sample registration, and Go 1.23 updates.
Responses SSE load benchmark
examples/load-tests/functions/oai_compatible_responses_sse_load_test.js, examples/load-tests/README.md
Adds calibration and sustained-load k6 profiles with SSE parsing, metrics, thresholds, request controls, and configuration documentation.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant HTTPServer
  participant K6LoadTest
  participant OpenAIClient
  Client->>HTTPServer: Send OpenAI-compatible request
  OpenAIClient->>HTTPServer: Run compatibility checks
  K6LoadTest->>HTTPServer: Send Responses SSE load
  HTTPServer-->>Client: Return JSON or SSE events
  HTTPServer-->>OpenAIClient: Return validated API response
  HTTPServer-->>K6LoadTest: Stream response events and timing data
Loading

Suggested reviewers: rohithb-hub

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title follows Conventional Commits and accurately describes the primary feature added by the pull request.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch jcameron/feat/load-tester-openai-benchmark-controls

Comment @coderabbitai help to get the list of available commands.

@FamousDirector
FamousDirector marked this pull request as ready for review August 5, 2026 14:53
@FamousDirector
FamousDirector requested a review from a team as a code owner August 5, 2026 14:53

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 8

🧹 Nitpick comments (4)
examples/function-samples/openai-compatible-sample/http-server/main_test.go (1)

245-247: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reset the shared gauge in cleanup.

activeRequests is package-level state shared by every test. This test resets it only at the start. If an assertion fails while the first request still holds a slot, the gauge stays non-zero for later tests. Add a cleanup reset.

Proposed refactor
 	activeRequests.Store(0)
+	t.Cleanup(func() { activeRequests.Store(0) })
 	router := newRouter()
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/function-samples/openai-compatible-sample/http-server/main_test.go`
around lines 245 - 247, Update TestConcurrencyLimit to register a cleanup reset
for the shared activeRequests gauge, ensuring it is restored to zero even when
the test fails before its normal completion. Keep the existing initial reset and
use the test cleanup mechanism so later tests cannot inherit stale state.
examples/function-samples/openai-compatible-sample/http-server/main.go (3)

880-883: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Extract the SSE header setup.

The same three-header block appears in streamResponses (lines 881-883), streamChatCompletion (lines 964-966), and streamCompletion (lines 1045-1047). Extract one helper so SSE header changes apply in one place.

Also note that Go's HTTP server manages Connection itself and strips it for HTTP/2, so that header has no effect. Consider dropping it from the helper.

Proposed refactor
+func setSSEHeaders(w http.ResponseWriter) {
+	w.Header().Set("Cache-Control", "no-cache")
+	w.Header().Set("Content-Type", "text/event-stream")
+}
+
 func streamResponses(ctx context.Context, w http.ResponseWriter, response responsesResponse, chunks []string, tuning benchmarkTuning) {
-	w.Header().Set("Cache-Control", "no-cache")
-	w.Header().Set("Content-Type", "text/event-stream")
-	w.Header().Set("Connection", "keep-alive")
+	setSSEHeaders(w)

Apply the same replacement in streamChatCompletion and streamCompletion.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/function-samples/openai-compatible-sample/http-server/main.go`
around lines 880 - 883, Extract the repeated SSE header setup from
streamResponses, streamChatCompletion, and streamCompletion into a shared helper
so all three call the same header-setting logic. Update that helper to set the
common SSE headers in one place and remove the Connection header from the shared
setup, since net/http manages it and it has no effect here. Keep the existing
streaming behavior unchanged aside from centralizing the header configuration.

655-665: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Drop the unused error return from outputChunks.

outputChunks never returns a non-nil error. Validation already happens in resolveBenchmarkTuning. The current signature creates three unreachable 400 branches in handleResponses, handleChatCompletions, and handleCompletions.

Proposed refactor
-func outputChunks(tuning benchmarkTuning) ([]string, error) {
+func outputChunks(tuning benchmarkTuning) []string {
 	chunks := make([]string, tuning.OutputChunks)
 	for index := range chunks {
 		chunk := tuning.Chunk
 		if tuning.ChunkBytes > 0 {
 			chunk = randomText(tuning.ChunkBytes)
 		}
 		chunks[index] = chunk
 	}
-	return chunks, nil
+	return chunks
 }

Then in each handler:

chunks := outputChunks(tuning)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/function-samples/openai-compatible-sample/http-server/main.go`
around lines 655 - 665, Update outputChunks to return only []string, removing
its unused error result and adjusting the return statement. Update
handleResponses, handleChatCompletions, and handleCompletions to call
outputChunks without error handling, removing the unreachable 400-response
branches while preserving their existing chunk-processing behavior.

272-280: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Bound body reads and idle connections.

The server sets only ReadHeaderTimeout. A client that sends headers and then stalls the body, or that keeps an idle connection open, retains a connection and a goroutine without limit. Add ReadTimeout and IdleTimeout.

Do not add WriteTimeout. SSE responses can run for minutes because X-Load-Tester-ITL-Ms and X-Load-Tester-Output-Chunks control the stream duration, and WriteTimeout would abort valid streams.

Proposed fix
 	server := &http.Server{
 		Addr:              ":8000",
 		Handler:           newRouter(),
 		ReadHeaderTimeout: 5 * time.Second,
+		ReadTimeout:       30 * time.Second,
+		IdleTimeout:       120 * time.Second,
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/function-samples/openai-compatible-sample/http-server/main.go`
around lines 272 - 280, Update the http.Server initialization in main to add
ReadTimeout for bounding request body reads and IdleTimeout for limiting
keep-alive connections. Preserve ReadHeaderTimeout and do not add WriteTimeout,
so long-running SSE responses controlled by X-Load-Tester-ITL-Ms and
X-Load-Tester-Output-Chunks continue uninterrupted.

Source: Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@examples/function-samples/load-tester-supreme/README.md`:
- Line 22: Update the message field documentation in the load-tester README to
specify protocol-specific requirements: require message for HTTP requests, while
allowing it to be omitted for gRPC and documenting that omission returns an
empty string.

In `@examples/function-samples/openai-compatible-sample/Dockerfile`:
- Around line 24-30: Update the final alpine stage after copying the binary to
create an unprivileged user named app, assign ownership of
/app/openai-compatible-sample to that user, and set USER app before CMD so the
server runs without root privileges.

In
`@examples/function-samples/openai-compatible-sample/http-server/openai_client_check.py`:
- Line 41: Replace every assertion in openai_client_check.py, including the
checks around response.output_text and the other listed validation points, with
explicit conditional checks that raise an error when expectations fail. Ensure
all compatibility checks still execute under python3 -O and success is printed
only after every condition passes.
- Around line 24-28: Update the OpenAI client initialization in the CLIENT
configuration to disable redirects for credentialed requests by supplying an
httpx.Client with follow_redirects set to false through http_client, while
preserving the existing base URL and authentication settings.
- Around line 24-28: In the OpenAI client initialization around BASE_URL and
OPENAI_API_KEY, validate that any non-placeholder API key is only used with an
HTTPS base URL. Preserve the local HTTP URL for the default "not-needed" key,
and reject or fail fast when a real key is configured with an HTTP URL before
constructing CLIENT.

In `@examples/load-tests/functions/oai_compatible_responses_sse_load_test.js`:
- Around line 219-224: Remove the unsupported timeout configuration from the
load-test options and eliminate the related OPENAI_RESPONSES_TIMEOUT
environment-variable usage, unless upgrading xk6-sse and implementing verified
timeout behavior through the sse.open call. Ensure the stream setup does not
pass a silently ignored timeout value.
- Around line 283-296: Update the request configuration returned by the OpenAI
Responses SSE load-test request builder to reject redirects before sending
credentialed requests with TOKEN. Since xk6-sse v0.1.7 does not expose a
redirects option, apply the required client/extension configuration rather than
adding an unsupported request field, while preserving the existing POST body,
headers, timeout, and tags.
- Around line 272-274: Update the header setup around config.token so the
OAI_COMPAT_URL is validated before assigning headers.Authorization. Reject HTTP
endpoints unless they target an explicit loopback host, while allowing HTTPS
endpoints, and only add the Bearer token after this validation succeeds.

---

Nitpick comments:
In `@examples/function-samples/openai-compatible-sample/http-server/main_test.go`:
- Around line 245-247: Update TestConcurrencyLimit to register a cleanup reset
for the shared activeRequests gauge, ensuring it is restored to zero even when
the test fails before its normal completion. Keep the existing initial reset and
use the test cleanup mechanism so later tests cannot inherit stale state.

In `@examples/function-samples/openai-compatible-sample/http-server/main.go`:
- Around line 880-883: Extract the repeated SSE header setup from
streamResponses, streamChatCompletion, and streamCompletion into a shared helper
so all three call the same header-setting logic. Update that helper to set the
common SSE headers in one place and remove the Connection header from the shared
setup, since net/http manages it and it has no effect here. Keep the existing
streaming behavior unchanged aside from centralizing the header configuration.
- Around line 655-665: Update outputChunks to return only []string, removing its
unused error result and adjusting the return statement. Update handleResponses,
handleChatCompletions, and handleCompletions to call outputChunks without error
handling, removing the unreachable 400-response branches while preserving their
existing chunk-processing behavior.
- Around line 272-280: Update the http.Server initialization in main to add
ReadTimeout for bounding request body reads and IdleTimeout for limiting
keep-alive connections. Preserve ReadHeaderTimeout and do not add WriteTimeout,
so long-running SSE responses controlled by X-Load-Tester-ITL-Ms and
X-Load-Tester-Output-Chunks continue uninterrupted.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 007b31ca-4460-4a32-9404-6b5c5c9e701f

📥 Commits

Reviewing files that changed from the base of the PR and between 6982d5b and b2e076a.

📒 Files selected for processing (11)
  • examples/README.md
  • examples/function-samples/load-tester-supreme/Dockerfile
  • examples/function-samples/load-tester-supreme/README.md
  • examples/function-samples/openai-compatible-sample/Dockerfile
  • examples/function-samples/openai-compatible-sample/README.md
  • examples/function-samples/openai-compatible-sample/http-server/go.mod
  • examples/function-samples/openai-compatible-sample/http-server/main.go
  • examples/function-samples/openai-compatible-sample/http-server/main_test.go
  • examples/function-samples/openai-compatible-sample/http-server/openai_client_check.py
  • examples/load-tests/README.md
  • examples/load-tests/functions/oai_compatible_responses_sse_load_test.js

Comment thread examples/function-samples/load-tester-supreme/README.md Outdated
Comment thread examples/function-samples/openai-compatible-sample/Dockerfile
Comment thread examples/load-tests/functions/oai_compatible_responses_sse_load_test.js Outdated
Signed-off-by: jcameron <jcameron@nvidia.com>
Reduce allocation and write overhead for long-lived OpenAI-compatible SSE streams while retaining compatible event and timing behavior.

NO-REF

Signed-off-by: jcameron <jcameron@nvidia.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
examples/function-samples/openai-compatible-sample/http-server/main_test.go (1)

470-478: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a positive assertion for the truncated Responses stream.

The block asserts only the absence of event: error and event: response.completed. An empty body, or a body truncated before the first delta, also satisfies both conditions. Assert the delta count that truncation is expected to emit, so the test detects a regression that stops the stream too early.

♻️ Proposed assertion
 	body = recorder.Body.String()
 	if strings.Contains(body, "event: error") || strings.Contains(body, "event: response.completed") {
 		t.Fatalf("truncated Responses stream unexpectedly terminated: %s", body)
 	}
+	if got := strings.Count(body, "event: response.output_text.delta\n"); got != 1 {
+		t.Fatalf("truncated Responses deltas = %d, want 1: %s", got, body)
+	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/function-samples/openai-compatible-sample/http-server/main_test.go`
around lines 470 - 478, The truncated Responses stream test around
postJSONWithHeaders must positively verify that the expected number of delta
events was emitted, not only that terminal events are absent. Add an assertion
using the stream’s existing delta event marker to confirm truncation after the
configured boundary produces the expected delta count, while preserving the
current error and response.completed checks.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@examples/function-samples/openai-compatible-sample/http-server/main_test.go`:
- Around line 470-478: The truncated Responses stream test around
postJSONWithHeaders must positively verify that the expected number of delta
events was emitted, not only that terminal events are absent. Add an assertion
using the stream’s existing delta event marker to confirm truncation after the
configured boundary produces the expected delta count, while preserving the
current error and response.completed checks.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 1f921b5c-74e8-4112-8897-58d43ed2d517

📥 Commits

Reviewing files that changed from the base of the PR and between fe6d4e5 and d8c7cf0.

📒 Files selected for processing (4)
  • examples/function-samples/openai-compatible-sample/README.md
  • examples/function-samples/openai-compatible-sample/http-server/main.go
  • examples/function-samples/openai-compatible-sample/http-server/main_test.go
  • examples/load-tests/README.md
🚧 Files skipped from review as they are similar to previous changes (3)
  • examples/load-tests/README.md
  • examples/function-samples/openai-compatible-sample/http-server/main.go
  • examples/function-samples/openai-compatible-sample/README.md

NO-REF

Signed-off-by: jcameron <jcameron@nvidia.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@examples/function-samples/openai-compatible-sample/http-server/main_test.go`:
- Line 350: Replace httptest.NewRequest with httptest.NewRequestWithContext at
both request construction sites in
examples/function-samples/openai-compatible-sample/http-server/main_test.go
lines 350-350 and 389-389, supplying an explicit context while preserving the
existing method, URL, and body arguments.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 6b89b433-911d-4a83-8377-8a3623777598

📥 Commits

Reviewing files that changed from the base of the PR and between d8c7cf0 and f99712b.

📒 Files selected for processing (4)
  • examples/function-samples/openai-compatible-sample/README.md
  • examples/function-samples/openai-compatible-sample/http-server/main.go
  • examples/function-samples/openai-compatible-sample/http-server/main_test.go
  • examples/load-tests/README.md
🚧 Files skipped from review as they are similar to previous changes (3)
  • examples/function-samples/openai-compatible-sample/README.md
  • examples/function-samples/openai-compatible-sample/http-server/main.go
  • examples/load-tests/README.md

{name: "above default maximum rejected", value: "6001", want: false},
} {
t.Run(test.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "/v1/responses", nil)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Use context-aware request construction.

golangci-lint reports noctx errors at both sites. Replace httptest.NewRequest with httptest.NewRequestWithContext and provide an explicit context.

  • examples/function-samples/openai-compatible-sample/http-server/main_test.go#L350-L350: Construct the request with httptest.NewRequestWithContext.
  • examples/function-samples/openai-compatible-sample/http-server/main_test.go#L389-L389: Construct the request with httptest.NewRequestWithContext.
🧰 Tools
🪛 golangci-lint (2.12.2)

[error] 350-350: net/http/httptest.NewRequest must not be called. use net/http/httptest.NewRequestWithContext

(noctx)

📍 Affects 1 file
  • examples/function-samples/openai-compatible-sample/http-server/main_test.go#L350-L350 (this comment)
  • examples/function-samples/openai-compatible-sample/http-server/main_test.go#L389-L389
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/function-samples/openai-compatible-sample/http-server/main_test.go`
at line 350, Replace httptest.NewRequest with httptest.NewRequestWithContext at
both request construction sites in
examples/function-samples/openai-compatible-sample/http-server/main_test.go
lines 350-350 and 389-389, supplying an explicit context while preserving the
existing method, URL, and body arguments.

Source: Linters/SAST tools

Signed-off-by: jcameron <jcameron@nvidia.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@examples/function-samples/openai-compatible-sample/http-server/main.go`:
- Around line 630-653: Remove the redundant initial assignments to
chunkBytesName, statusName, streamErrorName, and streamTruncateName in the
benchmark tuning logic; declare these variables directly through the
corresponding integerControl assignments while preserving the existing
returned-name behavior.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 7180828f-8e6e-448f-b782-2f2717412460

📥 Commits

Reviewing files that changed from the base of the PR and between f99712b and 783ff5b.

📒 Files selected for processing (3)
  • examples/function-samples/openai-compatible-sample/README.md
  • examples/function-samples/openai-compatible-sample/http-server/main.go
  • examples/function-samples/openai-compatible-sample/http-server/main_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • examples/function-samples/openai-compatible-sample/README.md
  • examples/function-samples/openai-compatible-sample/http-server/main_test.go

Comment on lines +630 to +653
chunkBytesName := headerChunkBytes
var hasChunkBytes bool
if tuning.ChunkBytes, hasChunkBytes, chunkBytesName, err = integerControl(r, headerChunkBytes, bodyChunkBytes, body.ChunkBytes, 0, 0, maxOutputBytes); err != nil {
return benchmarkTuning{}, err
}
if hasChunkBytes && tuning.ChunkBytes > 0 && hasChunk {
return benchmarkTuning{}, fmt.Errorf("%s and %s cannot be combined", chunkName, chunkBytesName)
}
if tuning.OutputChunks, _, _, err = integerControl(r, headerOutputChunks, bodyOutputChunks, body.OutputChunks, 1, 1, maxOutputChunks); err != nil {
return benchmarkTuning{}, err
}
statusName := headerStatusCode
if tuning.StatusCode, _, statusName, err = integerControl(r, headerStatusCode, bodyStatusCode, body.StatusCode, 0, 0, 599); err != nil {
return benchmarkTuning{}, err
}
if tuning.StatusCode != 0 && tuning.StatusCode < http.StatusBadRequest {
return benchmarkTuning{}, fmt.Errorf("%s must be an HTTP error status", statusName)
}
streamErrorName := headerStreamErrorAfter
if tuning.StreamErrorAfter, _, streamErrorName, err = integerControl(r, headerStreamErrorAfter, bodyStreamErrorAfter, body.StreamErrorAfter, -1, -1, tuning.OutputChunks); err != nil {
return benchmarkTuning{}, err
}
streamTruncateName := headerStreamTruncateAfter
if tuning.StreamTruncateAfter, _, streamTruncateName, err = integerControl(r, headerStreamTruncateAfter, bodyStreamTruncateAfter, body.StreamTruncateAfter, -1, -1, tuning.OutputChunks); err != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Remove the ineffectual initial assignments.

Line 630 assigns headerChunkBytes, but Line 632 overwrites chunkBytesName before use. The same issue occurs for statusName, streamErrorName, and streamTruncateName at Lines 641, 648, and 652. golangci-lint reports these as errors.

Proposed fix
-	chunkBytesName := headerChunkBytes
+	var chunkBytesName string
 	var hasChunkBytes bool
 	if tuning.ChunkBytes, hasChunkBytes, chunkBytesName, err = integerControl(r, headerChunkBytes, bodyChunkBytes, body.ChunkBytes, 0, 0, maxOutputBytes); err != nil {
 		return benchmarkTuning{}, err
 	}
@@
-	statusName := headerStatusCode
+	var statusName string
 	if tuning.StatusCode, _, statusName, err = integerControl(r, headerStatusCode, bodyStatusCode, body.StatusCode, 0, 0, 599); err != nil {
 		return benchmarkTuning{}, err
 	}
@@
-	streamErrorName := headerStreamErrorAfter
+	var streamErrorName string
 	if tuning.StreamErrorAfter, _, streamErrorName, err = integerControl(r, headerStreamErrorAfter, bodyStreamErrorAfter, body.StreamErrorAfter, -1, -1, tuning.OutputChunks); err != nil {
 		return benchmarkTuning{}, err
 	}
-	streamTruncateName := headerStreamTruncateAfter
+	var streamTruncateName string
 	if tuning.StreamTruncateAfter, _, streamTruncateName, err = integerControl(r, headerStreamTruncateAfter, bodyStreamTruncateAfter, body.StreamTruncateAfter, -1, -1, tuning.OutputChunks); err != nil {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
chunkBytesName := headerChunkBytes
var hasChunkBytes bool
if tuning.ChunkBytes, hasChunkBytes, chunkBytesName, err = integerControl(r, headerChunkBytes, bodyChunkBytes, body.ChunkBytes, 0, 0, maxOutputBytes); err != nil {
return benchmarkTuning{}, err
}
if hasChunkBytes && tuning.ChunkBytes > 0 && hasChunk {
return benchmarkTuning{}, fmt.Errorf("%s and %s cannot be combined", chunkName, chunkBytesName)
}
if tuning.OutputChunks, _, _, err = integerControl(r, headerOutputChunks, bodyOutputChunks, body.OutputChunks, 1, 1, maxOutputChunks); err != nil {
return benchmarkTuning{}, err
}
statusName := headerStatusCode
if tuning.StatusCode, _, statusName, err = integerControl(r, headerStatusCode, bodyStatusCode, body.StatusCode, 0, 0, 599); err != nil {
return benchmarkTuning{}, err
}
if tuning.StatusCode != 0 && tuning.StatusCode < http.StatusBadRequest {
return benchmarkTuning{}, fmt.Errorf("%s must be an HTTP error status", statusName)
}
streamErrorName := headerStreamErrorAfter
if tuning.StreamErrorAfter, _, streamErrorName, err = integerControl(r, headerStreamErrorAfter, bodyStreamErrorAfter, body.StreamErrorAfter, -1, -1, tuning.OutputChunks); err != nil {
return benchmarkTuning{}, err
}
streamTruncateName := headerStreamTruncateAfter
if tuning.StreamTruncateAfter, _, streamTruncateName, err = integerControl(r, headerStreamTruncateAfter, bodyStreamTruncateAfter, body.StreamTruncateAfter, -1, -1, tuning.OutputChunks); err != nil {
var chunkBytesName string
var hasChunkBytes bool
if tuning.ChunkBytes, hasChunkBytes, chunkBytesName, err = integerControl(r, headerChunkBytes, bodyChunkBytes, body.ChunkBytes, 0, 0, maxOutputBytes); err != nil {
return benchmarkTuning{}, err
}
if hasChunkBytes && tuning.ChunkBytes > 0 && hasChunk {
return benchmarkTuning{}, fmt.Errorf("%s and %s cannot be combined", chunkName, chunkBytesName)
}
if tuning.OutputChunks, _, _, err = integerControl(r, headerOutputChunks, bodyOutputChunks, body.OutputChunks, 1, 1, maxOutputChunks); err != nil {
return benchmarkTuning{}, err
}
var statusName string
if tuning.StatusCode, _, statusName, err = integerControl(r, headerStatusCode, bodyStatusCode, body.StatusCode, 0, 0, 599); err != nil {
return benchmarkTuning{}, err
}
if tuning.StatusCode != 0 && tuning.StatusCode < http.StatusBadRequest {
return benchmarkTuning{}, fmt.Errorf("%s must be an HTTP error status", statusName)
}
var streamErrorName string
if tuning.StreamErrorAfter, _, streamErrorName, err = integerControl(r, headerStreamErrorAfter, bodyStreamErrorAfter, body.StreamErrorAfter, -1, -1, tuning.OutputChunks); err != nil {
return benchmarkTuning{}, err
}
var streamTruncateName string
if tuning.StreamTruncateAfter, _, streamTruncateName, err = integerControl(r, headerStreamTruncateAfter, bodyStreamTruncateAfter, body.StreamTruncateAfter, -1, -1, tuning.OutputChunks); err != nil {
🧰 Tools
🪛 golangci-lint (2.12.2)

[error] 630-630: ineffectual assignment to chunkBytesName

(ineffassign)


[error] 641-641: ineffectual assignment to statusName

(ineffassign)


[error] 648-648: ineffectual assignment to streamErrorName

(ineffassign)


[error] 652-652: ineffectual assignment to streamTruncateName

(ineffassign)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/function-samples/openai-compatible-sample/http-server/main.go`
around lines 630 - 653, Remove the redundant initial assignments to
chunkBytesName, statusName, streamErrorName, and streamTruncateName in the
benchmark tuning logic; declare these variables directly through the
corresponding integerControl assignments while preserving the existing
returned-name behavior.

Source: Linters/SAST tools

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant