review: comment budget, declaration layout, request-path ownership - #48
Merged
Conversation
Free helper fns move below the type+impl blocks and public above private; HTTPClient and MockClient split into gateway/http and gateway/mock, matching the kv and user interface-parent/impl-subpackage layout.
Constant wire fields (role, object, finish_reason, reasoning effort) become Cow<'static, str>; the anthropic image url and the memory-store erasure lookup stop copying; the entrypoint reads config through tokio::fs and keeps a handle on the batch-drain task.
Type + impl blocks move ahead of the free fns in plugins.rs, public types first.
RtModeration::Deny carries Cow<'static, str>, and rt_error moves the message into the envelope instead of letting json! deep-copy it.
CMGS
added a commit
that referenced
this pull request
Sep 3, 2026
01e6087 switched the mock transport's reply encoding from v.to_string() to serde_json::to_vec. A per-commit bisect of PR #48 on the testbed put the whole +88k instructions per 48 KB request of the big-body regression on that line (p3 4,039k vs p4 4,127k instr/req; restoring the file returns to 4,039k), while the four production groups of that commit run the same instruction stream within 0.01%. The mock transport is benchmark and demo code; production uses the HTTP transport. The remaining rps spread between builds is code placement, not added work.
CMGS
added a commit
that referenced
this pull request
Sep 3, 2026
01e6087 switched the mock transport's reply encoding from v.to_string() to serde_json::to_vec. A per-commit bisect of PR #48 on the testbed put the whole +88k instructions per 48 KB request of the big-body regression on that line (p3 4,039k vs p4 4,127k instr/req; restoring the file returns to 4,039k), while the four production groups of that commit run the same instruction stream within 0.01%. The mock transport is benchmark and demo code; production uses the HTTP transport. The remaining rps spread between builds is code placement, not added work.
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Six review commits: comment budget, declaration layout, and ownership on the request path, first across the workspace and then over
crates/handler. Behaviour is unchanged except where an allocation is removed; the one shutdown change is that the batch-drain task is now aborted with its six siblings instead of being dropped at process exit.review: comment budgetreview: layoutreview: ownership on the request pathreview: one-line docs in handlerreview: layout in handlerreview: borrow the realtime denial reasonreview: comment budgetTwenty-one multi-line WHY blocks in
crates/views/src/lib.rscollapse to one line each, keeping the fact and dropping the narrative. Same treatment for one block incrates/config/src/lib.rs, the section label and the private-fn///incrates/server/src/main.rs, and the two-line godoc incontrol-plane/internal/user/user.goandinternal/gateway/gateway.go. Both inline comments insidecrates/models/src/cost.rs's test module are deleted. Every// SAFETY:line is untouched.review: layoutRust, declaration order only:
crates/config/src/lib.rs— the serde-default and hashing helpers (pick_variant,fnv1a,weight_one,default_priority, the six stabilitydefault_*,default_alert_dedup_seconds) move below the type+impl blocks, public free fn first.ProviderPresetis a private type, not a fn, so it moves with its sole consumerprovider_presetto the file tail and the type region stays public-only.crates/models/src/request.rs—is_protected_anthropic_blockmoves below the type blocks.crates/protocol/src/anthropic.rs—blocks_textmoves below the type blocks.crates/engines/src/realtime.rs—skip_scalaranddelta_is_textmove to the private tail.walkstays directly under its single callervisit_frame_text.crates/engines/src/openai_engine.rs— the publicmerge_tool_call_fragmentsmoves above the privateapply_sse_event.Go, the interface-parent/impl-subpackage split the module already uses for
kvanduser:gateway.Client(the interface), the wire types and the request-id helpers stay ininternal/gateway.HTTPClientbecomeshttp.Clientininternal/gateway/http, constructed byNew.MockClientbecomesmock.Clientininternal/gateway/mock, constructed byNew.cmd/,internal/httpapiandinternal/integrationfollow the existingkvmemory/userpostgresalias convention asgatewayhttp/gatewaymock.The nineteen comment lines this commit adds are relocated lines; the net +2 is the two package docs the new packages require.
review: ownership on the request pathConstant wire fields become
Cow<'static, str>:ChatMessage.role,Choice.finish_reason,ChatCompletionResponse.object,ChunkChoice.finish_reasonandReasoningParam.effort.finish_openai/finish_anthropicreturnCow<'static, str>so a mapped constant reaches the wire borrowed. Deserialisation is unaffected: serde produces the owned form, so the request path allocates exactly as before.user_erased_sincebuilt two owned Strings per probe and probed twice;erasuresis nowHashMap<String, HashMap<String, i64>>so the lookup borrows.image_to_image_urlmoves the url out of the ownedsourceinstead of copying it.Two idiom fixes with no allocation delta:
json!(name)/json!(args)on a&strbecomeValue::from, dropping theto_valueround-trip per tool-call fragment;MockTransport::ok_jsonencodes withserde_json::to_vecinstead ofValue::to_string, and the threeunwrap_or(&vec![])becomemap(Vec::as_slice).unwrap_or_default().Entrypoint, per reload rather than per request:
read_source_textis async and reads throughtokio::fs, so a reload no longer blocks a runtime worker, and it returnsCow<'static, str>so the embedded default YAML is no longer copied on every reload.gw-servernow declarestokiofeatures = ["fs"]— the feature was only reaching it transitively. The batch-drain task keeps itsJoinHandleand is aborted at shutdown like the other six background tasks, and120/2s/5sare namedBATCH_STALE_SECS,BATCH_POLLandCONFIG_FEED_RETRY.review: one-line docs in handlerSixty-two multi-line
///docs acrosscrates/handlercollapse. Public items keep one line stating the contract; private fns and types keep at most one WHY line, andpush_policies, whose doc only restated its name, loses it entirely. The four//!module docs go from three-to-five lines to two, dropping the design-rationale narrative. Test modules already carried no inline comments.review: layout in handlerplugins.rsinterleaved four type+impl blocks among its free fns.ScanCounts,SpanMasker,SignedThinkingandEventFragmentsmove up behind the publicRuleHitandScanOutcome, so the file reads consts → public types → private types → free fns → tests. Verified as a pure move: the sorted added and removed lines are identical.review: borrow the realtime denial reasonRtModeration::DenycarriesCow<'static, str>— borrowed at the two'staticliteral sites inmoderate_rt, owned for a moderator-supplied reason.The retype alone would have been allocation-neutral, because the reason immediately met
rt_error'simpl Into<String>and then ajson!interpolation that deep-copies the owned String. Sort_errorandrt_error_framenow takeimpl Into<Cow<'static, str>>and move the message into the envelope, andrt_inbound_policycarries theCowthrough instead of collapsing it to aString. Every caller already passes a'staticliteral, aformat!result or an owned reason.Per-request allocation accounting
String allocations removed, all on the response path:
object,role,finish_reason)object,role,"tool_calls")reasoning.enabledshorthandMemoryStore::user_erased_since(batch drain)Per reload rather than per request, the embedded default config is no longer copied and the file read moved off the runtime worker.
Bench
cargo test --release -p gw-server --test bench -- --ignored --nocapture, run with the arms interleaved and the order swapped. No regression; the spread between rounds exceeds the difference between arms.Gates
The three ignored tests are the
#[ignore]d benches above. The elevenGW_TEST_PG_URL/GW_TEST_REDIS_URLsuites silently early-return without those variables set, so they were not exercised in this run.The Postgres/Redis-backed
internal/integrationsuite needs its docker compose stack and was not run; it compiles undergo vet -tags=integrationon both platforms.