The stream reader drops a message of an unexpected type but not its body, and parses the body as the next messages

Abierto Apto para principiantes
#546 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

@Umer-Butt07 ya está trabajando en esto.

Desde el 30/11/2026.

  • #553 de @Umer-Butt07 — abierto

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
80/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
javascript, typescript
Área
data

Línea de trabajo

Ambos bucles están en src/ipc/reader.ts: RecordBatchStreamReaderImpl.next() alrededor de las líneas 504-530 y AsyncRecordBatchStreamReaderImpl.next() alrededor de las líneas 579-605, donde solo las ramas RecordBatch y DictionaryBatch llaman a reader.readMessageBody(message.bodyLength). Compila el paquete, ejecuta el repro.ts del issue contra él y confirma que actualmente termina con 1 con las 666 filas. Hecho significa que el repro termina con 0 — o ambos bucles lanzan una excepción con un tipo de header desconocido, o ambos consumen el body antes de seguir leyendo — y las pruebas existentes del IPC reader siguen pasando.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Describe the bug, including details regarding any error messages, version, and platform.

The stream reader drops a message whose header type is not Schema, RecordBatch or DictionaryBatch (for example Tensor, SparseTensor or NONE), but it does not skip the body of that message. So the next read starts inside the body, and the reader parses the body as the next messages. A reader that frames each message by its bodyLength, as the encapsulated message format says, sees different messages in the same bytes.

The repro puts a Tensor message between the Schema and the RecordBatch of a valid stream of [1, 2, 3]. The body of the Tensor message is the complete RecordBatch message of a second stream of [666, 777, 888]. tableFromIPC returns 6 rows, [666, 777, 888, 1, 2, 3], with no error.

Version and platform: apache-arrow 21.2.0, Node.js 24.21.0 on Windows 11. The code below is the same on main (5aa0205).

Repro. Save as repro.ts, install [email protected] and [email protected] (the version that apache-arrow installs), and run node repro.ts (Node.js 24 strips the types). It exits 1 while the fault is present.

// apache-arrow 21.2.0. The stream reader drops a message of an unexpected header type (for example Tensor), but it
// does not skip the body of that message. RecordBatchStreamReaderImpl.next() handles only Schema, RecordBatch and
// DictionaryBatch. So the reader parses the body as the next messages. A reader that frames each message by its
// bodyLength sees different rows in the same bytes.
import * as A from "apache-arrow";
import { Message } from "apache-arrow/fb/message";
import * as flatbuffers from "flatbuffers";

// This function gives the bounds of each message of a stream, and the root table of its metadata.
function messages(bytes: Uint8Array) {
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  const found = [];
  let start = 0;
  while (start + 8 <= bytes.length) {
    const metadataLength = view.getInt32(start + 4, true);
    if (metadataLength === 0) {
      found.push({ start, metadataEnd: start + 8, end: start + 8, header: "EOS", bodyLength: 0, fb: null });
      break;
    }
    const metadataEnd = start + 8 + metadataLength;
    const fb = Message.getRootAsMessage(new flatbuffers.ByteBuffer(bytes.slice(start + 8, metadataEnd)));
    const bodyLength = Number(fb.bodyLength());
    found.push({ start, metadataEnd, end: metadataEnd + bodyLength, header: A.MessageHeader[fb.headerType()], bodyLength, fb });
    start = metadataEnd + bodyLength;
  }
  return found;
}

const visible = A.tableToIPC(A.tableFromArrays({ x: Int32Array.of(1, 2, 3) }), "stream");
const hidden = A.tableToIPC(A.tableFromArrays({ x: Int32Array.of(666, 777, 888) }), "stream");
const [schema, batch, end] = messages(visible);
const hiddenBatch = messages(hidden)[1]!;
const hiddenBytes = hidden.slice(hiddenBatch.start, hiddenBatch.end);

// A Tensor message: the prefix and metadata of the RecordBatch, with the header type 4 (Tensor) and a bodyLength
// that covers the complete RecordBatch message of the hidden stream. Message field 1 (vtable offset 6) is
// header_type and field 3 (vtable offset 10) is bodyLength.
const fb = batch!.fb!;
const tensor = visible.slice(batch!.start, batch!.metadataEnd);
const headerTypePosition = 8 + fb.bb_pos + fb.bb!.__offset(fb.bb_pos, 6);
const bodyLengthPosition = 8 + fb.bb_pos + fb.bb!.__offset(fb.bb_pos, 10);
tensor[headerTypePosition] = A.MessageHeader.Tensor;
new DataView(tensor.buffer).setBigInt64(bodyLengthPosition, BigInt(hiddenBytes.length), true);

const crafted = new Uint8Array([
  ...visible.subarray(schema!.start, schema!.end),
  ...tensor,
  ...hiddenBytes,
  ...visible.subarray(batch!.start, batch!.end),
  ...visible.subarray(end!.start, end!.end),
]);

console.log(`messages by bodyLength: ${messages(crafted).map((m) => `${m.header} (body ${m.bodyLength})`).join(", ")}`);
const rows = (bytes: Uint8Array): string => {
  try {
    const table = A.tableFromIPC(bytes);
    return `${table.numRows} rows, x = ${JSON.stringify(Array.from(table.getChild("x") ?? []))}`;
  } catch (error) {
    return `throws: ${(error as Error).message}`;
  }
};
console.log(`tableFromIPC(original stream): ${rows(visible)}`);
const result = rows(crafted);
console.log(`tableFromIPC(stream with the Tensor message): ${result}`);

if (result.includes("666")) {
  console.log("BUG PRESENT: the reader returns the rows 666, 777 and 888 from the body of the Tensor message.");
  process.exit(1);
}
console.log("OK: the reader skips the body of the Tensor message, or refuses the message.");

Output:

messages by bodyLength: Schema (body 0), Tensor (body 160), RecordBatch (body 16), EOS (body 0)
tableFromIPC(original stream): 3 rows, x = [1,2,3]
tableFromIPC(stream with the Tensor message): 6 rows, x = [666,777,888,1,2,3]
BUG PRESENT: the reader returns the rows 666, 777 and 888 from the body of the Tensor message.
exit code: 1

Expected: An error for a message type that the stream format does not permit, or a reader that skips bodyLength bytes of the message before it reads the next one. The rows 666, 777 and 888 are not in the stream when each message is framed by its bodyLength.

Cause: RecordBatchStreamReaderImpl.next() in src/ipc/reader.ts (lines 504 to 530) has a branch for isSchema(), isRecordBatch() and isDictionaryBatch(), and no else. Only the RecordBatch and DictionaryBatch branches call reader.readMessageBody(message.bodyLength). For each other header type the loop reads the next message from the current position, which is the start of the body. AsyncRecordBatchStreamReaderImpl.next() (lines 579 to 605) has the same loop.

https://github.com/apache/arrow-js/blob/5aa020540217b1aef9571cd3c9473627cd909e2f/src/ipc/reader.ts#L504-L530

Possible fix: Add an else branch to both loops that throws an error that names the header type, because a stream holds only Schema, DictionaryBatch and RecordBatch messages. If the reader must accept such messages, the else branch can read and drop the body with reader.readMessageBody(message.bodyLength).

An AI coding assistant (Claude Code) found this fault, wrote the repro and wrote this text.

Component(s)

JavaScript

Lenguaje dominante
TypeScript
Estrellas
114
Forks
35
Merge medio
13 h 35 min
PR fusionados (30 d)
5

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de apache/arrow-js

Todos los issues de apache/arrow-js

Issues similares

Más issues de TypeScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.