jackc/pgx · error

invalid byte count at offset

Error message

invalid byte count %d at offset %d

What it means

Reader.Bytes was called with a negative length, which can only come from a corrupt or hostile message where an int32 length field was interpreted as a byte count without validation. The guard rejects the read at the recorded offset.

Solutions

  1. Validate length fields before passing them as byte counts
  2. Inspect the raw message at the given offset for a corrupt length value
  3. Treat as protocol corruption — close the connection rather than retry
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at internal/pgio/read.go:122 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of jackc/pgx@ec1a0befd2 (2026-08-04). Data as JSON: /api/errors/a502f881bf2d2af7. Report an issue: GitHub.

Appendix: source

Thrown at internal/pgio/read.go:122

func (r *Reader) Uint64() uint64 {
	if !r.need(8) {
		return 0
	}
	n := binary.BigEndian.Uint64(r.s[r.rp:])
	r.rp += 8
	return n
}

func (r *Reader) Int64() int64 {
	return int64(r.Uint64())
}

// Bytes reads the next n bytes. The returned slice aliases the source; it is
// not a copy.
func (r *Reader) Bytes(n int) []byte {
	if n < 0 {
		r.fail(fmt.Errorf("invalid byte count %d at offset %d", n, r.rp))
		return nil
	}
	if !r.need(n) {
		return nil
	}
	b := r.s[r.rp : r.rp+n]
	r.rp += n
	return b
}

// CString reads a NUL-terminated string, returning the bytes before the
// terminator and consuming the terminator. The returned slice aliases the
// source; it is not a copy.
func (r *Reader) CString() []byte {
	if r.err != nil {
		return nil
	}
	i := bytes.IndexByte(r.s[r.rp:], 0)

View on GitHub (pinned to ec1a0befd2)