Go developer inspecting a bufio.Scanner token-too-long error and partial batch output in a terminal.

Go Scanner Stopped: Check the Error Before Accepting Its Records

Tue, Dec 1, 2026

A line loop can look healthy right up to the point where it loses the batch. In the smallest useful example, record A|ok is valid and appears first, record B|... is syntactically ordinary but has an 82-byte token, and record C|ok follows it. With bufio.Scanner configured as Buffer(make([]byte, 16), 64), the loop can return A, then stop when the scanner cannot accommodate B. If the caller publishes each valid record as soon as Scan() returns it, A has already escaped while B and C never become accepted records.

The narrow operational question is not whether callbacks ran. It is whether the scanner reached a qualifying end, every staged token passed the application policy, the required record IDs were reconciled, and only then the batch crossed one publication boundary. The go1.27.4 bufio documentation says Scan returns false both when input ends and when scanning stops on an error; Err is how the caller discovers the first non-EOF error. It also documents that scanner failure is unrecoverable and that the underlying reader may have advanced beyond the last returned token.

For this article I used go1.27.4 documentation as the reference baseline, dated November 10, 2026 on pkg.go.dev, but I did not treat that documentation label as runtime evidence. The disposable fixture was actually executed with go1.23.2 linux/amd64, GOTOOLCHAIN=local, on finite in-memory readers. The observed twelve-case output matched the independently authored manifest; the decision remains deliberately local to this fixture, not a claim about upstream business completeness, network throughput, or restart safety for an arbitrary stream.

Define what counts as a complete record batch

The batch contract comes before the scanner configuration. Here the source is finite and authored in memory. The required nonempty record order is A, B, C. Each record has exactly one |, a nonempty allowed ID, and a nonempty payload. That tiny schema exists only to make acceptance observable; it is not a proposal for a general interchange format.

The publication model has two outputs that must not be conflated. Diagnostic evidence may retain every token the scanner returned before it stopped. Accepted output is a separate in-memory batch value released only after the whole candidate has qualified. A successful nonempty batch publishes A/B/C once and increments the acceptance counter once. A rejected guarded batch publishes no accepted records. S02 intentionally violates that rule by publishing A immediately; that prefix is retained as evidence of the defect, not as an acceptable degraded result.

Empty input is explicit rather than accidental. S10 defines an accepted empty-batch policy: zero tokens, Err()==nil, an empty accepted value, and an ACCEPT_EMPTY_BATCH status. That state is different from rejection even though both can contain zero accepted record IDs. A status field therefore carries part of the contract.

This is also why the problem is distinct from detecting an oversized Go response. That neighboring pattern asks whether opaque bytes fit a body-size admission rule; this one asks whether a multi-record tokenizer reached a valid terminal state after returning earlier records. The shared habit is explicit admission, not a reused N+1 algorithm.

The decision at the end of this article is intentionally limited to four operational choices: retain Scanner under the current policy, approve a larger scanner/token policy, reject the source under the existing application rule, or redesign ingestion when the source must support restartable streaming. A larger buffer changes one boundary. It does not prove that the producer emitted every intended business record, that input is safe without an application cap, or that a consumed source can be resumed.

Separate Scan termination from the scanner error

The core review trap is treating the loop condition as a completion signal:

for s.Scan() {
    use(s.Text())
}

The loop has only told us that Scan() returned false. The go1.27.4 Scanner.Scan contract states that false means there are no more tokens either because the input ended or because an error stopped scanning. After false, Scanner.Err() reports the scanning error except that EOF is normalized to nil. The same package documentation therefore makes Err() part of ordinary correct control flow, not merely optional logging.

Default Scanner uses ScanLines. The go1.27.4 ScanLines contract strips \n and an optional preceding \r, and returns the final nonempty line even when it has no terminating newline. That is enough for S08 and S09. This article does not generalize those conclusions to custom split functions or to ErrFinalToken early stopping, which are explicitly outside the fixture.

A token that cannot fit is a terminal scanner error. The bufio documentation says scanning stops unrecoverably at EOF, the first I/O error, or a token too large for the scanner buffer, and warns that the underlying reader may have advanced arbitrarily far beyond the last token returned. That warning matters operationally: after S03 fails on B, A is evidence of progress, but the current reader position is not a reliable retry checkpoint.

The documented default MaxScanTokenSize is 64 * 1024, but the package explicitly notes that the actual maximum token may be smaller because the buffer can also need room for a delimiter such as a newline. I therefore avoid converting that constant into a universal promise that every 65,536-byte line will scan. Our fixture uses much smaller values so the boundary is easy to observe.

Use error identity without parsing its message

