Go developer reviewing sync.Once initialization code on a workstation.

Go sync.Once Won’t Retry a Failed Initialization

Sat, Nov 28, 2026

A getter can look completely normal on its second call even though the initialization it depends on never succeeded. That is the lifecycle trap this playbook isolates. The review question is not whether sync.Once is thread-safe, nor whether a callback was entered once. The useful questions are whether initialization was attempted, whether a valid object was published, and what later callers receive after the first attempt fails.

Go’s public contract makes those distinctions important. Once.Do invokes its function at most once for a given Once, and if that function panics, the Once treats the invocation as completed for future Do calls. The later call can therefore return normally while the application-owned state remains nil or partial. OnceFunc, OnceValue, and OnceValues use a different caller-facing failure contract: if their initializer panics, calls to the returned wrapper panic with the same panic value. OnceValue and OnceValues also retain their returned values. None of those contracts says that a usable application Config necessarily exists.

This article uses a one-process, sequential, synthetic Go laboratory with ten independent owners and three calls per owner. The proposed documentation baseline, Go 1.27.4, is a real stable release dated November 10, 2026, and is available from the official Go download service.

Execution status: EXPECTED / NOT EXECUTED. No fixture result, PASS line, runtime stack trace, or Go 1.27.4 runtime observation is claimed here. The available research shell reports Go 1.23.2 on linux/amd64, so executing there would create a deliberate baseline mismatch; this playbook therefore remains expected-only. A future execution must record its actual go version, runtime.Version(), GOOS/GOARCH, relevant build settings, run ID, and fixture revision rather than relabeling another toolchain as Go 1.27.4.

Define successful initialization before calling the getter

Before reviewing sync.Once, define the application result that counts as initialized. This fixture deliberately refuses to equate “the callback ran,” “the getter returned normally,” “the pointer is nonnil,” or “the error is nil” with success.

The application-owned type is small:

type Config struct {
    Marker string json:"marker"
    Ready  bool   json:"ready"
}

The acceptance predicate is fixed before any execution:

func validConfig(c *Config) bool {
    return c != nil &&
        c.Ready &&
        c.Marker == "READY"
}

A deliberately damaged publication is:

&Config{
    Marker: "PARTIAL",
    Ready:  false,
}

That distinction matters because the Go memory model gives Once an ordering contract, not a business-validity oracle. The official memory model says completion of the function invoked through once.Do is synchronized before the return of calls to that Do; it does not define Marker == "READY", Ready == true, or any other application invariant. In this sequential experiment, that memory-order guarantee is background documentation rather than a concurrency qualification.

Four review dispositions are used throughout:

Decision

Meaning in this playbook

ACCEPT_BOUNDED_POLICY

The declared lifecycle policy is explicit, the retained state satisfies its application contract when success is claimed, and the evidence is complete.

REPAIR_FAILURE_VISIBILITY

The implementation loses, masks, or contradicts failure evidence, or leaves partial state that later callers can mistake for success.

HOLD_EVIDENCE

The record set, provenance, baseline, case identity, or verifier result is incomplete or contradictory.

REQUIRE_EXPLICIT_RETRY_POLICY

The application requires another initialization attempt, but the current one-time owner does not promise one. A new, application-owned lifecycle is required.

Those decisions concern application policy and evidence. A negative test can reproduce exactly the documented behavior of sync.Once and still require repair. G02, for example, is expected to demonstrate the correct Go contract while simultaneously demonstrating an unacceptable getter contract for an application that promises a ready configuration.

The observer therefore keeps separate fields for getter-call ordinal, initializer-entry count, successful-publication count, return kind, ordinary error code, panic-token identity, pointer presence, marker, readiness, and valid. G06 adds one more datum, returned_same_as_first, using pointer comparison rather than raw addresses.

The expected values live in a literal manifest written independently of the fixture’s control flow. They are not generated from the loop that performs three calls. That separation prevents the test implementation from redefining its own oracle after seeing output.

The evidence model is deliberately narrower than adjacent Go topics. This fixture uses one ordinary nonnil error whose diagnostic code is INIT_ERROR; it is not a typed-nil interface experiment and does not construct joined error trees. It also performs no real network, database, filesystem, HTTP, or other external work. There is consequently no claim that the bounded retry example establishes real-world replay safety.

Read the once contracts and build the observation boundary

The four relevant APIs have related but materially different caller-facing failure behavior.

sync.Once.Do invokes the callback only for the first applicable invocation on that Once. The documentation explicitly says that if the callback panics, Do considers it to have returned, and future Do calls return without invoking it again. The current implementation corroborates why the callback is consumed: the slow path defers the operation that marks the Once done, so that deferred update still executes while panic unwinds through the frame. That source is implementation corroboration, not permission to call a failed application initialization “successful.”

sync.OnceFunc returns a function that invokes its supplied function once. If that function panics, the wrapper panics with the same value on every call. sync.OnceValue adds one retained result, while sync.OnceValues retains two results. The public package docs identify all three wrappers as Go 1.21 additions. The Go 1.21 release notes likewise introduced OnceFunc, OnceValue, and OnceValues as additions for a common lazy-initialization pattern; they are not new 2026 APIs.

The wrapper source shows the mechanism relevant to this audit: it retains result slots, a validity flag, and a recovered panic value. A successful initializer marks the wrapper valid; a panicking initializer leaves it invalid, and later calls panic using the retained value. OnceValues stores both return values when the initializer returns normally. Three observed panics from such a wrapper therefore must not be counted as three builder entries.

This is different from Python lazy-import initialization checks, where deferred first use can move when a capability is reified and a later access may encounter a different initialization boundary. That neighboring Refonte Learning article explicitly treats readiness and first-use behavior as separate milestones. Here the primary problem is narrower: a single Go owner has already consumed its one-time execution or retained its wrapper result.

The recovery boundary is equally important. The Go specification says that a panic terminates normal execution of the panicking function, runs deferred functions during stack unwinding, and may be stopped by a directly deferred call to recover in the same goroutine. After recovery, the intervening state is discarded and the recovering function returns to its caller; execution does not continue at the original panicking statement.

