Skip to content

Self-contained generated code with no external runtime dependencies #2342

Open

Description

@tigrato

I’d like to propose support for generating code that is fully self-contained, without depending on external runtime/helper packages.

To reduce dependency footprint and supply-chain risk, I would strongly prefer generated output that relies on the Go standard library wherever possible, rather than importing additional packages for helpers, types, validation, marshaling, parameter binding, and other runtime behavior.

The main motivation is to make generated code easier to adopt in stricter environments where we want:

  • fewer external dependencies
  • simpler auditing and vendoring
  • less version coupling between generated code and helper libraries
  • more explicit, verbose generated logic instead of hidden/runtime behavior
  • code that is easier to copy, inspect, and maintain internally

In short, we would prefer the generated code to be self-contained, even if that means the output is more verbose.

A few thoughts on scope:

  • a config option for “self-contained” or “no runtime deps” generation would be ideal
  • generated code could inline helper types/functions instead of importing them from external packages

I realize this may involve tradeoffs in generated code size and maintenance burden, so I wanted to ask first whether this direction would be welcome.

If the project is open to receiving this change, I’d be happy to contribute an implementation.

Activity

  1. mromaszewicz commented on Apr 29, 2026

    @mromaszewicz
    Member

    I already have a prototype of this running in my experimental playground in https://github.com/oapi-codegen/oapi-codegen-exp

    It' a rather invasive change, but it's in my plans.

    Please look around in that repo. All the helper functions are here:
    https://github.com/oapi-codegen/oapi-codegen-exp/tree/main/codegen/internal/runtime

    They can be used to inline the functions required by your spec, which required producing a rather annoying dead code analyzer to minimize the number of embedded functions.

    Independently, the code generator can now generate a stand alone runtime package, which you can generate into your own source code, to avoid a dependency on an external package. This works much more nicely if you have multiple oapi-codegen generated servers.
    https://github.com/oapi-codegen/oapi-codegen-exp/tree/main/runtime

  2. tigrato commented on Apr 29, 2026

    @tigrato
    Author

    @mromaszewicz thanks.
    that's great news.
    Unfortunately, I can't use oapi-codegen-exp because of all the breaking changes and because it generates code that doesn't compile if you use external models. It ends up referencing structs that don't exist.

    In the meantime, will you accept a PR into this branch to add the same functionality gated behind one option?

  3. mromaszewicz commented on Apr 29, 2026

    @mromaszewicz
    Member

    What I'm saying is that I will take care of this myself. My intent is to back-port the implementation from oapi-codegen-exp, following what I did there, into oapi-codegen. My intent is to make embedded code opt-out, by default, it won't refer to an external runtime package. If an external runtime package is specified, then it will not generate. The runtime code needs to be tested inside the code generator, so I wrote some custom code to strip decorations from Go files and embed the Go directly, bypassing the _test.go files.

    I want to do it like that here. If you want to use oapi-codegen-exp as a reference for making that PR into this repo, I will happily merge it, since it saves me work to do so, but I've already tried several different approaches to doing this and I'd like to do it as described.

  4. jamietanna commented on Apr 30, 2026

    @jamietanna
    Member

    Slightly related to #1468

  5. jamietanna commented on Apr 30, 2026

    @jamietanna
    Member

    I'm pro removing the runtime package generally - I agree that having a fully self-contained set of functionality is good.

    A few thoughts:

    • feat(client): 160,000 -> 85,000 LOC improvement for query-param heavy openapi specs #1744 + related issues - the more code we generate, the larger the file will be, which means the harder the Go parser needs to work
      • I've been meaning to ask what your thoughts are around some level of code reuse (while also being cautious of https://github.com/oapi-codegen/oapi-codegen#key-design-decisions)
      • If we're generating this code, I'd also quite like us to also generate test files for this functionality - so folks are confident that the generated code works as expected (especially if we're removing it from runtime). Or alternatively, we make sure that the test coverage comes into oapi-codegen, but we'd need to make sure we've got a set of generated code that handles all the cases we need
      • The approach in -exp seems reasonable
    • This will lead to fewer folks (outside of the project) knowing that they're using oapi-codegen. In a very frustrating case, a lot of tools don't detect oapi-codegen as a dependency. Where the runtime package is used, this does at least lead to some level of sponsorship from companies - removing this does remove that.
      • I'm not saying we should keep the runtime module for this reason. Only that if I were thinking of adoption stats and sponsorship money only I would make sure that there's always a dependency in every oapi-codegen generated project
      • I would prefer a fully self-contained set of generated code
  6. mromaszewicz commented on May 19, 2026

    @mromaszewicz
    Member

    I don't think people can miss that they're using oapi-codegen since each generated file has a comment on top, they must have some tool to invoke the codegen, and it's something they must install to work on that code base.

    In terms of huge code, yes, that is 100% a concern. What I did in oapi-codegen-exp allows you to generate the runtime package locally, or to embed parts of it into your generated code. It doesn't grow in size with the number of parameters, it's included only once, so it's a fixed overhead. I even prototyped automatic dead code pruning via traversal of the AST.

    The way I see people using this is one of two ways:

    1. If they have a single generated file from a single spec, then there is no issue embedding this extra code.
    2. If they have multiple specs, they should use the codegen to generate their own runtime package, and refer to it from all specs.
  7. jamietanna commented on Jul 12, 2026

    @jamietanna
    Member

    @mromaszewicz have you seen if we have a general "try and reduce some duplication in the generated code" issue?

    I know we aim to not reduce duplication for the sake of it, but some larger specs do end up leading to a lot of duplication, and there are some areas we can reduce this (I can share some suggestions that Claude Opus has, too)

    Details
    I've analyzed the 200k-line `schema.gen.go`. Here are the biggest sources of duplication in oapi-codegen's output — ordered by lines-of-code impact and ranked by how mechanical the upstream fix would be.
    
    ## 1. `Response.Status()`, `StatusCode()`, `ContentType()` — the single largest win
    
    **559 response types × 3 identical methods ≈ 11,700 lines.** Every generated response type has the same three trivial getters (schema.gen.go:152300, 152308, 152316 and repeated verbatim ~1,676 more times):
    
    ```go
    func (r ListAllIncidentActionItemsResponse) Status() string { … }
    func (r ListAllIncidentActionItemsResponse) StatusCode() int { … }
    func (r ListAllIncidentActionItemsResponse) ContentType() string { … }
    ```
    
    **Upstream fix:** embed an unexported base struct that carries the methods once:
    ```go
    type responseBase struct { Body []byte; HTTPResponse *http.Response }
    func (r responseBase) Status() string { … }   // defined ONCE
    ```
    Then generate `type ListAllIncidentActionItemsResponse struct { responseBase; ApplicationVndAPIJSON200 *… }`. Method set is unchanged for callers.
    
    ## 2. Per-enum `Valid()` methods
    
    **1,482 enum types, each with its own switch-based `Valid()` ≈ 8-12k lines** (schema.gen.go:37-49 pattern, repeated). Every one is mechanically `switch e { case KnownVal1: return true; …; default: return false }`.
    
    **Upstream fix:** emit a package-level `var validXxxValues = map[Xxx]struct{}{…}` (or slice) per enum, plus one generic helper `func isValid[T comparable](e T, set map[T]struct{}) bool`. Or even simpler: skip `Valid()` unless opted in — most consumers don't call it.
    
    ## 3. `Client.Op` + `ClientWithResponses.OpWithResponse` boilerplate
    
    **777 + 777 = 1,554 methods ≈ 12-13k lines.** Every `Client.Foo` is (schema.gen.go:91190):
    ```go
    req, err := NewFooRequest(...)
    if err != nil { return nil, err }
    req = req.WithContext(ctx)
    if err := c.applyEditors(ctx, req, reqEditors); err != nil { return nil, err }
    return c.Client.Do(req)
    ```
    Every `ClientWithResponses.FooWithResponse` is (schema.gen.go:170641):
    ```go
    rsp, err := c.Foo(ctx, ...)
    if err != nil { return nil, err }
    return ParseFooResponse(rsp)
    ```
    
    **Upstream fix:** the "with-response" wrappers are pure boilerplate — a single generic `func doWithResponse[R any](c *ClientWithResponses, exec func() (*http.Response, error), parse func(*http.Response) (*R, error)) (*R, error)` collapses all 777. Slightly harder for the plain `Client` methods because of typed params, but a shared `c.do(ctx, req, editors)` helper eliminates ~4 lines from each of the 777.
    
    ## 4. Query-fragment append loop
    
    **1,425 occurrences** of this five-line block inside request builders (schema.gen.go:105188):
    ```go
    if queryFrag, err := runtime.StyleParamWithOptions(...); err != nil { return nil, err }
    } else {
        for _, qp := range strings.Split(queryFrag, "&") {
            rawQueryFragments = append(rawQueryFragments, qp)
        }
    }
    ```
    
    **Upstream fix:** either have `runtime` expose `StyleParamFragments(...) ([]string, error)` returning the split slice directly, or emit a small local helper at the top of each builder. Either way saves ~3 lines × 1,425 = ~4,000 lines.
    
    ## 5. Union type `As` / `From` / `Merge` triples
    
    **562 × 3 = 1,686 near-identical methods** (schema.gen.go:68335 pattern). Each triple is 15 lines of `json.Marshal` / `json.Unmarshal` around a `t.union` byte slice.
    
    **Upstream fix:** these are the most defensible as generated (they preserve type safety), but the `Merge*` variant specifically is a strong candidate to be opt-in — I doubt most users call it. Alternatively, express the whole triple via a generic on the union base: `type union struct { data json.RawMessage }; func as[T any](u union) (T, error) { … }`, callable as `as[Foo0](t.union)`.
    
    ## 6. Per-operation request-builder scaffolding
    
    **559 `NewFooRequest` functions × ~15 lines of identical scaffolding** (parse server URL, dot-prefix path, `serverURL.Parse`, `http.NewRequest`) = ~8,000 lines that could compress to a helper `buildRequest(server, method, path, body, contentType)`.
    
    ## 7. Enum-type explosion from inlined schemas
    
    Not a codegen bug per se, but oapi-codegen does nothing to help: the spec inlines the same enum in many places, so you get e.g. `ActionItemTriggerParamsIncidentActionItemConditionGroup`, `ActionItemTriggerParamsIncidentActionItemConditionKind`, `IncidentTriggerParamsIncidentConditionGroup`, `PostMortemTriggerParamsIncidentConditionGroup`… **1,475 named string types**, many with byte-identical value sets. `= "CONTAINS_ALL"` appears 64 times as a const definition.
    
    **Upstream fix (harder):** oapi-codegen could hash the value set of each anonymous enum and, when identical, emit later ones as `type X = Y` aliases. The value constants would be one set, and downstream users would still get named types. This is the highest-effort change but would trim several thousand lines and, more importantly, make the file browsable.
    
    ---
    
    ## Ranking by impact vs. upstream complexity
    
    | #   | Change                                                 | Lines saved            | Upstream difficulty                      | API break                   |
    | --- | ------------------------------------------------------ | ---------------------- | ---------------------------------------- | --------------------------- |
    | 1   | Embed `responseBase` for Status/StatusCode/ContentType | ~11,700                | Trivial                                  | None                        |
    | 2   | Replace `Valid()` switch with map lookup / opt-in      | ~10,000                | Easy                                     | None (keep signature)       |
    | 3   | Generic `doWithResponse` for the WithResponse wrappers | ~5,400                 | Easy                                     | None                        |
    | 4   | Consolidated `Client.do` helper for the 777 methods    | ~3,000                 | Easy                                     | None                        |
    | 5   | `runtime.StyleParamFragments` returning slice          | ~4,000                 | Trivial in runtime, small codegen change | None                        |
    | 6   | `buildRequest` helper for URL/path scaffolding         | ~5,000                 | Medium (paths have styled params)        | None                        |
    | 7   | `Merge*` becomes opt-in                                | ~3,000                 | Trivial (config flag)                    | Yes — behind flag           |
    | 8   | De-dup enum types via aliasing                         | ~3-5k plus readability | Hard                                     | Possibly (usually cosmetic) |
    
    Total realistic reduction if the first 5 land: **~34k lines (~17%)** with no API break. Add 6-7 and you're at **~42-45k (~22%)**.
    
    The two highest-leverage-per-effort wins are #1 (embedded base struct) and #2 (map-based enum validation). Both are self-contained changes to the templates in oapi-codegen with zero caller-visible impact.
  8. mromaszewicz commented on Jul 12, 2026

    @mromaszewicz
    Member

    It's not something I've thought much about, because I've been focusing on bugs and correctness, not verbosity.

    It would be good to rethink some of this, yes, particularly now that we have generics available as well.

    I think claude's finding #1 above is really a big win and trivial in that test spec, but in real specs, it's less likely to help since responses likely won't be the same for everything, but it'd still help.

  9. jamietanna commented on Jul 12, 2026

    @jamietanna
    Member

    To note, this was tested with https://github.com/rootlyhq/rootly-go, so it's a real enough spec that it'd see some use for :) but yes, agreed it may not help for everything

    We could probably make this opt-in?

  10. mromaszewicz commented on Jul 12, 2026

    @mromaszewicz
    Member

    If it's compatible, I'd default-on any kind of code simplification. Let's file a separate issue to track generated code minification.

  11. jamietanna commented on Jul 12, 2026

    @jamietanna
    Member

    Sounds good - will raise one tomorrow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions