Skip to content

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

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

feat(examples): add OpenAI-compatible benchmark sample#686
FamousDirector wants to merge 3 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 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, usage, compatibility checks, configuration, 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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 4284fb96-b439-490c-b879-d75145fee541

📥 Commits

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

📒 Files selected for processing (7)
  • examples/function-samples/load-tester-supreme/README.md
  • examples/function-samples/openai-compatible-sample/Dockerfile
  • 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
🚧 Files skipped from review as they are similar to previous changes (5)
  • examples/function-samples/load-tester-supreme/README.md
  • examples/function-samples/openai-compatible-sample/http-server/main.go
  • examples/function-samples/openai-compatible-sample/Dockerfile
  • examples/load-tests/README.md
  • examples/function-samples/openai-compatible-sample/http-server/main_test.go

📝 Walkthrough

Walkthrough

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

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 tests
examples/function-samples/openai-compatible-sample/http-server/main_test.go
Exercises JSON responses, SSE output, header controls, invalid inputs, injected failures, concurrency limits, model listing, 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

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 uses valid Conventional Commit syntax and accurately describes the new OpenAI-compatible benchmark sample.
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

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.12.2)

level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain main module or its selected dependencies"


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>
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