That is why each getter call needs its own observer:

func observe(
    c *testCase,
    call int,
    firstReturned **Config,
) (r Record) {
    r.Case = c.id
    r.Call = call
    r.ReturnKind = "NORMAL"

    defer func() {
        if p := recover(); p != nil {
            r.ReturnKind = "PANIC"
            r.PanicIdentityMatch = boolPtr(p == c.panicToken)
        }

        current := c.current()
        r.Attempts = c.attempts()
        r.SuccessfulPublications = c.publications()
        r.PointerPresent = current != nil
        r.Valid = validConfig(current)

        if current != nil {
            r.Marker = stringPtr(current.Marker)
            r.Ready = boolPtr(current.Ready)
        }

        r.PolicyState = c.policyState()

        if c.id == "G06" && r.ReturnKind == "NORMAL" {
            if *firstReturned == nil {
                *firstReturned = r.Returned
            }
            r.ReturnedSameAsFirst = boolPtr(r.Returned == *firstReturned)
        }
    }()

    cfg, err := c.get()
    r.Returned = cfg
    if err != nil {
        r.ErrorCode = stringPtr(errorCode(err))
    }
    return r
}

The outer driver then performs:

for _, c := range cases {
    var firstReturned *Config
    for call := 1; call <= 3; call++ {
        rec := observe(c, call, &firstReturned)
        emit(rec)
    }
}

A single defer recover() around this whole sequence would be an invalid harness. Once the panic unwound to that outer function, the remainder of the intended call sequence would not resume beneath the point where it panicked. Per-invocation observation is what lets call two and call three actually occur.

Each panic case owns a distinct nonnil token:

type PanicToken struct {
    Case string
}

token := &PanicToken{Case: "G02"}

The record checks recovered == token. Equal text is not substituted for identity. Unexpected panic values therefore cannot be normalized into a passing record merely because they print similarly.

The laboratory is intentionally sequential. It provides no qualification of a concurrent retry algorithm, recursive initialization, Goexit, panic(nil), or reentrance. It also never copies or resets a used sync.Once; Go’s public documentation says a Once must not be copied after first use.

Show how Once.Do can consume failure, partial state, and a local error

G01 is the clean control. One fresh owner contains one sync.Once, one shared *Config, and counters for initializer entries and successful publication.

func newG01() *testCase {
    var once sync.Once
    var cfg *Config
    attempts, pubs := 0, 0

    return caseOf("G01",
        func() (*Config, error) {
            once.Do(func() {
                attempts++
                candidate := &Config{Marker: "READY", Ready: true}
                if !validConfig(candidate) {
                    panic("fixture invariant")
                }
                cfg = candidate
                pubs++
            })
            return cfg, nil
        },
        func() *Config { return cfg },
        func() int { return attempts },
        func() int { return pubs },
        nil,
    )
}

Derived expectation for G01: all three getter calls are NORMAL; attempts are [1,1,1]; successful publications are [1,1,1]; the current pointer is present and valid after every call. The single builder entry is reused through the owner’s retained state.

G02 changes only the initialization outcome. The callback increments the entry counter and panics before publication:

func newG02() *testCase {
    var once sync.Once
    var cfg *Config
    attempts, pubs := 0, 0
    token := &PanicToken{Case: "G02"}

    return caseOf("G02",
        func() (*Config, error) {
            once.Do(func() {
                attempts++
                panic(token)
            })
            return cfg, nil
        },
        func() *Config { return cfg },
        func() int { return attempts },
        func() int { return pubs },
        token,
    )
}

DOCUMENTED BEHAVIOR: after the panic, that Once considers its callback invocation consumed, so later Do calls do not invoke it again.

Derived expectation for G02: return kinds are [PANIC,NORMAL,NORMAL]; attempts are [1,1,1]; successful publications stay zero; pointer presence is false; validity is false.

The important diagnostic is the pair NORMAL plus valid=false on calls two and three. Those normal calls show that the Do path no longer panics because it no longer enters the callback. They do not show that initialization eventually worked. Describing the owner merely as “initialized once” would collapse callback consumption into application readiness.

G03 makes the same mistake more dangerous by publishing too early:

once.Do(func() {
    attempts++
    cfg = &Config{Marker: "PARTIAL", Ready: false}
    panic(token)
})

Derived expectation for G03: [PANIC,NORMAL,NORMAL], attempts [1,1,1], publications zero under the fixture’s definition of successful publication, pointer present on all three post-call snapshots, marker "PARTIAL", readiness false, validity false.

A nonnil pointer is therefore not the acceptance predicate. The application owns the sequence “construct locally, validate locally, publish only after validation.” sync.Once does not roll back an assignment made before panic.

That ownership pattern is adjacent to, but different from, fresh candidates for Go replacement semantics. The referenced article separates a fresh candidate from mutation of an existing destination so stale state is not accidentally admitted. This fixture contains no JSON; the shared idea is simply that candidate ownership should make publication an explicit operation rather than an incidental side effect halfway through construction.

G04 exposes a quieter error contract. The getter declares a new local err each time:

func get() (*Config, error) {
    var err error

    once.Do(func() {
        attempts++
        cfg, err = buildFailure()
    })
    return cfg, err
}

with:

func buildFailure() (*Config, error) {
    return nil, errInit
}

Call one enters the callback, assigns errInit to that invocation’s local variable, and returns the error. Calls two and three allocate fresh local err variables initialized to nil, but their once.Do callbacks are skipped. Nothing assigns those later locals.

Derived expectation for G04: three NORMAL returns; errors [INIT_ERROR,null,null]; attempts [1,1,1]; no pointer; zero successful publications; validity false throughout.

This is a local-lifetime bug, not an interface-representation bug. The Refonte Learning article on Go nil error return contracts studies the different case where a nil concrete pointer is converted into a nonnil error interface. G04 uses an ordinary nonnil error on call one and literal nil on later calls because a skipped callback never writes the new local.

G05 repairs visibility without pretending to retry:

type stickyOwner struct {
    once sync.Once
    cfg  *Config
    err  error
}

