Entry 04 · 23 October 2026 · 13 min read

The contract is a value

A walk through the release where what is true of the boundary became a value of its own: a contract beside the functions, typed bindings that build the request before the function sees it, structural rules that the runtime and the OpenAPI document both read, and scopes checked before anything runs. The polls service that runs through this series, as that release could express it; what one declaration now serves twice, and what it could not yet say.

The release

The previous entry walked the line's first step, where the API stopped being routed and became a description, compiled once into a plan. The plan could say where an operation lives and how it is reached, and the document it generated could promise that a parameter is required or bounded — but the runtime enforced none of it. The function still read strings from the context and parsed them itself, and a violation was a panic and a 500. What the boundary lacked was a place to live: the knowledge was implied by shapes and spread across handlers, middleware and memory.

This entry walks the step that added the missing thing, version 1.1.01. Its whole thesis sits in the doc comment of the one type it is remembered for:

APIContract describes the executable boundary between transports and API functions. Its operations are keyed by exported Go method name, just like APIDocumentation. Request descriptors bind transport values into ordinary typed function inputs; structural rules are shared by runtime validation and contract renderers.

That comment is the release compressed into three sentences, and the last one needs unpacking before it earns its keep. Request descriptors bind transport values into ordinary typed function inputs: beside each operation, a companion value will say where each piece of its request comes from — Cast will take its poll id from the path and its ballot from the body — and the runtime will construct the function's ordinary typed argument from that map, so the function never sees a wire value. Structural rules are shared by runtime validation and contract renderers: the same declared constraint — a page between zero and five hundred — will be what rejects a bad request before the function runs and what the published API document states. Both halves have their section below.

The service that runs through this series, as far as this release can express it, now looks like this:

go
// Polls declares polls, takes ballots into their logs and closes them.
type Polls struct{}

func (*Polls) ListPolls(ctx context.Context) []Poll                               { ... }
func (*Polls) DeclarePoll(ctx context.Context, request DeclarePollRequest) Poll   { ... }
func (*Polls) Cast(ctx context.Context, request CastRequest) Receipt              { ... }
func (*Polls) ReadLog(ctx context.Context, request ReadLogRequest) LogPage        { ... }
func (*Polls) ClosePoll(ctx context.Context, request ClosePollRequest)            { ... }

The functions now take a context, and still know nothing of any wire. What changed is that beside them, for the first time, there is something else.

A value beside the functions

The contract is a plain Go value, keyed by exported method name:

go
// APIContract describes the executable boundary between transports and API
// functions. Its operations are keyed by exported Go method name, just like
// APIDocumentation. Request descriptors bind transport values into ordinary
// typed function inputs; structural rules are shared by runtime validation and
// contract renderers.
type APIContract struct {
    Operations map[string]OperationContract
}

// OperationContract contains the request construction and authorization rules
// accepted by one operation.
type OperationContract struct {
    Inputs map[string]InputContract
    // Request maps transport values directly into the operation's request
    // argument. It is normally a companion struct whose exported fields mirror
    // the request type and whose leaves are Binding[T] values. Inputs remains
    // available for the legacy semantic-input/context binding model.
    Request       any
    Authorization AuthorizationContract
}

An API value that declares one implements a small interface, and the interface is careful about what it asks:

go
// WithAPIContract is implemented by API values which declare executable
// boundary rules. Implementations should be metadata-only so they can safely be
// called on a typed nil receiver by build-time generators.
type WithAPIContract interface {
    APIContract() APIContract
}

The functions are not touched. The contract is one declaration for the whole API, standing beside it, reviewed in the same diff.

Beside does not mean unrelated. The map's keys are the same exported method names the description walks, and when the API is described the two are held to one answer: a contract entry naming a method the API does not have is refused outright — API contract references unknown API method "Cast" — and every binding is joined to the request type itself, its type parameter required to exactly match the corresponding field of the operation's request, named types and pointer types included. The value cannot drift from the functions it stands beside; disagreement is an error when the API is described, not a surprise at serving time.

Why a value, rather than the other shapes the boundary could have taken? The question underneath is who owns the boundary's truth — and each candidate has a shape you can write down:

  • A base class hands the truth to the framework. Go has none, but the nearest writing is type Polls struct { koba.BaseAPI }, the boundary's rules as methods to override — the boundary is behavior an API inherits, and only the framework decides what it means.

  • An interface of behaviors hands it to the API as an obligation. Authorize(principal) error, Validate(input) error, every API implementing its own checking. Not the small APIContract() this release asks for: that method only returns a value, it implements nothing.

  • Rules as functions hand it to opacity. validate(input) error, one closure per constraint — the trap that looks harmless, and the sharpest one here: a function can be run but not read. The document cannot publish what a closure refuses, two services cannot be compared on rules they cannot see, and the same sentence written twice drifts with nothing able to prove it.

  • Annotations hand it to nobody. PollID string \uri:"poll_id" binding:"required"`` — struct tags, Go's own idiom for keeping a rule near the field: prose wearing a colon, untyped, unread until the first request arrives.

