apache/beam · error · IOException

Expected 0 or 1, got %d

Error message

Expected 0 or 1, got %d

What it means

BooleanCoder.decode() reads one byte and maps 0 to false and 1 to true; any other byte value is a corrupt/invalid encoding, so it throws an IOException with "Expected 0 or 1, got %d". This indicates corrupted or incorrectly produced serialized data rather than bad user input.

Source

Thrown at sdks/java/core/src/main/java/org/apache/beam/sdk/coders/BooleanCoder.java:48

  /** Returns the singleton instance of {@link BooleanCoder}. */
  public static BooleanCoder of() {
    return INSTANCE;
  }

  @Override
  public void encode(Boolean value, OutputStream os) throws IOException {
    BYTE_CODER.encode(value ? (byte) 1 : 0, os);
  }

  @Override
  public Boolean decode(InputStream is) throws IOException {
    Byte value = BYTE_CODER.decode(is);
    if (value == 0) {
      return false;
    } else if (value == 1) {
      return true;
    }
    throw new IOException(String.format("Expected 0 or 1, got %d", value));
  }

  @Override
  public boolean consistentWithEquals() {
    return true;
  }

  @Override
  public boolean isRegisterByteSizeObserverCheap(Boolean value) {
    return true;
  }

  @Override
  protected long getEncodedElementByteSize(Boolean value) throws Exception {
    return 1;
  }
}

View on GitHub (pinned to 12126d8942)

Solutions

  1. Verify data was written with BooleanCoder/BYTE_CODER (0/1 bytes), not raw Java or another format.
  2. Check stream alignment: ensure preceding fields are read with the same coder that wrote them.
  3. Re-generate the corrupted data if it was produced by a buggy writer.
  4. If interoping with other systems, agree on a single byte representation (0x00/0x01) for booleans.

Example fix

// before (writer packs booleans as bits)
out.writeBit(boolValue);
// after (writer uses a full byte)
out.write(boolValue ? 1 : 0);
Defensive patterns

Strategy: try-catch

Validate before calling

// validate bytes before decoding
if (!payload.every(b -> b == 0 || b == 1)) throw new IllegalStateException("Non-boolean byte in payload");

Try / catch

try {
  Boolean b = BooleanCoder.of().decode(in);
} catch (IOException e) {
  if (e.getMessage().startsWith("Expected 0 or 1")) {
    LOG.error("Corrupted boolean encoding; data not written by BooleanCoder", e);
  }
  throw e;
}

Prevention

When it happens

Trigger: Decoding a byte stream where the boolean byte is not exactly 0x00 or 0x01 - e.g. data written by a different (non-Beam) serializer, bit-packing bugs, or offset misalignment in a stream.

Common situations: Mixing custom serialization output with Beam coders; manual stream reads with wrong offsets (reading a bitfield or 2-byte value instead of 1 byte); data corruption in transit or at rest; version changes in record layout.

Related errors


AI-assisted analysis of apache/beam@12126d8942 (2026-09-13). Data as JSON: /api/errors/ab08ef4246ef6f93. Report an issue: GitHub.