func (o *stickyOwner) Get() (*Config, error) {
    o.once.Do(func() {
        o.attempts++
        o.cfg, o.err = buildFailure()
    })
    return o.cfg, o.err
}

Derived expectation for G05: errors [INIT_ERROR,INIT_ERROR,INIT_ERROR]; attempts [1,1,1]; config nil and invalid on every call.

This is an honest sticky-failure policy. It preserves what the initializer learned for the lifetime of that owner. It does not repair the resource, create a new candidate, or enter the builder twice. If callers require a second initialization attempt, the right disposition is not “clear the error.” It is REQUIRE_EXPLICIT_RETRY_POLICY.

Compare remembered wrapper outcomes with one initializer entry

G06 replaces an owner-managed sync.Once result with one sync.OnceValue wrapper constructed exactly once:

func newG06() *testCase {
    var current *Config
    attempts, pubs := 0, 0

    getValue := sync.OnceValue(func() *Config {
        attempts++
        candidate := &Config{Marker: "READY", Ready: true}
        if !validConfig(candidate) {
            panic("fixture invariant")
        }
        current = candidate
        pubs++
        return candidate
    })

    return caseOf("G06",
        func() (*Config, error) {
            return getValue(), nil
        },
        func() *Config { return current },
        func() int { return attempts },
        func() int { return pubs },
        nil,
    )
}

Constructing getValue inside Get would destroy the experiment because each getter call would receive a fresh wrapper with fresh once-state. The wrapper is therefore part of the case owner.

The public contract says OnceValue invokes its function only once and returns the value produced by that invocation. The source retains that result in the wrapper state.

Derived expectation for G06: all calls NORMAL; attempts [1,1,1]; one successful publication; every returned config is valid; returned_same_as_first is [true,true,true].

The first value is compared with itself for the first row, making the field true there by definition. Later rows compare returned pointers with the pointer retained from call one. No raw addresses need to be printed.

G07 gives one OnceValue wrapper an initializer that panics before it produces a value:

token := &PanicToken{Case: "G07"}

getValue := sync.OnceValue(func() *Config {
    attempts++
    panic(token)
})

The wrapper contract says that if the initializer panics, the returned function panics with the same value on every call. The implementation records the panic value and uses it when later calls observe the invalid wrapper state.

Derived expectation for G07: return kinds [PANIC,PANIC,PANIC]; panic identity matches the case-owned token three times; attempts [1,1,1]; successful publications zero; no current config.

This gives the ledger its most important counting example: three panic observations are evidence of three caller-visible failures, not three initializer attempts. The wrapper is replaying its remembered failure contract.

That statement should not be stretched into claims about stack equivalence. The source takes care to re-panic during the initial failure path and later raises the retained panic value, but this playbook records only value identity. It does not assert that later stack traces reproduce the original panic origin.

G08 uses OnceValues with (*Config,error):

getValues := sync.OnceValues(func() (*Config, error) {
    attempts++
    return nil, errInit
})

func get() (*Config, error) {
    return getValues()
}

The initializer returns normally. Therefore this is not a panic case. OnceValues retains both returned values and supplies them on later wrapper calls. The implementation assigns both result slots during the one invocation and returns those stored results thereafter.

Derived expectation for G08: all calls NORMAL; errors [INIT_ERROR,INIT_ERROR,INIT_ERROR]; attempts [1,1,1]; no config; zero publications.

An error is just one element of the returned tuple here. Nothing in the OnceValues contract interprets error != nil as a request to execute the initializer again. That application-level interpretation belongs outside the wrapper.

G05 and G08 thus converge on similar caller observations through different ownership. G05 manually stores the config/error pair in fields guarded by Once; G08 delegates retention of the two return values to one OnceValues wrapper. They are not therefore interchangeable in all designs. The point is narrower: both can implement an honest sticky ordinary-error contract.

Add a bounded retry owner, then exhaust it explicitly

A sticky result is appropriate only when the owner’s contract really is “one attempt for this lifetime.” If the application promises another attempt after a qualifying failure, that behavior needs a different owner rather than wishful interpretation of sync.Once.

G09 and G10 use a tiny sequential owner with an explicit state machine:

type retryState string

const (
    stateEmpty     retryState = "EMPTY"
    stateReady     retryState = "READY"
    stateExhausted retryState = "EXHAUSTED"
)

type boundedOwner struct {
    maxAttempts int
    attempts    int
    pubs        int
    state       retryState
    cfg         *Config
    script      []error
}

func (o *boundedOwner) Get() (*Config, error) {
    switch o.state {
    case stateReady:
        return o.cfg, nil
    case stateExhausted:
        return nil, errRetryBudgetExhausted
    }

    o.attempts++
    err := o.script[o.attempts-1]
    if err != nil {
        if o.attempts >= o.maxAttempts {
            o.state = stateExhausted
        }
        return nil, err
    }

    candidate := &Config{Marker: "READY", Ready: true}
    if !validConfig(candidate) {
        return nil, errors.New("invalid candidate")
    }

    o.cfg = candidate
    o.pubs++
    o.state = stateReady
    return o.cfg, nil
}

maxAttempts is literally 2. The sequence is serialized by the fixture’s single caller; this code is not presented as a concurrent retry implementation.

G09 provides the script:

[]error{errInit, nil}

Derived expectation for G09: call one returns INIT_ERROR, attempts 1, state EMPTY, no valid config. Call two enters the builder again, succeeds, publishes a validated candidate, and reaches attempts 2, state READY, valid=true. Call three reuses the ready config without another builder entry, so attempts remain 2.

The error sequence is therefore [INIT_ERROR,null,null]; attempts [1,2,2]; valid states [false,true,true].

This is intentionally only a comparison. The neighboring Refonte Learning discussion of coroutine reuse versus completed results already covers failure, explicit retry/reconstruction, and later reuse in a different ecosystem. Nothing here turns the Go owner into a cache, eviction strategy, or generic retry framework.

G10 supplies two failures:

[]error{errInit, errInit}