The go1.27.4 bufio package exposes ErrTooLong, and the go1.27.4 errors documentation recommends identity-aware matching with errors.Is, which can continue through wrapping. The fixture classifies the scanner limit with errors.Is(err, bufio.ErrTooLong) and the injected reader failure with errors.Is(err, injectedFailure). Human-readable text such as bufio.Scanner: token too long is retained as evidence, but no branch depends on a substring.

Unrecognized non-EOF errors stay unclassified rather than being rewritten into a familiar category. That is an important operational failure mode: an evidence pipeline should not collapse a new reader or scanner problem into ERR_TOO_LONG merely because the incident looks similar.

Build the bounded line-ingestion fixture

The fixture is deliberately disposable: one main package, standard library only, literal strings, finite readers, and fresh reader construction for every case. The independent manifest is built before runAll() produces observations. The scanner always uses default ScanLines; no custom split function participates.

The documentation baseline is go1.27.4. The actual execution was separate: go version go1.23.2 linux/amd64; GOOS=linux; GOARCH=amd64; GOTOOLCHAIN=local. The invocation was GOTOOLCHAIN=local go run /tmp/scanner_evidence.go. It exited zero at 2026-12-01T07:09:42Z. The exact program bytes had SHA-256 141ace29f3eccc4d778a21042c3a77d2b23eff11be3125f922d03088c8aa4564. The local toolchain source inspected at /usr/local/go/src/bufio/scan.go had SHA-256 99dea654896963b22a75a7fb1440d6e89d5037bc91876d3d4dd37bcce5bd9e5f. These are runtime/source identities for this execution, not claims about the rolling source page or go1.27.4 installation.

The official rolling scan.go source was used only as an implementation cross-check. It shows the buffer-growth branch setting ErrTooLong, Buffer replacing the initial buffer with buf[0:cap(buf)], and ScanLines requesting more data until it finds a newline or receives end-of-input. Because that URL is rolling source, I treat those observations as implementation details and keep the package documentation as the contract baseline.

package main

import (
    "bufio"
    "crypto/sha256"
    "encoding/hex"
    "encoding/json"
    "errors"
    "fmt"
    "io"
    "os"
    "runtime"
    "strings"
    "testing/iotest"
)

var injectedFailure = errors.New("injected reader failure")

const shortSource = "A|ok\nB|ok\nC|ok\n"
var oversizedSource = "A|ok\nB|" + strings.Repeat("x", 80) + "\nC|ok\n"
var declaredIDs = []string{"A", "B", "C"}

type ManifestRow struct {
    Case              string   json:"case"
    SourceName        string   json:"source_name"
    SourceDigest      string   json:"source_digest"
    DeclaredIDs       []string json:"declared_ids"
    InitialCapacity   int      json:"initial_capacity"
    ScannerMax        int      json:"scanner_max"
    ApplicationCap    *int     json:"application_cap,omitempty"
    ExpectedTokenIDs  []string json:"expected_token_ids"
    ExpectedTokenLens []int    json:"expected_token_lengths"
    ExpectedError     string   json:"expected_terminal_error"
    ExpectedSchema    string   json:"expected_schema_decision"
    ExpectedAccepted  []string json:"expected_accepted_ids"
    ExpectedCount     int      json:"expected_acceptance_count"
    ExpectedStatus    string   json:"expected_status"
}

type Evidence struct {
    Case            string   json:"case"
    DiagnosticIDs   []string json:"diagnostic_ids"
    DiagnosticLens  []int    json:"diagnostic_token_lengths"
    TerminalError   string   json:"terminal_error_category"
    ErrorText       string   json:"error_text,omitempty"
    SchemaDecision  string   json:"schema_decision"
    AcceptedIDs     []string json:"accepted_ids"
    AcceptanceCount int      json:"acceptance_count"
    Status          string   json:"status"
}

type RunEnvelope struct {
    Runtime  map[string]string json:"runtime"
    Manifest []ManifestRow     json:"manifest"
    Evidence []Evidence        json:"evidence"
}

func digest(s string) string {
    sum := sha256.Sum256([]byte(s))
    return "sha256:" + hex.EncodeToString(sum[:])
}
func intp(v int) *int { return &v }

