jackc/pgx · error
invalid length for bit/varbit: bitLen=
Error message
invalid length for bit/varbit: bitLen=%d
What it means
The binary bit/varbit length header decoded to a negative value, which is impossible on the wire; guards against corrupt or malicious data before computing byte counts.
Solutions
- Discard the malformed value and fail the query
- Check for data corruption between server and client
- Verify a custom encoder is not sending negative lengths
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at pgtype/bits.go:177 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/4127b0bd5866d1c3.
Report an issue: GitHub.
Appendix: source
Thrown at pgtype/bits.go:177
}
type scanPlanBinaryBitsToBitsScanner struct{}
func (scanPlanBinaryBitsToBitsScanner) Scan(src []byte, dst any) error {
scanner := (dst).(BitsScanner)
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 {View on GitHub (pinned to ec1a0befd2)