Call one returns INIT_ERROR and leaves one budgeted attempt. Call two enters the builder, receives INIT_ERROR again, sets the owner to EXHAUSTED, and returns that second builder error. Call three sees EXHAUSTED before any builder entry and returns:

var errRetryBudgetExhausted = errors.New("RETRY_BUDGET_EXHAUSTED")

Derived expectation for G10: errors [INIT_ERROR,INIT_ERROR,RETRY_BUDGET_EXHAUSTED]; attempts [1,2,2]; no published config; states [EMPTY,EXHAUSTED,EXHAUSTED].

That exact third-call error is application policy, not something provided by Go’s standard library. The same applies to the decision to return the underlying INIT_ERROR on the budget-consuming second failure rather than replacing it immediately with the budget error.

The prior Refonte Learning article on error membership and policy precedence emphasizes the same ownership boundary in a different setting: Go can expose error structure while an application decides which action follows from it. This laboratory does not reuse its joined-error machinery; errInit and errRetryBudgetExhausted remain ordinary errors.

A declared attempt limit is not backoff, rate limiting, circuit breaking, or proof of idempotency. Because this fixture has no real side effects, G09 demonstrates only lifecycle semantics: a new attempt is permitted by an application-owned state machine, and a candidate is published only after validation. A real service would need separate evidence that repeating the actual external work is permitted and safely cleaned up.

Build the complete standard-library fixture and literal manifest

The project can remain standard-library-only:

once-lab/
├── go.mod
├── cmd/
│   ├── fixture/
│   │   └── main.go
│   └── verify/
│       └── main.go
└── expected.json

Use this proposed module baseline:

module example.com/once-lab

go 1.27

Before a future execution, record the environment independently:

go version
go env GOOS GOARCH GOEXPERIMENT CGO_ENABLED
go run ./cmd/fixture > actual.jsonl
go run ./cmd/verify -expected expected.json -actual actual.jsonl

The official release history records Go 1.27.4 as released on November 10, 2026, and the official downloads page lists its installers and archives, so it is an available baseline rather than a hypothetical version. The run must nevertheless report what executable actually ran.

A compact complete cmd/fixture/main.go follows:

package main

import (
    "debug/buildinfo"
    "encoding/json"
    "errors"
    "fmt"
    "os"
    "runtime"
    "sync"
)

const fixtureRevision = "once-lab-v1"

var (
    errInit                 = errors.New("INIT_ERROR")
    errRetryBudgetExhausted = errors.New("RETRY_BUDGET_EXHAUSTED")
)

type Config struct {
    Marker string json:"marker"
    Ready  bool   json:"ready"
}

type PanicToken struct {
    Case string
}

type Record struct {
    RunID                  string          json:"run_id"
    FixtureRevision        string          json:"fixture_revision"
    Toolchain              string          json:"toolchain"
    GOOS                   string          json:"goos"
    GOARCH                 string          json:"goarch"
    BuildSettings          map[string]string json:"build_settings,omitempty"
    Case                   string          json:"case"
    Call                   int             json:"call"
    ReturnKind             string          json:"return_kind"
    ErrorCode              *string         json:"error_code"
    PanicIdentityMatch     *bool           json:"panic_identity_match"
    Attempts               int             json:"attempts"
    SuccessfulPublications int             json:"successful_publications"
    PointerPresent         bool            json:"pointer_present"
    Valid                  bool            json:"valid"
    ReturnedSameAsFirst    *bool           json:"returned_same_as_first"
    Marker                 *string         json:"marker"
    Ready                  *bool           json:"ready"
    PolicyState            *string         json:"policy_state"
    Returned               *Config         json:"-"
}

type testCase struct {
    id           string
    get          func() (*Config, error)
    current      func() *Config
    attempts     func() int
    publications func() int
    panicToken   *PanicToken
    policyState  func() *string
}

func validConfig(c *Config) bool {
    return c != nil && c.Marker == "READY" && c.Ready
}

func sp(v string) *string { return &v }
func bp(v bool) *bool     { return &v }

func errorCode(err error) string {
    switch {
    case errors.Is(err, errInit):
        return "INIT_ERROR"
    case errors.Is(err, errRetryBudgetExhausted):
        return "RETRY_BUDGET_EXHAUSTED"
    default:
        return "UNEXPECTED_ERROR"
    }
}

func onceDoCase(id string, mode string) *testCase {
    var once sync.Once
    var cfg *Config
    var stickyErr error
    attempts, pubs := 0, 0
    token := &PanicToken{Case: id}

    get := func() (*Config, error) { return cfg, nil }

    switch mode {
    case "success":
        get = func() (*Config, error) {
            once.Do(func() {
                attempts++
                candidate := &Config{Marker: "READY", Ready: true}
                cfg = candidate
                pubs++
            })
            return cfg, nil
        }
    case "panic-early":
        get = func() (*Config, error) {
            once.Do(func() {
                attempts++
                panic(token)
            })
            return cfg, nil
        }
    case "panic-partial":
        get = func() (*Config, error) {
            once.Do(func() {
                attempts++
                cfg = &Config{Marker: "PARTIAL", Ready: false}
                panic(token)
            })
            return cfg, nil
        }
    case "local-error":
        get = func() (*Config, error) {
            var err error
            once.Do(func() {
                attempts++
                cfg, err = nil, errInit
            })
            return cfg, err
        }
    case "sticky-error":
        get = func() (*Config, error) {
            once.Do(func() {
                attempts++
                cfg, stickyErr = nil, errInit
            })
            return cfg, stickyErr
        }
    }

    return &testCase{
        id: id, get: get,
        current: func() *Config { return cfg },
        attempts: func() int { return attempts },
        publications: func() int { return pubs },
        panicToken: func() *PanicToken {
            if mode == "panic-early" || mode == "panic-partial" {
                return token
            }
            return nil
        }(),
        policyState: func() *string { return nil },
    }
}