func manifest() []ManifestRow {
    malformed := "A|ok\nBbad\nC|ok\n"
    crlf := "A|ok\r\nB|ok\r\nC|ok\r\n"
    noFinalNL := "A|ok\nB|ok\nC|ok"
    empty := ""
    return []ManifestRow{
        {"S01", "short", digest(shortSource), declaredIDs, 16, 64, nil, []string{"A", "B", "C"}, []int{4, 4, 4}, "NONE", "VALID", []string{"A", "B", "C"}, 1, "ACCEPT_BATCH"},
        {"S02", "oversized-middle", digest(oversizedSource), declaredIDs, 16, 64, nil, []string{"A"}, []int{4}, "ERR_TOO_LONG", "PREFIX_VALID_ONLY", []string{"A"}, 1, "REPAIR_CANDIDATE"},
        {"S03", "oversized-middle", digest(oversizedSource), declaredIDs, 16, 64, nil, []string{"A"}, []int{4}, "ERR_TOO_LONG", "NOT_EVALUATED_AFTER_SCAN_ERROR", []string{}, 0, "REPAIR_CANDIDATE"},
        {"S04", "oversized-middle", digest(oversizedSource), declaredIDs, 16, 128, nil, []string{"A", "B", "C"}, []int{4, 82, 4}, "NONE", "VALID", []string{"A", "B", "C"}, 1, "ACCEPT_BATCH"},
        {"S05", "oversized-middle", digest(oversizedSource), declaredIDs, 128, 64, nil, []string{"A", "B", "C"}, []int{4, 82, 4}, "NONE", "VALID", []string{"A", "B", "C"}, 1, "ACCEPT_BATCH"},
        {"S06", "oversized-middle", digest(oversizedSource), declaredIDs, 128, 64, intp(64), []string{"A", "B", "C"}, []int{4, 82, 4}, "NONE", "TOKEN_POLICY_REJECT_B", []string{}, 0, "REJECT_TOKEN_POLICY"},
        {"S07", "prefix-then-injected-error", digest("A|ok\n"), declaredIDs, 16, 64, nil, []string{"A"}, []int{4}, "INJECTED_FAILURE", "NOT_EVALUATED_AFTER_SCAN_ERROR", []string{}, 0, "HOLD_READ_FAILURE"},
        {"S08", "short-no-final-newline", digest(noFinalNL), declaredIDs, 16, 64, nil, []string{"A", "B", "C"}, []int{4, 4, 4}, "NONE", "VALID", []string{"A", "B", "C"}, 1, "ACCEPT_BATCH"},
        {"S09", "short-crlf", digest(crlf), declaredIDs, 16, 64, nil, []string{"A", "B", "C"}, []int{4, 4, 4}, "NONE", "VALID", []string{"A", "B", "C"}, 1, "ACCEPT_BATCH"},
        {"S10", "empty", digest(empty), []string{}, 16, 64, nil, []string{}, []int{}, "NONE", "VALID_EMPTY", []string{}, 1, "ACCEPT_EMPTY_BATCH"},
        {"S11", "malformed-middle", digest(malformed), declaredIDs, 16, 64, nil, []string{"A", "", "C"}, []int{4, 4, 4}, "NONE", "SCHEMA_REJECT", []string{}, 0, "REJECT_SCHEMA"},
        {"S12", "short-one-byte-dataerr", digest(shortSource), declaredIDs, 16, 64, nil, []string{"A", "B", "C"}, []int{4, 4, 4}, "NONE", "VALID", []string{"A", "B", "C"}, 1, "ACCEPT_BATCH"},
    }
}

func classifyErr(err error) string {
    if err == nil { return "NONE" }
    if errors.Is(err, bufio.ErrTooLong) { return "ERR_TOO_LONG" }
    if errors.Is(err, injectedFailure) { return "INJECTED_FAILURE" }
    return "UNCLASSIFIED_NON_EOF"
}

func parseRecord(token string) (string, bool) {
    if strings.Count(token, "|") != 1 { return "", false }
    id, payload, := strings.Cut(token, "|")
    if id == "" || payload == "" { return "", false }
    if id != "A" && id != "B" && id != "C" { return "", false }
    return id, true
}

func idsMatch(got, want []string) bool {
    if len(got) != len(want) { return false }
    for i := range want { if got[i] != want[i] { return false } }
    return true
}

func guarded(caseID string, r io.Reader, initialCap, max int, appCap *int, required []string, emptyAllowed bool) Evidence {
    s := bufio.NewScanner(r)
    s.Buffer(make([]byte, initialCap), max)

    staged := make([]string, 0, 3)
    lens := make([]int, 0, 3)
    diagIDs := make([]string, 0, 3)
    for s.Scan() {
        token := s.Text()
        staged = append(staged, token)
        lens = append(lens, len(token))
        id, := parseRecord(token)
        diagIDs = append(diagIDs, id)
    }
    if err := s.Err(); err != nil {
        return Evidence{caseID, diagIDs, lens, classifyErr(err), err.Error(), "NOT_EVALUATED_AFTER_SCAN_ERROR", []string{}, 0, statusForError(err)}
    }
    if len(staged) == 0 && emptyAllowed {
        return Evidence{caseID, diagIDs, lens, "NONE", "", "VALID_EMPTY", []string{}, 1, "ACCEPT_EMPTY_BATCH"}
    }

    accepted := make([]string, 0, len(staged))
    for , token := range staged {
        if appCap != nil && len(token) > *appCap {
            return Evidence{caseID, diagIDs, lens, "NONE", "", "TOKENPOLICY_REJECT_B", []string{}, 0, "REJECT_TOKEN_POLICY"}
        }
        id, ok := parseRecord(token)
        if !ok {
            return Evidence{caseID, diagIDs, lens, "NONE", "", "SCHEMA_REJECT", []string{}, 0, "REJECT_SCHEMA"}
        }
        accepted = append(accepted, id)
    }
    if !idsMatch(accepted, required) {
        return Evidence{caseID, diagIDs, lens, "NONE", "", "REQUIRED_IDS_MISMATCH", []string{}, 0, "HOLD_EVIDENCE"}
    }
    published := append([]string(nil), accepted...)
    return Evidence{caseID, diagIDs, lens, "NONE", "", "VALID", published, 1, "ACCEPT_BATCH"}
}

