Repository navigation
codegen: expose --idempotency-key on the endpoints that accept it (PRINFRA-1265) - #365
Conversation
…INFRA-1265) The v3 spec declares an optional Idempotency-Key header on 31 operations, but codegen only ever built flags from query parameters, so no command could send it. A caller retrying a create had no way to avoid a duplicate resource, and help text that told them to supply a key was unactionable. Header parameters now become flags generally, routed by a new "header" FlagSpec.Source through Invocation.Headers, which gives 23 visible commands a --idempotency-key flag and leaves room for any future header parameter. The flag's help carries the spec's own example, so an agent can copy the key shape rather than infer it. The CLI never generates a key. Whether a request is a retry of an earlier one is the caller's knowledge, not ours. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Command surface: 23 existing command(s) changedChanged — these already existed, so a change can break existing calls.
|
jrusso1020
left a comment
There was a problem hiding this comment.
Reviewed at 23067389a83e44cd6077af93efc39159ba90921c. Approving — the mechanism is right, and the part you flagged holds up better than the comment around it does. One test gap worth a follow-up, nothing blocking.
I went after your build-time validation specifically, plus the two numbers in the description.
Verified rather than read
1. The generated half is generator output, not hand-editing. Pulled EF openapi/external-api.json at 5a660aa26b9dcbbc478f4f47c6085a2e393151c7 (the SHA #364 synced) and ran make generate SPEC=… at this head. Zero diff. That target deletes every gen/*.go before regenerating, so it is a full-rebuild proof, not an incremental one. The gen/ diff is +284 / −0 — purely additive, and all 23 Example: help additions land on the new header flags. No existing query param's help text moved, which is the measurement behind point 5 below.
2. 31 vs 23 reconciles exactly, in both directions.
| count | |
|---|---|
Spec operations declaring Idempotency-Key |
31 |
| …of those, with a generated CLI command | 23 |
…of those, carrying x-cli-visible: false |
8 |
| Generated commands with the flag | 23 |
The 8 are custom-agents/{agent_id}/videos, hyperframes/renders, podcasts, video-quality/comparisons, video-quality/comparisons/batches, workflow-runs, workflows, workflows/{workflow_id}/versions — every one x-cli-visible: false in EF, so the CLI generates no command for them at all (control: the visible creates have the extension absent). Set equality holds: zero commands missing a declared flag, zero flags on a command the spec doesn't declare it for. Worth stating in the description, since 31→23 reads like attrition and is actually an EF-side visibility decision. Note POST /v3/workflow-runs declares the header required: true — inert today, but it's the one that changes shape if it's ever made visible.
Also confirmed your "exactly one distinct header parameter name today": the spec's complete set of header parameter names is {Idempotency-Key}.
3. Mutation battery: 8 mutations, 7 caught. Ran each against the suite rather than reading the assertions.
| mutation | caught by |
|---|---|
| remove the executor header hop | …FlagReachesRequestHeader, …WithoutDisplacingAuth |
| send the header when the flag was omitted | …OmittedSendsNoHeader |
| drop the builder-collision check | TestValidateFlags |
| drop the string-slice check | TestValidateFlags |
| revert codegen to query-only, no regen | …HeaderParamBecomesFlag |
hasIdempotencyKey → presence instead of non-empty |
TestHasIdempotencyKey |
paramHelp → never append the example |
…HeaderParamBecomesFlag |
route by flag.Name instead of flag.JSONName |
nothing — see below |
4. The poll path doesn't leak the key. ExecuteAndPoll builds statusInv fresh with no Headers, so the key rides the create and never the status GETs.
5. Ordering claim holds against the full reserved set, not just x-api-key: applyHeaders sets x-api-key/Authorization (with a Del of the other), User-Agent, X-HeyGen-Source and X-HeyGen-Client-Origin unconditionally after extraHeaders, and executeWithContext writes inv.Headers before Do. A spec header can displace none of them.
6. Description claims spot-checked at source. The 24-hour window, the 409 request_in_progress, 1-255 from [A-Za-z0-9_:.-] and per-endpoint/per-resource scope all come from the parameter's own description, and the schema pattern is ^[A-Za-z0-9_\-:.]{1,255}$. Your reason for not reusing the --headers validation checks out too: headerValueRe is ^[a-zA-Z0-9_\-\.]+$, which really does reject :.
The one finding: the wire-name hop isn't actually pinned
idempotency_key_test.go says it pins three hops "at once … and the wire carrying the header name over the flag name." It pins the first two. It structurally cannot pin the third.
Swapping inv.Headers[flag.JSONName] to inv.Headers[flag.Name] in BuildInvocation passes the entire suite. Idempotency-Key is a fixed point of ToKebab + HTTP canonicalization, so both spellings arrive identically:
| wire name | ToKebab |
canonical(kebab) | canonical(wire) | same? |
|---|---|---|---|---|
Idempotency-Key |
idempotency-key |
Idempotency-Key |
Idempotency-Key |
yes |
X-HeyGen-Client-Origin |
x-hey-gen-client-origin |
X-Hey-Gen-Client-Origin |
X-Heygen-Client-Origin |
no |
XApiVersion |
x-api-version |
X-Api-Version |
Xapiversion |
no |
The code is right — JSONName is the correct source. But the distinction is load-bearing for the next header the API adds, and the row that proves it is a header this repo already sends. Cheapest fix is a second header in codegen/testdata/test_spec.yaml whose kebab form differs, or a direct BuildInvocation assertion on a synthetic FlagSpec. Non-blocking: today's behaviour is correct, and this is about the guard on a future change.
On the validation, since you asked
The mirror is complete for the cases that panic, and the comment is wrong about three of them. I injected a colliding parameter into gen.Groups and built the real root:
| injected parameter | result |
|---|---|
wait / timeout on a poll-configured command |
panic — create flag redefined |
wait on a non-poll command |
fine — your conditional reasoning is right |
data |
panic |
help, human, headers |
no panic |
Those last three are cobra's automatic flag and two root persistent flags, and cobra's AddFlagSet skips duplicates rather than redefining. So a spec parameter named human doesn't panic — it silently shadows the global. Measured: video create --human goes from bool to string, and the table toggle stops working on that one command with no error anywhere. Rejecting them is still correct; if anything it's more valuable than the comment claims, because the failure it prevents is silent rather than loud. Just worth fixing the stated mechanism, since the next reader will use it to decide whether a new case belongs.
The wait/timeout hole is process-wide, but it's CI-visible. newRootCmd builds the whole tree — 170 nodes, 116 leaves, from 106 specs — so a pflag panic in any one leaf takes down heygen --help and heygen auth login too, not just the offending command. That's a harsher reading than "fail loudly at runtime" suggests. The mitigation is that five test files construct the full root, so the panic lands in CI on the regeneration commit, not in a user's hands. Worth saying that in the comment — it's what makes leaving the hole reasonable.
The string-slice guard is the whole class, not an instance. I checked this because guarding one type name usually isn't. schemaToFlagType can only ever return a literal "string" or a value from openAPITypeToFlag, which has five entries and exactly one non-scalar (array → string-slice); object isn't in the map and falls through to "string". So string-slice is the only type getFlagAsString mishandles, and the guard is complete by construction. It stops being complete the moment anyone adds a second non-scalar entry to that map — a one-line comment on the map would tie the two together.
Smaller notes
paramHelpis unclaimed scope, but measurably inert. It applies to every query param, not just headers; the +284/−0 diff shows it changed no existing help text, so nothing shipped. Thestrings.Containssuppression is case-sensitive, so a description mentioning the example in different case would double it — cosmetic, and currently unreachable.Content-Typeis the one reserved header set conditionally (if req.Header.Get("Content-Type") == ""), so unlike the others it would yield to a spec-declared header. Irrelevant today and arguably correct, but it's the single exception to "reserved always wins."Source:is already inSURFACE_FIELDS, so the release surface check sees header routing — a future regression flipping header→query wouldn't be invisible to it.- 4 files are unformatted under
gofmt; all pre-existing, none touched here.go vetclean, full suite green.
Review by Rames
Scope
Surfaces: CLI | Module: Codegen / command surface
Summary
The v3 spec declares an optional
Idempotency-Keyheader on 31 operations, but codegen only everbuilt flags from
queryparameters, so no command could send it. A caller retrying a create had noway to avoid a duplicate resource, and help text telling them to supply a key was unactionable.
Header parameters now become flags generally, which gives 23 visible commands an
--idempotency-keyflag. The CLI does not generate keys: the caller supplies one and reuses it onretry.
Context
FlagSpec.Sourceis how a resolved flag value finds its destination. It had three values,query,bodyandfile, routed byBuildInvocationinto the query string, the JSON body, or a multipartupload. Header parameters had no representation at all, so codegen skipped them silently rather
than failing, and the capability stayed invisible.
Idempotency is also the one thing in that header's contract the CLI cannot paper over. Whether a
given request is a retry of an earlier one is knowledge only the caller has.
How it works
Sourcegains a fourth value,header, andInvocationgains aHeadersmap. That is the wholemechanism: codegen stops filtering header parameters out, and
BuildInvocationfiles their valuesunder the header's wire name rather than the flag's kebab-cased one, so
--idempotency-keyarrivesas
Idempotency-Key.The header is applied in
executeWithContextafter either request builder runs, which puts it onthe JSON, multipart and bodyless paths at once. Placement is load-bearing:
applyHeadersrunslater, inside
Do, and writes the reserved auth and attribution headers, so a spec-declared headercan never displace a credential no matter what the spec names it.
Help text comes from the spec, including its
example, so the flag documents the key format and ausable sample without anything hardcoded here. That matters for the agent case, where the caller
has to construct a value rather than look one up.
Because the path is generic, it can now meet spec shapes it cannot serialize.
validateFlagsfailsgeneration rather than emitting a command that misbehaves at runtime, on two shapes: an array-typed
header, since header values serialize as a single string; and a parameter that collapses onto a
flag the builder already registers, which would panic pflag when the command tree is built. The
builder registers most of its own flags conditionally, so each case mirrors the corresponding
guard:
forceis a collision on a destructive command and perfectly fine anywhere else.Design decisions
Header parameters become flags generally, rather than special-casing this one header. The spec
has exactly one distinct header parameter name today, so the general path and a special case would
produce the same flag. The difference is what happens to the next header parameter the API adds:
generically it works, special-cased it is silently dropped again.
The CLI never generates a key. Not even as a default. Auto-generating per invocation would make
two intentional back-to-back creates independent when the caller wanted them deduplicated, or
collide when they did not, and the CLI has no way to tell those apart. The caller knows.
No client-side validation of the key. The spec constrains keys to 1-255 characters from
[A-Za-z0-9_:.-], and the API enforces it. Duplicating that regex here risks rejecting keys theAPI accepts, and the charset is a live example: it permits
:, which the pre-existing--headersvalue regex does not, so reusing that validation would have rejected valid keys.
Retry policy is unchanged. A keyed POST is still never re-sent automatically. The safety
argument for doing so is sound, but re-sending a mutation is the caller's decision in a CLI, and
doing it properly means handling the 409
request_in_progressthat a retry gets while the originalis still in flight. Tracked separately.
Timeout guidance branches on the key. The unkeyed hint tells the caller to reconcile with
get/listbefore retrying, which is the wrong instruction once a key makes the retry safe. Boththe direct path and the
--waitpath now say to re-run with the same key when one was sent, keyedoff the effective header value rather than mere map presence, since an empty value is sent and
rejected.
Testing
Three command-level cases covering the flag end to end: the value reaches the wire, omitting the
flag sends no header at all, and a command whose spec omits the header rejects the flag as a usage
error. One executor case pins the ordering against
applyHeaders, so a header cannot displace thecredential.
validateFlagshas five cases, including both directions of the conditional collision.A codegen-level case asserts the parameter-to-flag mapping directly against a fixture, which the
command-level tests cannot do because they read committed generated code and CI does not regenerate
it.
Each test was verified by mutation rather than by passing: removing the executor hop, breaking the
invocation routing, sending the header unconditionally, and reverting codegen to query-only without
regenerating each produced a distinct failure, with the tree restored and asserted afterwards.
README documents the 24-hour replay window and that a key reused after it creates a second
resource. SKILL.md documents the retry workflow for agents, including the window and the in-flight
409.
🤖 Generated with Claude Code