func wrapperCases() []*testCase {
    var g06cfg *Config
    a6, p6 := 0, 0
    v6 := sync.OnceValue(func() *Config {
        a6++
        g06cfg = &Config{Marker: "READY", Ready: true}
        p6++
        return g06cfg
    })

    g06 := &testCase{
        id: "G06",
        get: func() (*Config, error) { return v6(), nil },
        current: func() *Config { return g06cfg },
        attempts: func() int { return a6 },
        publications: func() int { return p6 },
        policyState: func() *string { return nil },
    }

    var g07cfg *Config
    a7, p7 := 0, 0
    t7 := &PanicToken{Case: "G07"}
    v7 := sync.OnceValue(func() *Config {
        a7++
        panic(t7)
    })

    g07 := &testCase{
        id: "G07",
        get: func() (*Config, error) { return v7(), nil },
        current: func() *Config { return g07cfg },
        attempts: func() int { return a7 },
        publications: func() int { return p7 },
        panicToken: t7,
        policyState: func() *string { return nil },
    }

    var g08cfg *Config
    a8, p8 := 0, 0
    v8 := sync.OnceValues(func() (*Config, error) {
        a8++
        return nil, errInit
    })

    g08 := &testCase{
        id: "G08",
        get: func() (*Config, error) { return v8() },
        current: func() *Config { return g08cfg },
        attempts: func() int { return a8 },
        publications: func() int { return p8 },
        policyState: func() *string { return nil },
    }

    return []*testCase{g06, g07, g08}
}

type boundedOwner struct {
    maxAttempts int
    attempts    int
    pubs        int
    state       string
    cfg         *Config
    script      []error
}

func (o *boundedOwner) Get() (*Config, error) {
    switch o.state {
    case "READY":
        return o.cfg, nil
    case "EXHAUSTED":
        return nil, errRetryBudgetExhausted
    }

    o.attempts++
    err := o.script[o.attempts-1]
    if err != nil {
        if o.attempts >= o.maxAttempts {
            o.state = "EXHAUSTED"
        }
        return nil, err
    }

    candidate := &Config{Marker: "READY", Ready: true}
    if !validConfig(candidate) {
        return nil, errors.New("invalid candidate")
    }
    o.cfg = candidate
    o.pubs++
    o.state = "READY"
    return o.cfg, nil
}

func boundedCase(id string, script []error) *testCase {
    o := &boundedOwner{
        maxAttempts: 2,
        state:       "EMPTY",
        script:      script,
    }
    return &testCase{
        id: id,
        get: o.Get,
        current: func() *Config { return o.cfg },
        attempts: func() int { return o.attempts },
        publications: func() int { return o.pubs },
        policyState: func() *string { return sp(o.state) },
    }
}

func observe(c *testCase, call int, first **Config, settings map[string]string) (r Record) {
    r = Record{
        RunID:           os.Getenv("RUN_ID"),
        FixtureRevision: fixtureRevision,
        Toolchain:       runtime.Version(),
        GOOS:            runtime.GOOS,
        GOARCH:          runtime.GOARCH,
        BuildSettings:   settings,
        Case:            c.id,
        Call:            call,
        ReturnKind:      "NORMAL",
    }

    defer func() {
        if p := recover(); p != nil {
            r.ReturnKind = "PANIC"
            r.PanicIdentityMatch = bp(c.panicToken != nil && p == c.panicToken)
        }

        current := c.current()
        r.Attempts = c.attempts()
        r.SuccessfulPublications = c.publications()
        r.PointerPresent = current != nil
        r.Valid = validConfig(current)
        r.PolicyState = c.policyState()

        if current != nil {
            r.Marker = sp(current.Marker)
            r.Ready = bp(current.Ready)
        }

        if c.id == "G06" && r.ReturnKind == "NORMAL" {
            if *first == nil {
                *first = r.Returned
            }
            r.ReturnedSameAsFirst = bp(r.Returned == *first)
        }
    }()

    cfg, err := c.get()
    r.Returned = cfg
    if err != nil {
        r.ErrorCode = sp(errorCode(err))
    }
    return r
}

func buildSettings() map[string]string {
    out := map[string]string{}
    if bi, ok := buildinfo.ReadFile(os.Args[0]); ok && bi != nil {
        for , s := range bi.Settings {
            switch s.Key {
            case "GOOS", "GOARCH", "CGOENABLED", "GOEXPERIMENT":
                out[s.Key] = s.Value
            }
        }
    }
    return out
}

func main() {
    cases := []*testCase{
        onceDoCase("G01", "success"),
        onceDoCase("G02", "panic-early"),
        onceDoCase("G03", "panic-partial"),
        onceDoCase("G04", "local-error"),
        onceDoCase("G05", "sticky-error"),
    }
    cases = append(cases, wrapperCases()...)
    cases = append(cases,
        boundedCase("G09", []error{errInit, nil}),
        boundedCase("G10", []error{errInit, errInit}),
    )

    enc := json.NewEncoder(os.Stdout)
    settings := buildSettings()

    for _, c := range cases {
        var first *Config
        for call := 1; call <= 3; call++ {
            if err := enc.Encode(observe(c, call, &first, settings)); err != nil {
                panic(fmt.Errorf("encode: %w", err))
            }
        }
    }
}

A production-quality implementation could refactor repetitive case construction, but this fixture intentionally keeps ownership visible. Each G01–G08 owner is created once, every wrapper is constructed outside its three-call loop, and G09–G10 use separate bounded owners.

The expected manifest must be literal rather than copied from the output. This compact form contains all thirty rows:

[
  {"case":"G01","call":1,"return_kind":"NORMAL","error_code":null,
   "panic_identity_match":null,"attempts":1,"successful_publications":1,
   "pointer_present":true,"valid":true,"returned_same_as_first":null,
   "marker":"READY","ready":true,"policy_state":null},
  {"case":"G01","call":2,"return_kind":"NORMAL","error_code":null,
   "panic_identity_match":null,"attempts":1,"successful_publications":1,
   "pointer_present":true,"valid":true,"returned_same_as_first":null,
   "marker":"READY","ready":true,"policy_state":null},
  {"case":"G01","call":3,"return_kind":"NORMAL","error_code":null,
   "panic_identity_match":null,"attempts":1,"successful_publications":1,
   "pointer_present":true,"valid":true,"returned_same_as_first":null,
   "marker":"READY","ready":true,"policy_state":null},

  {"case":"G02","call":1,"return_kind":"PANIC","error_code":null,
   "panic_identity_match":true,"attempts":1,"successful_publications":0,
   "pointer_present":false,"valid":false,"returned_same_as_first":null,
   "marker":null,"ready":null,"policy_state":null},
  {"case":"G02","call":2,"return_kind":"NORMAL","error_code":null,
   "panic_identity_match":null,"attempts":1,"successful_publications":0,
   "pointer_present":false,"valid":false,"returned_same_as_first":null,
   "marker":null,"ready":null,"policy_state":null},
  {"case":"G02","call":3,"return_kind":"NORMAL","error_code":null,
   "panic_identity_match":null,"attempts":1,"successful_publications":0,
   "pointer_present":false,"valid":false,"returned_same_as_first":null,
   "marker":null,"ready":null,"policy_state":null},

  {"case":"G03","call":1,"return_kind":"PANIC","error_code":null,
   "panic_identity_match":true,"attempts":1,"successful_publications":0,
   "pointer_present":true,"valid":false,"returned_same_as_first":null,
   "marker":"PARTIAL","ready":false,"policy_state":null},
  {"case":"G03","call":2,"return_kind":"NORMAL","error_code":null,
   "panic_identity_match":null,"attempts":1,"successful_publications":0,
   "pointer_present":true,"valid":false,"returned_same_as_first":null,
   "marker":"PARTIAL","ready":false,"policy_state":null},
  {"case":"G03","call":3,"return_kind":"NORMAL","error_code":null,
   "panic_identity_match":null,"attempts":1,"successful_publications":0,
   "pointer_present":true,"valid":false,"returned_same_as_first":null,
   "marker":"PARTIAL","ready":false,"policy_state":null},

  {"case":"G04","call":1,"return_kind":"NORMAL","error_code":"INIT_ERROR",
   "panic_identity_match":null,"attempts":1,"successful_publications":0,
   "pointer_present":false,"valid":false,"returned_same_as_first":null,
   "marker":null,"ready":null,"policy_state":null},
  {"case":"G04","call":2,"return_kind":"NORMAL","error_code":null,
   "panic_identity_match":null,"attempts":1,"successful_publications":0,
   "pointer_present":false,"valid":false,"returned_same_as_first":null,
   "marker":null,"ready":null,"policy_state":null},
  {"case":"G04","call":3,"return_kind":"NORMAL","error_code":null,
   "panic_identity_match":null,"attempts":1,"successful_publications":0,
   "pointer_present":false,"valid":false,"returned_same_as_first":null,
   "marker":null,"ready":null,"policy_state":null},

  {"case":"G05","call":1,"return_kind":"NORMAL","error_code":"INIT_ERROR",
   "panic_identity_match":null,"attempts":1,"successful_publications":0,
   "pointer_present":false,"valid":false,"returned_same_as_first":null,
   "marker":null,"ready":null,"policy_state":null},
  {"case":"G05","call":2,"return_kind":"NORMAL","error_code":"INIT_ERROR",
   "panic_identity_match":null,"attempts":1,"successful_publications":0,
   "pointer_present":false,"valid":false,"returned_same_as_first":null,
   "marker":null,"ready":null,"policy_state":null},
  {"case":"G05","call":3,"return_kind":"NORMAL","error_code":"INIT_ERROR",
   "panic_identity_match":null,"attempts":1,"successful_publications":0,
   "pointer_present":false,"valid":false,"returned_same_as_first":null,
   "marker":null,"ready":null,"policy_state":null},

  {"case":"G06","call":1,"return_kind":"NORMAL","error_code":null,
   "panic_identity_match":null,"attempts":1,"successful_publications":1,
   "pointer_present":true,"valid":true,"returned_same_as_first":true,
   "marker":"READY","ready":true,"policy_state":null},
  {"case":"G06","call":2,"return_kind":"NORMAL","error_code":null,
   "panic_identity_match":null,"attempts":1,"successful_publications":1,
   "pointer_present":true,"valid":true,"returned_same_as_first":true,
   "marker":"READY","ready":true,"policy_state":null},
  {"case":"G06","call":3,"return_kind":"NORMAL","error_code":null,
   "panic_identity_match":null,"attempts":1,"successful_publications":1,
   "pointer_present":true,"valid":true,"returned_same_as_first":true,
   "marker":"READY","ready":true,"policy_state":null},

  {"case":"G07","call":1,"return_kind":"PANIC","error_code":null,
   "panic_identity_match":true,"attempts":1,"successful_publications":0,
   "pointer_present":false,"valid":false,"returned_same_as_first":null,
   "marker":null,"ready":null,"policy_state":null},
  {"case":"G07","call":2,"return_kind":"PANIC","error_code":null,
   "panic_identity_match":true,"attempts":1,"successful_publications":0,
   "pointer_present":false,"valid":false,"returned_same_as_first":null,
   "marker":null,"ready":null,"policy_state":null},
  {"case":"G07","call":3,"return_kind":"PANIC","error_code":null,
   "panic_identity_match":true,"attempts":1,"successful_publications":0,
   "pointer_present":false,"valid":false,"returned_same_as_first":null,
   "marker":null,"ready":null,"policy_state":null},

  {"case":"G08","call":1,"return_kind":"NORMAL","error_code":"INIT_ERROR",
   "panic_identity_match":null,"attempts":1,"successful_publications":0,
   "pointer_present":false,"valid":false,"returned_same_as_first":null,
   "marker":null,"ready":null,"policy_state":null},
  {"case":"G08","call":2,"return_kind":"NORMAL","error_code":"INIT_ERROR",
   "panic_identity_match":null,"attempts":1,"successful_publications":0,
   "pointer_present":false,"valid":false,"returned_same_as_first":null,
   "marker":null,"ready":null,"policy_state":null},
  {"case":"G08","call":3,"return_kind":"NORMAL","error_code":"INIT_ERROR",
   "panic_identity_match":null,"attempts":1,"successful_publications":0,
   "pointer_present":false,"valid":false,"returned_same_as_first":null,
   "marker":null,"ready":null,"policy_state":null},

  {"case":"G09","call":1,"return_kind":"NORMAL","error_code":"INIT_ERROR",
   "panic_identity_match":null,"attempts":1,"successful_publications":0,
   "pointer_present":false,"valid":false,"returned_same_as_first":null,
   "marker":null,"ready":null,"policy_state":"EMPTY"},
  {"case":"G09","call":2,"return_kind":"NORMAL","error_code":null,
   "panic_identity_match":null,"attempts":2,"successful_publications":1,
   "pointer_present":true,"valid":true,"returned_same_as_first":null,
   "marker":"READY","ready":true,"policy_state":"READY"},
  {"case":"G09","call":3,"return_kind":"NORMAL","error_code":null,
   "panic_identity_match":null,"attempts":2,"successful_publications":1,
   "pointer_present":true,"valid":true,"returned_same_as_first":null,
   "marker":"READY","ready":true,"policy_state":"READY"},

  {"case":"G10","call":1,"return_kind":"NORMAL","error_code":"INIT_ERROR",
   "panic_identity_match":null,"attempts":1,"successful_publications":0,
   "pointer_present":false,"valid":false,"returned_same_as_first":null,
   "marker":null,"ready":null,"policy_state":"EMPTY"},
  {"case":"G10","call":2,"return_kind":"NORMAL","error_code":"INIT_ERROR",
   "panic_identity_match":null,"attempts":2,"successful_publications":0,
   "pointer_present":false,"valid":false,"returned_same_as_first":null,
   "marker":null,"ready":null,"policy_state":"EXHAUSTED"},
  {"case":"G10","call":3,"return_kind":"NORMAL",
   "error_code":"RETRY_BUDGET_EXHAUSTED","panic_identity_match":null,
   "attempts":2,"successful_publications":0,"pointer_present":false,
   "valid":false,"returned_same_as_first":null,"marker":null,"ready":null,
   "policy_state":"EXHAUSTED"}
]