func statusForError(err error) string {
    if errors.Is(err, bufio.ErrTooLong) { return "REPAIR_CANDIDATE" }
    if errors.Is(err, injectedFailure) { return "HOLD_READ_FAILURE" }
    return "HOLD_EVIDENCE"
}

func naiveS02() Evidence {
    s := bufio.NewScanner(strings.NewReader(oversizedSource))
    s.Buffer(make([]byte, 16), 64)
    diagIDs, lens, published := []string{}, []int{}, []string{}
    count := 0
    schema := "PREFIX_VALID_ONLY"
    for s.Scan() {
        token := s.Text()
        lens = append(lens, len(token))
        id, ok := parseRecord(token)
        if ok {
            diagIDs = append(diagIDs, id)
            published = append(published, id) // deliberate defect
            count++
        } else {
            diagIDs = append(diagIDs, "")
            schema = "SCHEMA_REJECT"
        }
    }
    err := s.Err()
    text := ""
    if err != nil { text = err.Error() }
    return Evidence{"S02", diagIDs, lens, classifyErr(err), text, schema, published, count, "REPAIR_CANDIDATE"}
}

func runAll() []Evidence {
    malformed := "A|ok\nBbad\nC|ok\n"
    crlf := "A|ok\r\nB|ok\r\nC|ok\r\n"
    noFinalNL := "A|ok\nB|ok\nC|ok"
    app64 := 64
    return []Evidence{
        guarded("S01", strings.NewReader(shortSource), 16, 64, nil, declaredIDs, false),
        naiveS02(),
        guarded("S03", strings.NewReader(oversizedSource), 16, 64, nil, declaredIDs, false),
        guarded("S04", strings.NewReader(oversizedSource), 16, 128, nil, declaredIDs, false),
        guarded("S05", strings.NewReader(oversizedSource), 128, 64, nil, declaredIDs, false),
        guarded("S06", strings.NewReader(oversizedSource), 128, 64, &app64, declaredIDs, false),
        guarded("S07", io.MultiReader(strings.NewReader("A|ok\n"), iotest.ErrReader(injectedFailure)), 16, 64, nil, declaredIDs, false),
        guarded("S08", strings.NewReader(noFinalNL), 16, 64, nil, declaredIDs, false),
        guarded("S09", strings.NewReader(crlf), 16, 64, nil, declaredIDs, false),
        guarded("S10", strings.NewReader(""), 16, 64, nil, []string{}, true),
        guarded("S11", strings.NewReader(malformed), 16, 64, nil, declaredIDs, false),
        guarded("S12", iotest.DataErrReader(iotest.OneByteReader(strings.NewReader(shortSource))), 16, 64, nil, declaredIDs, false),
    }
}

func main() {
    env := map[string]string{
        "go_version": runtime.Version(),
        "goos": runtime.GOOS,
        "goarch": runtime.GOARCH,
        "gotoolchain": os.Getenv("GOTOOLCHAIN"),
    }
    out := RunEnvelope{Runtime: env, Manifest: manifest(), Evidence: runAll()}
    enc := json.NewEncoder(os.Stdout)
    enc.SetIndent("", "  ")
    if err := enc.Encode(out); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(2)
    }
}

Run it as a local evidence generator, not as a benchmark:

GOTOOLCHAIN=local go run scanner_evidence.go > scanner_evidence.json

A nonzero harness exit, a missing case row, or a mismatched source identity blocks acceptance. The JSON envelope keeps the manifest and evidence adjacent without deriving the oracle from the scanner under test. The exact executed source is scanner_evidence.go, and the complete machine-readable result is scanner_evidence.json.

Record the source before starting the scanner

Source identity belongs before scanning because tokenization changes representation. S09's CRLF source and S01's LF source yield the same normalized ScanLines tokens, but their source digests differ. The digest therefore identifies authored bytes; returned tokens identify scanner output. One cannot substitute for the other.

The three required IDs are also independently authored. They are not obtained by first scanning the fixture and then using whatever appeared as the expected list. That circular test would make missing C look self-consistent.

