Skip to content

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

Merged
FamousDirector merged 7 commits into
mainfrom
jcameron/feat/load-tester-openai-benchmark-controls
Sep 29, 2026
Merged

FamousDirector merged 7 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. Existing examples lack one synthetic target that exercises common OpenAI API routes and streaming behavior without a model deployment.

Additional Details

  • Serve Chat Completions, Responses, Completions, Embeddings, and Models endpoints.
  • Provide request controls for queue delay, time to first token, inter-token latency, chunk shape, output count, injected failures, stream stops, and concurrency limits.
  • Add OpenAI-shaped errors, output limits, streaming tests, and a Python OpenAI client compatibility check.
  • Add a Responses SSE load test and update the load tester Go builder to match its Go 1.23 module declaration.
  • Resolve the current main conflict in the examples table and address review comments about test request contexts and redundant assignments.
  • Image and file APIs remain outside this sample's scope.

For the Reviewer

Review benchmark control validation and stream termination in examples/function-samples/openai-compatible-sample/http-server/main.go.

For QA

  • go test ./... and go vet ./... passed in the sample Go module.
  • docker build -t openai-compatible-sample:pr-686 . passed.
  • Container smoke check passed for /health and /v1/responses.
  • Prior PR validation included go test -race ./... and an OpenAI Python SDK check. These were not rerun after the merge with main.

QA Needed: No. This is a sample-only change with focused local coverage.

Issues

Closes #2170

Dependencies

No new third-party module in the sample. Dockerfile uses golang:1.23 and alpine:3.20; load-test extension remains as documented. License and NOTICE checks passed on the prior PR head. CI will rerun on the updated head.

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.

Add controllable OpenAI endpoints for SDK and load testing.

NO-REF

Signed-off-by: jcameron <[email protected]>
@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
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title follows Conventional Commits format and accurately describes the primary feature: adding an OpenAI-compatible benchmark sample.
  • Fix all pre-merge checks with AI
✨ 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
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 <[email protected]>

@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

@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

Comment thread examples/function-samples/openai-compatible-sample/http-server/main_test.go Outdated

@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 thread examples/function-samples/openai-compatible-sample/http-server/main.go Outdated
@FamousDirector
FamousDirector added this pull request to the merge queue Sep 29, 2026
Merged via the queue into main with commit df5b059 Sep 29, 2026
25 checks passed
@FamousDirector
FamousDirector deleted the jcameron/feat/load-tester-openai-benchmark-controls branch September 29, 2026 20:01
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.

feat(examples): add OpenAI-compatible benchmark sample

2 participants