These are EXPECTED / NOT EXECUTED values. Matching them later would show that the fixture reproduced its declared lifecycle cases. It would not convert G02, G03, G04, or G07 into approved initialization designs.

Reconcile all thirty records and preserve a consumed owner

An independent verifier should not import or call the fixture’s case constructors. Its job is to consume two files: the literal expected.json and emitted actual.jsonl.

A compact verifier can use a comparison struct that deliberately excludes volatile provenance from the expected manifest while separately enforcing the required runtime baseline:

package main

import (
    "bufio"
    "encoding/json"
    "flag"
    "fmt"
    "os"
)

type Row struct {
    Case                   string  json:"case"
    Call                   int     json:"call"
    ReturnKind             string  json:"return_kind"
    ErrorCode              *string json:"error_code"
    PanicIdentityMatch     *bool   json:"panic_identity_match"
    Attempts               int     json:"attempts"
    SuccessfulPublications int     json:"successful_publications"
    PointerPresent         bool    json:"pointer_present"
    Valid                  bool    json:"valid"
    ReturnedSameAsFirst    *bool   json:"returned_same_as_first"
    Marker                 *string json:"marker"
    Ready                  *bool   json:"ready"
    PolicyState            *string json:"policy_state"

    RunID           string json:"run_id"
    FixtureRevision string json:"fixture_revision"
    Toolchain       string json:"toolchain"
    GOOS            string json:"goos"
    GOARCH          string json:"goarch"
}

func key(r Row) string {
    return fmt.Sprintf("%s/%d", r.Case, r.Call)
}

func comparable(r Row) any {
    return struct {
        Case string
        Call int
        ReturnKind string
        ErrorCode *string
        PanicIdentityMatch *bool
        Attempts int
        SuccessfulPublications int
        PointerPresent bool
        Valid bool
        ReturnedSameAsFirst *bool
        Marker *string
        Ready *bool
        PolicyState *string
    }{
        r.Case, r.Call, r.ReturnKind, r.ErrorCode,
        r.PanicIdentityMatch, r.Attempts,
        r.SuccessfulPublications, r.PointerPresent,
        r.Valid, r.ReturnedSameAsFirst,
        r.Marker, r.Ready, r.PolicyState,
    }
}

func main() {
    expectedPath := flag.String("expected", "expected.json", "")
    actualPath := flag.String("actual", "actual.jsonl", "")
    flag.Parse()

    var expected []Row
    b, err := os.ReadFile(*expectedPath)
    if err != nil {
        fail("HOLD_EVIDENCE: read expected: %v", err)
    }
    if err := json.Unmarshal(b, &expected); err != nil {
        fail("HOLD_EVIDENCE: decode expected: %v", err)
    }

    f, err := os.Open(*actualPath)
    if err != nil {
        fail("HOLD_EVIDENCE: read actual: %v", err)
    }
    defer f.Close()

    actual := map[string]Row{}
    sc := bufio.NewScanner(f)
    for sc.Scan() {
        var r Row
        if err := json.Unmarshal(sc.Bytes(), &r); err != nil {
            fail("HOLD_EVIDENCE: decode row: %v", err)
        }
        k := key(r)
        if , exists := actual[k]; exists {
            fail("HOLDEVIDENCE: duplicate %s", k)
        }
        actual[k] = r
    }
    if err := sc.Err(); err != nil {
        fail("HOLD_EVIDENCE: scan: %v", err)
    }

    if len(expected) != 30 || len(actual) != 30 {
        fail("HOLD_EVIDENCE: expected 30 rows, got expected=%d actual=%d",
            len(expected), len(actual))
    }

    for , e := range expected {
        k := key(e)
        a, ok := actual[k]
        if !ok {
            fail("HOLDEVIDENCE: missing %s", k)
        }
        if a.Toolchain != "go1.27.4" {
            fail("HOLD_EVIDENCE: baseline mismatch %s: %s", k, a.Toolchain)
        }
        if a.FixtureRevision != "once-lab-v1" {
            fail("HOLD_EVIDENCE: revision mismatch %s", k)
        }
        if a.RunID == "" || a.GOOS == "" || a.GOARCH == "" {
            fail("HOLD_EVIDENCE: incomplete provenance %s", k)
        }

        ej, := json.Marshal(comparable(e))
        aj, := json.Marshal(comparable(a))
        if string(ej) != string(aj) {
            fail("HOLD_EVIDENCE: mismatch %s\nexpected=%s\nactual=%s",
                k, ej, aj)
        }
    }

    fmt.Println("VERIFIED_30_ROWS")
}

