jackc/pgx · error

invalid length for bit/varbit: bitLen=

Error message

invalid length for bit/varbit: bitLen=%d: %w

What it means

After reading (bitLen+7)/8 bytes of bit data, the reader had leftover bytes (Finish failed): the message length is inconsistent with the declared bit length. The bitLen value is included to show the mismatch.

Solutions

  1. Treat the payload as corrupt and fail the scan
  2. Ensure custom encoders write exactly the bytes implied by the length header
  3. Check for protocol-level corruption (proxy, truncation)
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at pgtype/bits.go:184 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/e4630fee14d97024. Report an issue: GitHub.

Appendix: source

Thrown at pgtype/bits.go:184

	if src == nil {
		return scanner.ScanBits(Bits{})
	}

	r := pgio.NewReader(src)

	bitLen := r.Int32()
	if err := r.Err(); err != nil {
		return fmt.Errorf("invalid length for bit/varbit: %w", err)
	}
	if bitLen < 0 {
		return fmt.Errorf("invalid length for bit/varbit: bitLen=%d", bitLen)
	}

	// Finish rejects trailing bytes, so together with the read below the data
	// must be exactly the number of bytes bitLen calls for.
	data := r.Bytes((int(bitLen) + 7) / 8)
	if err := r.Finish(); err != nil {
		return fmt.Errorf("invalid length for bit/varbit: bitLen=%d: %w", bitLen, err)
	}

	buf := make([]byte, len(data))
	copy(buf, data)

	return scanner.ScanBits(Bits{Bytes: buf, Len: bitLen, Valid: true})
}

type scanPlanTextAnyToBitsScanner struct{}

func (scanPlanTextAnyToBitsScanner) Scan(src []byte, dst any) error {
	scanner := (dst).(BitsScanner)

	if src == nil {
		return scanner.ScanBits(Bits{})
	}

	bitLen := len(src)

View on GitHub (pinned to ec1a0befd2)