pola-rs/polars · error · PolarsError

Cannot write to a finished stream

Error message

Cannot write to a finished stream

What it means

IpcStreamWriter/FileWriter::write checks a `finished` flag and returns a PolarsError (from an UnexpectedEof io::Error) if the stream has already been finished via .finish(). After finish, the stream's trailers/metadata have been written and no further record batches may be appended.

Solutions

  1. Restructure code so finish() is called exactly once, after all write() calls.
  2. Collect all record batches first, then open a fresh writer if you need to re-emit them after finishing.
  3. If you need the finished bytes, use the result of finish()/into_inner() instead of writing again.

Example fix

// before
for batch in batches {
    writer.write(&batch)?;
    writer.finish()?; // stream finished on first iteration
}

// after
for batch in batches {
    writer.write(&batch)?;
}
writer.finish()?;
Defensive patterns

Strategy: try-catch

Validate before calling

struct OnceWriter<'a, W: Write> { writer: IpcStreamWriter<'a, W>, done: bool }
impl<'a, W: Write> OnceWriter<'a, W> {
    fn write_batch(&mut self, b: &RecordBatchT<Box<dyn Array>>) -> PolarsResult<()> {
        if self.done { polars_bail!(opq = "stream already finished"); }
        self.writer.write(b)
    }
    fn finish(&mut self) -> PolarsResult<()> { self.done = true; self.writer.finish() }
}

Try / catch

match writer.write(&batch) {
    Ok(()) => {},
    Err(e) if e.to_string().contains("finished stream") => {
        // recreate the writer and re-emit remaining batches
    },
    Err(e) => return Err(e),
}

Prevention

When it happens

Trigger: Calling write() on an IpcStreamWriter or IpcFileWriter after finish()/into_inner() was already called (crates/polars-arrow/src/io/ipc/write/stream.rs:93).

Common situations: Writing batches in a loop that also calls finish() per iteration; reusing a writer after moving it through finish to get bytes; retries that re-invoke write after a successful finish.

Understand the failure class

Background: "Invalid state transition" errors: "status must be X, actually Y", "already rejected/charging/uninstalled", "cannot ... while running" — what they mean when a library rejects your call — this error's family across 31 libraries.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/2cd2d467b151d70c. Report an issue: GitHub.

Appendix: source

Thrown at crates/polars-arrow/src/io/ipc/write/stream.rs:93

            ipc_message: schema_to_bytes(
                schema,
                self.ipc_fields.as_ref().unwrap(),
                self.custom_schema_metadata.as_deref(),
            ),
            arrow_data: vec![],
        };
        write_message(&mut self.writer, &encoded_message)?;
        Ok(())
    }

    /// Writes [`RecordBatchT`] to the stream
    pub fn write(
        &mut self,
        columns: &RecordBatchT<Box<dyn Array>>,
        ipc_fields: Option<&[IpcField]>,
    ) -> PolarsResult<()> {
        if self.finished {
            let io_err = std::io::Error::new(
                std::io::ErrorKind::UnexpectedEof,
                "Cannot write to a finished stream".to_string(),
            );
            return Err(PolarsError::from(io_err));
        }

        // we can't make it a closure because it borrows (and it can't borrow mut and non-mut below)
        #[allow(clippy::or_fun_call)]
        let fields = ipc_fields.unwrap_or(self.ipc_fields.as_ref().unwrap());

        let (encoded_dictionaries, encoded_message) = encode_chunk(
            columns,
            fields,
            &mut self.dictionary_tracker,
            &self.write_options,
        )?;

        for encoded_dictionary in encoded_dictionaries {

View on GitHub (pinned to fe841f959e)