func fail(format string, args ...any) {
    fmt.Fprintf(os.Stderr, format+"\n", args...)
    os.Exit(2)
}

A future evidence packet should additionally retain the command-level go version, go env GOOS GOARCH GOEXPERIMENT CGO_ENABLED, fixture source revision or commit, verifier source revision, and unedited actual.jsonl. runtime.Version() inside the rows and go version outside the program provide two distinct provenance surfaces.

Any missing row, duplicate key, wrong G01–G10 identity, wrong ordinal, comparison failure, verifier nonzero result, missing run ID, or runtime other than the declared baseline is HOLD_EVIDENCE. A future runtime can certainly be newer than Go 1.27.4, but that would be a different qualification run and must be labeled as such.

Repair work must not mutate the failed owner to manufacture a green second attempt. The Go package documentation says a used Once must not be copied, and its contract gives no reset operation. Assigning a zero Once over one that has already participated in lifecycle decisions, copying its containing owner, or reconstructing a OnceValue wrapper secretly on each getter call would change ownership semantics rather than test them.

Preserve the original owner long enough to collect its evidence. If policy review concludes that another attempt is required, create a reviewed lifecycle transition with a new owner or an application state machine that explicitly allows it. Give that requalification a new run ID.

The difference matters operationally. A sticky owner promises that all later callers observe the first outcome. A retrying owner promises that some later caller may re-enter initialization under declared conditions. Those are distinct APIs even when they share the same method name.

After a policy change, revalidate the full caller contract: which failures remain visible, how many entries are permitted, what happens at budget exhaustion, whether only validated candidates are published, and what a caller receives once a valid state exists. In a real service, cleanup of failed attempts and idempotency of external side effects need their own evidence; this synthetic fixture cannot establish either.

Decide what the evidence permits and strengthen the ownership discipline

The ten cases reduce the review to a lifecycle ledger:

Case

What later callers receive

Attempts after three calls

Useful publication

Review meaning

G01

READY config three times

1

Yes

A one-attempt success baseline can be accepted with complete evidence.

G02

panic, then two normal calls with nil state

1

No

Documented Once.Do behavior reproduced; getter contract needs failure visibility.

G03

panic, then two normal calls with PARTIAL state

1

No

Partial publication is especially unsafe; repair publication ownership.

G04

INIT_ERROR, then two nil errors

1

No

Failure evidence is lost; REPAIR_FAILURE_VISIBILITY.

G05

INIT_ERROR three times

1

No

Honest sticky failure; retry still requires a different policy.

G06

same valid pointer three times

1

Yes

Wrapper success retained honestly.

G07

same panic token observed three times

1

No

One initializer entry, three failure observations; no retry occurred.

G08

cached (nil, INIT_ERROR) three times

1

No

Honest retained ordinary error; no implicit retry.

G09

error, success, reuse

2

Yes

Explicit attempt budget can support ACCEPT_BOUNDED_POLICY in this synthetic scope.

G10

error, error, budget exhausted

2

No

Exhaustion is explicit and the third call does not enter the builder.

The broad decision rule is compact. A valid retained config plus complete, baseline-matched evidence can support ACCEPT_BOUNDED_POLICY for the policy actually declared. Lost ordinary errors, misleading normal returns, or partial publication require REPAIR_FAILURE_VISIBILITY. Missing provenance, incomplete records, wrong case identities, unexpected panics, or a baseline mismatch are HOLD_EVIDENCE. If the product requirement is “try initialization again,” but the current owner is sync.Once, OnceValue, OnceValues, or a sticky stored error, choose REQUIRE_EXPLICIT_RETRY_POLICY instead of disguising a new lifecycle as continued use of the old owner.

The negative controls matter because a test suite can be green for the wrong reason. G02 is expected to pass its diagnostic oracle precisely by showing one panic followed by skipped initialization. G04 is expected to pass by reproducing the disappearing local error. G07 is expected to pass by showing three panic observations but one builder entry. A passing diagnostic fixture says the lifecycle was reproduced; it does not approve the lifecycle for production use.

The primary Go sources support the mechanical parts of that conclusion. Once.Do consumes a panicking invocation for future calls; the wrappers retain panic behavior; OnceValue and OnceValues retain results; the memory model addresses ordering rather than business validity; and the language specification requires the recovery boundary used here to let the caller regain control after each panic. The wrappers were added in Go 1.21, so the relevant design distinction is established API behavior rather than a 2026 release novelty.

The remaining limitation is deliberate: nothing in this sequential synthetic experiment qualifies a concurrent retry owner. A real service that changes from sticky failure to retry needs a separate review of concurrent callers, state transitions, cancellation, cleanup, side-effect safety, and the visibility guarantees required by its own API. The present fixture proves only the one-process sequential lifecycle it declares.

That review discipline is broader than sync.Once: identify the owner of a state transition, write the acceptance predicate before execution, keep producer attempts separate from caller observations, and preserve evidence when failure changes control flow. Refonte Learning’s Backend Developer Program lists a three-month schedule, roughly 10–12 hours per week, basic programming knowledge, and curriculum areas including Node.js/Express, MongoDB and SQL, REST and microservices, authentication, testing/debugging, Docker/cloud topics, and a capstone. Its admissions page also states that applicants are working toward a bachelor’s or higher-level degree and describes educational guidance, potential internship opportunities, a Training Certificate, and a Certificate of Internship upon successful completion.

Those confirmed backend and testing foundations are relevant to the ownership habits used in this playbook, but the page does not establish that the program teaches Go, sync.Once, this exact laboratory, or a particular Go version. Readers interested in specialized Go lifecycle work can review the Backend Developer Program and ask Refonte Learning directly whether that coverage is currently available.