This distinction resembles the broader discipline of proving a finite source reached completion: a convenience signal is not automatically a completion contract. The Java article concerns a different API and is not being translated here; the shared review habit is to define expected content and the source boundary independently.

Reproduce the oversized middle-record failure

S01 is the positive control. The literal source is A|ok\nB|ok\nC|ok\n. With initial capacity 16 and scanner max 64, ScanLines returns three four-byte tokens. The loop then ends, Err() is nil, the schema accepts A/B/C, the manifest reconciliation succeeds, and the batch is published once.

S02 changes only the source to A|ok\nB| plus 80 x bytes plus \nC|ok\n. The middle token itself is 82 bytes, excluding its newline. The naive path still publishes inside the scan loop. In the recorded run it published A, incremented its publication counter to one, and then the scanner terminated with ErrTooLong. No token for B or C was returned. The diagnostic outcome is therefore useful because it reproduces the defect; the candidate implementation is still REPAIR_CANDIDATE.

The order matters. A did not become wrong merely because B was large. The defect is that the caller treated validity of an early record as permission to publish before it knew the terminal scanner state of the batch. A later Go Scanner Err check cannot retroactively turn that externalized prefix into an atomic batch.

img-over-sized

This is the essential bufio.Scanner token too long failure mode: valid prefix tokens can exist before terminal failure. Scan() returning false does not say which terminal condition occurred, and a caller that commits per token has already violated the whole-batch contract by the time Err() explains the stop.

Withhold accepted records until scanning finishes

S03 uses the same oversized bytes and the same Buffer(make([]byte, 16), 64) configuration, but routes them through guarded. That function collects Text() strings and diagnostic token lengths, finishes the scan loop, and checks Err() before any accepted-batch publication. In the recorded run the diagnostic prefix was A, the terminal category was ERR_TOO_LONG, the accepted IDs were empty, and the acceptance count stayed zero.

Only after a nil scanner error does the function apply the application token cap, parse the tiny record schema, reconcile IDs against the independent manifest, and publish one copied slice. The stages are deliberate. A scanner success does not imply schema success; a schema-valid subset does not imply required multiplicity; and a complete staged candidate is not accepted output until the final publication line executes.

withold-img-second

Checking Err() after irreversible per-record side effects would be too late for this contract. The check would still improve diagnosis, but it would not repair atomic admission. The guarded function is small precisely because the fixture is small; it stages three authored strings. I do not present that slice as a production memory bound for arbitrary ingestion. Larger services need their own bounded ownership or transactional publication mechanism if they require equivalent all-or-nothing visibility.

Keep diagnostic tokens outside the accepted result

On failure, the evidence record keeps diagnostic_ids, token lengths, error category, and error text. Those fields answer what the scanner actually returned. accepted_ids stays empty. That separation is more than naming: it prevents a troubleshooting prefix from being consumed by code that expects an admitted batch.

Returning no accepted data does not rewind the reader, and it cannot undo S02's earlier naive publication. The guard prevents new partial publication; it is not rollback. If the system must compensate already-visible effects, that is a different design problem and outside this in-memory fixture.

Increase the buffer only when the input policy allows it

S04 proves a narrower point than “increase the buffer.” It recreates the oversized source from the beginning, keeps initial capacity 16, raises scanner max from 64 to 128, and explicitly declares that the larger-token policy is approved for this comparison. The recorded run returned token lengths 4,82,4, ended with no scanner error, passed schema and ID reconciliation, and published A/B/C once.

The go1.27.4 Scanner.Buffer contract says Buffer sets the initial buffer and the maximum size the scanner may allocate during scanning, and it must be called before scanning starts or it panics. That is why the fixture configures it immediately after NewScanner.

Operationally, S04 is not a silent repair of S03. S03 remains evidence that the 64 configuration rejects this 82-byte token. S04 is a new candidate under a different, explicitly approved policy. If the service owner says 64 bytes is the business limit, S04 is irrelevant to acceptance; the right outcome is to reject the source, not to make the tokenizer more permissive behind the owner's back.

Nor does 128 make arbitrary input safe or complete. It permits this scanner configuration to accommodate this authored token. Application size policy, finite-source boundary, record schema, and publication remain separate gates.

Test buffer capacity separately from the application limit

S05 is the counterexample that prevents max from being misread as a business rule. It uses a fresh copy of the same oversized source, an initial buffer with capacity 128, and max=64. The go1.27.4 Buffer documentation states that the effective maximum token size must be less than the larger of max and cap(buf); if max <= cap(buf), the scanner can use that supplied buffer without allocating.

The recorded S05 therefore scanned the 82-byte middle token successfully even though the numeric max argument was 64. This is exactly why bufio Scanner Buffer limit and application token policy must not share one undocumented meaning.

