Go: optional fields are pointers — absence-capability by type, no waivers

Merged
JE
4mo ago
+3931-3571

Summary

Closes #436 with the decided Go end-state: every optional field in the generated client can represent absence, classified by type — no zero-value sentinels, no waiver list. Fixes #537 as a verified side effect.

Breaking for external pkg/generated consumers (deliberate, pre-1.0): optional value types are now pointers. The hand-written pkg/basecamp surface keeps its ergonomic value types.

What changed

Generator policy (commit 1):

  • go/oapi-codegen.yaml drops the global prefer-skip-optional-pointer: true — optional strings/booleans/numerics/time.Time/types.Date/nested structs generate as pointers (a value type cannot represent absence; omitempty made explicit zeros unsendable on request shapes).
  • scripts/enhance-openapi-go-types.sh: ten hand-maintained per-field pointerization passes and waivers collapse into one generic pass — optional non-nullable arrays on response-shaped schemas keep native []T (nil already represents absence). Request-shaped arrays stay pointers so an explicit empty array is sendable (omitempty drops a len-0 slice — the Create* subscriptions nil-vs-[] distinction), and nullable arrays keep the pointer for present-null. The time.Time/types.Date waivers are removed on principle: IsZero() is a zero-value sentinel, not absence.
  • The ten required-and-nullable jsonAdd fields (MyNote id/timestamps, Draft parent/scheduled_posting_at, SearchResult content/description, SearchType key, Wormhole color/destination_url) drop their hand-spelled pointer x-go-types — those compensated for the old flag suppressing oapi-codegen's nullable star and stacked to **T once it was removed.

Generated end-state (re-inventoried from the fresh diff): 770 omitempty fields — 711 pointers, 58 native slices, 1 interface{} (ValidationError.Details, where oapi-codegen intentionally never emits *interface{}), zero value-typed leftovers.

Wrapper/test absorption (commit 2): ~670 sites across 41 wrapper files + 6 test files. Reads use deref/derefInt64; writes preserve existing guard structure (&opts.X inside guards, omitzero() for zero-means-unset, ptr() for always-meaningful values); nested generated structs are nil-guarded with pointer presence replacing the old Id != 0 || Name != "" heuristics.

Two live crash bugs found and fixed (Go auto-derefs pointer field access, so gm.Category.Id compiles and then nil-panics at runtime): messages.go Category and events.go Details both crashed on payloads omitting those objects. Caught by test fixtures + a 97-site static sweep of pointer-field accesses; every other site verified guarded. events.go gains a red-proofed regression test (panics without the guard, passes with it).

Guard (commit 3): make go-check-optional-pointers (in make check + CI) classifies every omitempty field in client.gen.go: pointer/slice/map/interface pass, value types fail. No waiver list — the classifier is the policy. Red-proofed by injecting a value-typed violation; ValidationError.Details is the nil-capable negative control. SPEC §10 replaces the waiver-mechanics knob table with the resolved policy; rubric-audit.json 1B.4 → pass with history preserved.

Downstream regen (commit 4), incl. the #537 fix: the Ruby generator's datetime coercion matches the exact x-go-type spelling time.Time, so the previously starred fields were passing through as raw strings. De-starring fixes Draft.scheduled_posting_at + MyNote.created_at/updated_at coercion (Ruby suite 949 runs, 0 failures). The openapi.json change is otherwise Go-only: TS/Ruby/Python/Swift/Kotlin regenerate with zero real drift.

Wire-behavior notes (reviewed intentional improvements)

A handful of previously unconditionally-sent zero-valued query params are now omitted — each was a blank-default or an active hazard:

  • search.exclude_chat=false (Rails presence-checks make an explicit "false" string truthy territory), todos.completed=false, everything.*.page=0 (server defaults to 1), timesheet.person_id=0 (a bogus person filter), empty sort=/direction= pairs under compound guards.

Read-side: position: 0 on the wire now maps to &0 instead of nil (positions are 1-based, so unobserved in practice); present-but-empty nested objects (e.g. project.clientside) now yield a non-nil empty wrapper instead of nil — pointer presence is the truth.

Verification

  • Full make check green (verified REAL_EXIT=0 from the log, not a mid-run banner) — all six SDKs, conformance suites, all drift gates, the new guard.
  • Go: full test suite + vet green; go-check-drift/go-check-wrapper-drift/go-check-generated-drift clean (wrapper drift: 88 pairs, 1155 generated fields verified); conformance runner module builds clean.
  • Red proofs: guard (injected violation), events nil-Details regression test (stripped guard → panic), Go replay skip-marker tests unaffected.

Review round (all findings were real)

Guard had two silent holes of its own:

  • It matched only tags starting with json:, so every generated query parameter — which tags form: first — was exempt from the policy this PR establishes. Now matches omitempty in any tag: 859 fields checked, up from 770.
  • File.foreach inherited a US-ASCII external encoding under a non-UTF-8 locale and raised on client.gen.go's multibyte doc comments, so the guard died on the file it guards. Reads UTF-8 explicitly; verified under LC_ALL=C.

Request-reachability was a name match, now a $ref closure. QuestionSchedule is reached through Create/UpdateQuestion without carrying the RequestContent suffix, so its days array was wrongly kept native — an explicit empty array was unsendable. One schema was affected; the closure makes the class impossible.

Four wrapper sites carried len(x) > 0 guards forward from the value-typed world, where nil and empty were indistinguishable. With pointers they are not, and the guard silently drops an explicit empty array: hill_charts tracked/untracked, schedules CreateEntry participant_ids (UpdateEntry already used != nil — the file disagreed with itself), and questionScheduleToMap days. All now key on nil.

QuestionSchedule.Hour/Minute are *int so absence survives; the deref-then-address pattern manufactured a non-nil zero that reads back as "explicitly midnight". intPtrFrom carries nil through. Regression tests for both presence contracts, red-proofed against the pre-fix code.

#537 fixed at the mechanism, not the symptom. The de-star alone would have left ruby/scripts/generate-types.rb's exact-string x-go-type match in place, so a future *time.Time would regress silently. timestamp_go_type? now normalizes a leading star; types.FlexibleTime is deliberately excluded and documented (it also accepts date-only values — including it would be a behavior change, not a spelling fix). Regression tests cover all three affected fields plus the null case, red-proofed by reconstructing the pre-fix world (exact-match generator + starred spec → raw String → test fails), and the forward claim verified directly (new generator + starred spec still emits parse_datetime).

Synced with current main (#541 field-keyed 422, #557 Ruby pagination) and regenerated; rubric 1B.5 truthed up.

Closes #436. Fixes #537.
🤖 Authored with agent assistance by @jeremy.