#977·sonic

StreamEncoder.Encode ignores newline write errors

Author: dajiaohuangCreated Aug 22, 2026Updated Aug 22, 2026

Describe the bug

StreamEncoder.Encode ignores an error returned while writing the terminating newline. If the JSON payload is written successfully but the newline write fails, Encode returns nil even though the complete encoded record was not written.

Affected commit: 2a36d6da63e25b9080cc4e11398bd5b3512dfc2a (current main).

To Reproduce

go
package main

import (
    "errors"
    "fmt"

    "github.com/bytedance/sonic"
)

type writer struct{ calls int }

func (w *writer) Write(p []byte) (int, error) {
    w.calls++
    if w.calls == 2 {
        return 0, errors.New("newline failed")
    }
    return len(p), nil
}

func main() {
    w := new(writer)
    err := sonic.ConfigDefault.NewEncoder(w).Encode(map[string]int{"a": 1})
    fmt.Printf("calls=%d err=%v\n", w.calls, err)
}

Output:

calls=2 err=<nil>

Expected behavior

Encode should return the error from every write required to emit the encoded record, including the terminating newline.

Sonic version:

Current main at 2a36d6da63e25b9080cc4e11398bd5b3512dfc2a.

Environment:

go version go1.26.3 windows/amd64
GOOS=windows
GOARCH=amd64
CGO_ENABLED=0

Additional context

The payload write loop already propagates writer errors, but the separate newline call in internal/encoder/stream.go discards both return values. A focused writer regression test can cover this without changing the stream format or public API.