S06 preserves the S05 scanner configuration but adds an explicit 64-byte application cap. Scanning still completes normally and all three diagnostic tokens are present. Only after Err()==nil does the acceptance layer evaluate token lengths. The 82-byte B violates the declared application rule, so the batch is REJECT_TOKEN_POLICY, accepted IDs remain empty, and the acceptance counter remains zero.

I avoid claiming the exact scanner boundary for every delimiter arrangement. The package itself warns that token capacity can interact with delimiter storage. The useful tested fact is concrete: an 82-byte token fit with cap(buf)=128,max=64, and the explicit 64-byte application rule rejected it afterward.

An initial buffer can exceed the max argument

The implementation cross-check explains why S05 is unsurprising without turning source code into a new contract. The rolling scan.go currently reslices the user buffer to its capacity and stores max separately. The documented contract already captures the behavior that matters: the larger of max and cap(buf) controls what can fit.

The decision vocabulary should therefore say exactly what changed. S05 changed scanner storage configuration and had no application cap. S06 kept that scanner configuration and added an application acceptance cap. Those are not two spellings of the same setting.

Inject an I/O failure after a valid prefix

A token-size error is not the only way a scanner can stop after useful-looking data. S07 builds io.MultiReader(strings.NewReader("A|ok\n"), iotest.ErrReader(injectedFailure)). The go1.27.4 io documentation says a Reader may return data with an error or report the error on a later call, and MultiReader reads components sequentially while propagating a non-EOF error from a component. The go1.27.4 testing/iotest documentation defines ErrReader as a reader that returns the supplied error.

The observed S07 diagnostic prefix was A; the next scan path encountered the sentinel and stopped. errors.Is(err, injectedFailure) retained provenance. Accepted IDs remained empty and the status was HOLD_READ_FAILURE.

That is a different problem from validating a complete JSON request, where an application decides whether one decoded JSON value consumed the intended request. Here multiple line records are intended; the defect is a tokenizer/reader failure after an earlier valid line.

The fixture proves only this controlled non-EOF path. It does not claim a finite local MultiReader represents transport completeness, nor that every real reader reports errors at the same byte boundary.

Check final lines, empty input, and chunk boundaries

S08 removes only the final newline after C|ok. The documented ScanLines behavior returns a final nonempty unterminated line, so the guarded path stages A/B/C, sees nil Err, and accepts the batch. That is not a special exception added by our code; it is part of the default split contract.

S09 changes line endings to CRLF. ScanLines strips the line ending, including an optional \r before \n, so diagnostic token strings are again A|ok, B|ok, C|ok. The source digest is nevertheless different from S01 because the authored bytes differ.

S10 supplies an empty finite reader. The scan loop produces no tokens and Err() is nil. Because this fixture explicitly allows an empty batch, the status is ACCEPT_EMPTY_BATCH and the acceptance counter is one even though accepted IDs is an empty slice. A rejected batch would have count zero and a rejection/hold status. Empty content by itself therefore does not identify success or failure.

S12 wraps the short valid source with iotest.OneByteReader inside iotest.DataErrReader. OneByteReader changes each nonempty read to at most one byte, while DataErrReader changes final-error timing so the final error can accompany the final data rather than appear on a subsequent read. Both are documented test mechanisms. The scanner still produced the same three line tokens and the guarded batch was accepted.

The result is useful because it challenges assumptions about reader chunking without adding concurrency, networking, or a new parser. It does not prove throughput properties or wall-clock bounds.

Keep token normalization separate from source identity

S01 and S09 demonstrate why a receipt should carry both source identity and normalized tokens. Same IDs do not imply byte-for-byte source equality. Conversely, a changed digest does not necessarily mean the logical records differ; CRLF and LF are a concrete example under ScanLines.

S10 makes the same point about state. An accepted empty batch and a rejected batch can both have accepted_ids=[]. Their status and acceptance count differ. Evidence schemas should preserve those distinctions rather than infer them later from one field.

Reject invalid records even when Scanner.Err is nil

S11 uses A|ok\nBbad\nC|ok\n. Scanner has no reason to reject Bbad: it is a perfectly ordinary line token under ScanLines. The loop therefore completes and Scanner.Err() is nil. Only the application schema notices that the middle token contains no separator.

The guarded function then rejects the batch as REJECT_SCHEMA, publishes nothing, and keeps the staged token evidence. That proves two independent gates: tokenizer completion and record admission. A nil scanner error means the scanner did not report a non-EOF scanning failure; it does not mean the application has accepted the record shape.

The tiny schema checks exactly one separator, a nonempty payload, and an ID in A/B/C. It is intentionally not CSV or JSON. For the broader design habit of separating parser success from record shape, Refonte's CSV article explores a different parser and different structural policy. This fixture keeps the same principle but not the CSV mechanism.