A value keeps it with the author. It can be constructed, passed, rendered into the document, diffed between two versions of a service; stating what is true of a boundary becomes an act of authorship with a place to live. And because the value stands apart from both the functions and the framework, everything the project did later joined as a new reader of it — the validator, the document builder, the generated plans — while the functions never took on a single new obligation.

Rules with types

The opening section recalled the previous step's cost: the description could promise that a parameter is required or bounded, and nothing enforced the promise. The contract's rules are that promise becoming checkable. An input — one scalar value the boundary speaks of, a poll id or a page — carries its constraints as typed fields:

go
// InputContract describes one scalar operation input.
type InputContract struct {
    GoType reflect.Type

    Required   bool
    Default    any
    HasDefault bool
    Minimum    any
    Maximum    any
    MinLength  *uint64
    MaxLength  *uint64
    Enum       []any
    Pattern    string
    Format     string
}

The constraint fields are loose any values because that is how they read best when written — Min(0), Default(50) — and GoType anchors them: when the API is compiled, each value is normalized to that type and stored as the very value the input will hold. The constructors make the type hard to get wrong: InputOf[T] with Required(), Default(v), Min(v), Max(v), MinLength(n), MaxLength(n), OneOf(...), Matches(pattern). A minimum on a string, a required input that also has a default, a pattern that does not compile, an enum with duplicates: all of it is refused when the API is described, not when the first request arrives. The rules are also checked against themselves — a default must survive its own constraints — because a value nobody checks is a comment with ambition.

The request is built, not parsed

The second half of the release is the one that changes what the function receives. A binding is a typed leaf that says where a value comes from:

go
// Binding is a typed leaf in a request companion struct. Its type parameter
// must exactly match the corresponding field in the operation request,
// including named and pointer types. Bindings are constructed with Query,
// Path, Header, Cookie, or Value rather than struct literals so their Go type
// cannot drift from T.
type Binding[T any] struct { ... }

An operation's request descriptor is a pair of structs that mirror each other — the request type the function has always had, and the companion that speaks for it (fb is the library's package, the alias its own fixture imports it under):

go
type DeclarePollRequest struct {
    Question string
    Options  []string
}

type declarePollContract struct {
    Question fb.Binding[string]
    Options  fb.Binding[[]string]
}

Same fields, same types, Binding[T] wherever the request has T; that is the mirror the walk holds to one answer. Where a value comes from is said at construction: Query, Path (always required), Header, Cookie, Value inside a BodyObject, or Body for the whole payload. The polls service declares its boundary like this:

go
type declarePollContract struct {
    Question fb.Binding[string]
    Options  fb.Binding[[]string]
}

type castRequestContract struct {
    PollID fb.Binding[string]
    Ballot fb.BodyObjectBinding[ballotContract]
}

type ballotContract struct {
    Nullifier fb.Binding[string]
    Sealed    fb.Binding[string]
    Proof     fb.Binding[string]
}

type readLogContract struct {
    PollID fb.Binding[string]
    Page   fb.Binding[int]
}

func (*Polls) APIContract() fb.APIContract {
    return fb.APIContract{Operations: map[string]fb.OperationContract{
        "DeclarePoll": {
            Request: fb.BodyObject(declarePollContract{
                Question: fb.Value[string](fb.Required(), fb.MinLength(1)),
                Options:  fb.Value[[]string](),
            }, fb.Required()),
            Authorization: fb.AuthorizationContract{
                RequiredScopes: []string{"polls:manage"},
            },
        },
        "Cast": {
            Request: castRequestContract{
                PollID: fb.Path[string]("poll_id", fb.MinLength(1)),
                Ballot: fb.BodyObject(ballotContract{
                    Nullifier: fb.Value[string](fb.Required(), fb.MinLength(1)),
                    Sealed:    fb.Value[string](fb.Required()),
                    Proof:     fb.Value[string](fb.Required()),
                }, fb.Required()),
            },
        },
        "ReadLog": {
            Request: readLogContract{
                PollID: fb.Path[string]("poll_id", fb.MinLength(1)),
                Page:   fb.Query[int]("page", fb.Default(50), fb.Min(0), fb.Max(500)),
            },
        },
        "ClosePoll": { ... },
    }}
}

Before anything runs, the companion is walked against the real request type, and the walk refuses what it cannot trust: a field that does not exist in the request, an unexported field, a nil pointer leaf, a pointer cycle, a descriptor with no bindings at all, the same wire parameter bound twice, a second body. What survives is a compiled list of bindings — source, wire name, field index into the real request type, input contract — stored beside the description so generated plans never need to serialize the author's structs.

At run time the request is constructed, not parsed into the domain:

go
// constructOperationRequest materializes the request argument declared by an
// API function. The compiled bindings are the only bridge between HTTP values
// and the request fields; the API function receives an ordinary typed value.
func constructOperationRequest(operation OperationDescription, c *httprouter.Context) (any, error) { ... }

The body is decoded once, defaults are applied where a value is absent, presence is told apart from null, each scalar is validated against its contract, and a violation is answered with a 400 that names the field and the reason — before anything of the domain has run. The messy half-typed world stops at the contract, and the function receives the ordinary typed argument it always wanted.