Required-ID reconciliation is another independent check. Even if every returned token is locally valid, the batch is not accepted unless the staged IDs equal the authored manifest in order. That is what prevents an apparently clean A prefix from being mistaken for the intended three-record result after a failure.

Reconcile every case into a batch receipt

The manifest below was authored independently of scanner output; its rows were EXPECTED before execution. The observation columns are EXECUTED evidence from the recorded go1.23.2 run, not values backfilled into the oracle. Source digests identify the literal bytes supplied before scanning. App cap is None where no application token-size rule exists. S07's digest identifies its authored byte prefix A|ok\n; the injected sentinel is separately represented by case construction and terminal category.

Case

Source digest

Declared IDs

Scanner cap/max

App cap

Expected token IDs / lengths

Expected terminal

Expected schema

Expected accepted / count

Observed terminal

Observed accepted / count

Runtime

S01

d3e88e4f…b4495cd

A,B,C

16/64

None

A,B,C / 4,4,4

NONE

VALID

A,B,C / 1

NONE

A,B,C / 1

go1.23.2 linux/amd64

S02

e465e342…5c13041

A,B,C

16/64

None

A / 4

ERR_TOO_LONG

PREFIX_VALID_ONLY

A / 1

ERR_TOO_LONG

A / 1

go1.23.2 linux/amd64

S03

e465e342…5c13041

A,B,C

16/64

None

A / 4

ERR_TOO_LONG

NOT_EVALUATED_AFTER_SCAN_ERROR

∅ / 0

ERR_TOO_LONG

∅ / 0

go1.23.2 linux/amd64

S04

e465e342…5c13041

A,B,C

16/128

None

A,B,C / 4,82,4

NONE

VALID

A,B,C / 1

NONE

A,B,C / 1

go1.23.2 linux/amd64

S05

e465e342…5c13041

A,B,C

128/64

None

A,B,C / 4,82,4

NONE

VALID

A,B,C / 1

NONE

A,B,C / 1

go1.23.2 linux/amd64

S06

e465e342…5c13041

A,B,C

128/64

64

A,B,C / 4,82,4

NONE

TOKEN_POLICY_REJECT_B

∅ / 0

NONE

∅ / 0

go1.23.2 linux/amd64

S07

5a47c684…45679f

A,B,C

16/64

None

A / 4

INJECTED_FAILURE

NOT_EVALUATED_AFTER_SCAN_ERROR

∅ / 0

INJECTED_FAILURE

∅ / 0

go1.23.2 linux/amd64

S08

e71b0303…99ede7

A,B,C

16/64

None

A,B,C / 4,4,4

NONE

VALID

A,B,C / 1

NONE

A,B,C / 1

go1.23.2 linux/amd64

S09

facdcea5…214ceb

A,B,C

16/64

None

A,B,C / 4,4,4

NONE

VALID

A,B,C / 1

NONE

A,B,C / 1

go1.23.2 linux/amd64

S10

e3b0c442…b855

∅

16/64

None

∅ / ∅

NONE

VALID_EMPTY

∅ / 1

NONE

∅ / 1

go1.23.2 linux/amd64

S11

d0822803…006b7

A,B,C

16/64

None

A,invalid,C / 4,4,4

NONE

SCHEMA_REJECT

∅ / 0

NONE

∅ / 0

go1.23.2 linux/amd64

S12

d3e88e4f…b4495cd

A,B,C

16/64

None

A,B,C / 4,4,4

NONE

VALID

A,B,C / 1

NONE

A,B,C / 1

go1.23.2 linux/amd64

The machine-readable JSON is the authoritative detailed receipt for the run; the table compresses hashes for readability. A complete evidence record should preserve the full digest, declared IDs, scanner configuration, application cap, token IDs and lengths, terminal category, schema decision, accepted IDs, acceptance count, runtime identity, invocation, and source/program identity. A missing row, nonzero harness exit, or observation that conflicts with the manifest should move the candidate to investigation rather than being edited until it “passes.”

Restart from a known source after scanner failure

The recovery procedure is bounded because the fixture has a retained finite source. It does not attempt to resume from wherever the failed scanner left the reader.

  1. Preserve the rejected receipt: source digest, declared manifest, scanner configuration, staged diagnostics, terminal error identity, and acceptance count.

  2. Decide which condition is actually wrong. If the service owner approves an 82-byte token, change the scanner/token policy explicitly as in S04. If the owner retains a 64-byte application rule, reject the source as in S06. If the failure is a reader error, hold the batch until the complete source can be recovered.

  3. Construct a new reader from the retained source beginning at byte zero. Do not reuse the consumed reader from S03 or S07.

  4. Construct a new scanner, apply the approved pre-scan buffer configuration, and run the guarded path from the beginning.

  5. Compare the new candidate with the original independent manifest and source identity. Publish only if the entire new run reaches a qualifying terminal state and all application checks succeed.

This is the only retry claim the fixture earns. It has the complete source bytes available, so reconstruction from the beginning is deterministic. A live stream, an unrecoverable upstream cursor, or a source whose beginning is no longer available would require a different ownership model.

Never reconstruct a file from a consumed suffix

The Scanner documentation is unusually direct: scanning stops unrecoverably, and the reader may have advanced arbitrarily far past the last returned token. Creating a new scanner over the old reader after ErrTooLong is therefore not a retry of the original input. It is a scan from an unspecified later position.

That documented read-ahead warning is enough to reject suffix reconstruction as an operational procedure. We do not need, and should not claim, the exact number of bytes read ahead in S03. If the complete source cannot be recreated from a trusted retained boundary, hold the batch. Do not invent missing records from whatever bytes happen to remain.

If restartable streaming is a hard requirement, the decision may be to redesign ingestion rather than retain Scanner as the sole boundary. The redesign must provide a recoverable source position or transaction model owned by the application. That architecture is outside this small fixture, but the need for it follows directly from the Scanner contract.

Set acceptance criteria and operational ownership

The final decision should be made from evidence, not from whether the loop printed some records. The decision matrix below keeps configuration, source policy, reader failure, and harness integrity separate.

Decision

Required evidence

Operational action

ACCEPT_BATCH

Scanner terminates with Err()==nil; all staged tokens satisfy application size and schema policy; IDs equal the independent manifest; publication count is exactly one.

Retain Scanner for this bounded contract and publish the accepted batch once.

REPAIR_CANDIDATE

Candidate publishes a prefix before terminal scanner state is known, or Scanner ends with ErrTooLong under a source policy that may legitimately allow the token.

Withhold release; repair staging/publication and obtain explicit owner approval before changing the buffer/token policy.

REJECT_TOKEN_POLICY

Scan completes, but a token exceeds the declared application cap.

Reject the source under the current policy; do not “fix” it by changing Scanner capacity alone.

HOLD_READ_FAILURE

Non-EOF reader error is identified, even if valid diagnostic tokens precede it.

Publish nothing; preserve provenance and recover a complete trusted source before rerun.

HOLD_EVIDENCE

Required receipt fields, source identity, manifest reconciliation, or error classification are missing/ambiguous.

Do not accept; collect or correct evidence.

RERUN_HARNESS

Harness exits nonzero, omits a case, uses the wrong source, or runtime/source identity cannot be established.

Rerun from the exact fixture and record the new evidence; do not infer success.

The service owner owns the accepted record-size and source contract. Maintainers own Scanner configuration, reader construction, error propagation, and the publication path. QA owns independent fixtures, expected manifests, negative controls, and evidence completeness. Those roles should converge on the receipt, not on an informal “it processed A” observation.

Revalidation is warranted after changing the split function, scanner capacity, reader wrapper, source construction, or publication path. In this article the split function remains default ScanLines; custom split functions, ErrFinalToken, pooling, buffer aliasing, concurrent consumers, compression, databases, real files, HTTP, and live upstreams are outside the exercised claim.

The decision to retain Scanner is reasonable when finite inputs can be recreated, maximum token policy is explicit, scanner failures are treated as batch failures, and whole-batch staging/publication is acceptable. Approve a larger buffer only when the input policy permits the larger token. Reject a source when the application cap says the token is invalid. Redesign ingestion when restartability from a durable source position is mandatory, because increasing Buffer cannot provide that property.

Strengthen backend validation through practical study

The engineering habit here is broader than bufio.Scanner: define what successful input means, separate acquisition/tokenizer state from application validity, preserve identity-aware errors, and delay publication until the relevant boundary has been established. Refonte's backend development foundations provide broader career context for those debugging and testing habits, while the specialist Scanner fixture remains this article's own narrow exercise.

The current Backend Developer Program page lists a three-month period at 10–12 hours per week and covers Node.js/Express, MongoDB/SQL, REST APIs and microservices, authentication/authorization, backend testing and debugging, Docker/cloud deployment, and a capstone. It describes hands-on projects, guidance, virtual internship opportunities with “Potential Internship” wording, and successful-completion certificates for training and internship. The page lists basic programming understanding and separately states an admission prerequisite of working toward a bachelor's or higher degree; it presents Backend Developer, API Developer, and Database Administrator as career directions, not guaranteed employment.

The page does not establish that the program teaches Go, bufio.Scanner, this laboratory, or any specific Go version. Mentor cadence, one-to-one entitlement, individual internship terms, and any particular applicant's eligibility also require separate verification. For readers who want structured practice around backend testing and debugging, the program's documented foundations are a relevant next context; the Scanner-specific decision still belongs to the service owner, maintainer, and QA evidence described above.