Look at ReadLog again. The previous entry recorded a cost: a read forced into POST because the signature had a request, and the signature cannot say that reading is safe. The release does not quite fix that — the method still defaults from the signature, for compatibility — but the description can now say what the signature cannot: ReadLog is routed at /polls/:poll_id/log, its request binds from the path and the query, no body exists, and its documentation says GET. A reader is finally a reader.

One fact, two readers

The same InputContract that rejects a page of 1000 also publishes the constraint. The OpenAPI builder projects minimum, maximum, lengths, enum and pattern straight from the contract into the document, and the parameters themselves come from the bindings; the parameter lists the description used to carry are documentation only now. Before this release, the check the runtime enforced and the document the world read were two texts that could disagree. After it, they are one fact with two readers.

That is the release's quiet thesis: stated once, consumed everywhere, checked mechanically. And the description has two compilers — the reflected one and the generated plan — which the repository holds to equality with a parity fixture, so the one fact reaches both of them too.

Who may call

AuthorizationContract is one field, RequiredScopes, with plain semantics: an authenticated principal must hold every listed scope, matching exactly. It is checked before the request is constructed — an unauthorized caller learns nothing about the shape of the input — and an operation that declares scopes with no authentication middleware behind it is refused outright when the API is added: a declared requirement with nothing to enforce it is a bug, and the boundary says no before the program ever serves a request.

That is deliberately all this entry says about it. Scopes in the contract is the first move of a security model — who the principal is, what a wire may reveal, which enforcement belongs on which side — and that model gets its own entries; what this release contributed is putting the requirement where the system can read it.

What the tests record

The test names read as the list of behaviors the release commits to:

  • TestNormalizeInputContractRejectsContradictoryRules
  • TestNormalizeRequestBindingsRejectsShapeTypeAndRuleErrors
  • TestNormalizeRequestBindingsRejectsDuplicateWireAndBodyBindings
  • TestRequestDescriptorConstructsNestedFunctionInput
  • TestRequestDescriptorRejectsInvalidOrMissingValuesBeforeInvocation
  • TestValidateOperationInputsAppliesTypedDefaultsAndTracksPresence
  • TestValidateOperationInputsReportsErrorsDeterministically
  • TestValidateOperationInputsUsesUnicodeCodePointsForLength
  • TestAuthorizationRunsBeforeStructuralValidation
  • TestAddAPIFailsClosedWhenScopedOperationHasNoAuthenticationMiddleware
  • TestStaticFixtureHTTPParity

The last one is the newcomer worth naming: the reflected description and the generated plan must agree, on real routes, for every operation — the contract feeds two compilers and the test holds them to one answer.

What this release did not solve

Failure is still not a fact. An error may carry a status code, and a panic is still a 500, but the contract has no place to say which failures a caller must handle. Cast refusing a nullifier the log has already seen is a string inside whatever status the error carries; nothing checks that the failure is declared, nothing publishes it, and the caller's obligation lives in prose. Declared outcomes are two entries ahead.

The rules are structural and scalar. A page between zero and five hundred can be said; "two to twenty options, all distinct" cannot — Options binds and nothing more, which is why the excerpt above says nothing about it. A rule that could state and check such a sentence is a later layer's work, when rules become values that run both ways.

And the contract's vocabulary is transport-neutral, but the core that serves it is not. The module still contains its http/, its middleware/, its workers/, and the request construction reads the router's context. The boundary truth is neutral; its enforcement lives beside one wire, and the claim that the same contract could serve a second wire — that "contract renderers" means more than one document — is, at this release, a claim with exactly one witness.

What the release established

Three things, each one earned in the sections above.

First, the contract states the execution boundary of the wire as data. What may reach a function — from where, satisfying what rules, holding which scopes — is declared once, beside the functions, and enforced before the function runs. The boundary between the transport and the API stopped being convention and behavior, and became a fact the system reads.

Second, the contract is a value — the ownership answer this entry kept returning to. A base class would have handed the truth to the framework, an interface of behaviors to the API's obligations, rules as functions to opacity, annotations to nobody; the value keeps it with the author, checked against the functions it serves when the API is described, read by the runtime and the document from one source. The boundary got a place to live — and every later addition, the validator, the document builder, the generated plans, became a new reader of it, never a new obligation on the functions.

Third — the one the future builds on — a value can be projected. The OpenAPI document was the first projection: the same fact, rendered for a reader who will never call the function. This entry had to concede that the contract's enforcement lives beside exactly one wire; the value itself never said it must. What one value renders when a second wire arrives is the question this line asks next.

Where this blog goes

The next entry walks the release where the claim got its second witness: the contract reaching a wire that is not a request and an answer — a subject bound before the function runs, a typed WebSocket channel, and Kafka consumers compiled from the same contract.

Notes

  1. Tag v1.1.0 of roxiegrillo/koba-public, dated 4 September 2026. The quotes, the code and the rules in this entry are from that release; api_contract.go, request_binding.go, request_construction.go, api_contract_validation.go and operation_authorization.go are the files walked here. The release before this one, v1.0.0, is the previous entry's subject. ↩

← All entries