{"record":{"id":"2cd2d467b151d70c","repo":"pola-rs/polars","slug":"cannot-write-to-a-finished-stream","errorCode":null,"errorMessage":"Cannot write to a finished stream","messagePattern":"Cannot write to a finished stream","errorType":"exception","errorClass":"PolarsError","httpStatus":null,"severity":"error","filePath":"crates/polars-arrow/src/io/ipc/write/stream.rs","lineNumber":93,"sourceCode":"            ipc_message: schema_to_bytes(\n                schema,\n                self.ipc_fields.as_ref().unwrap(),\n                self.custom_schema_metadata.as_deref(),\n            ),\n            arrow_data: vec![],\n        };\n        write_message(&mut self.writer, &encoded_message)?;\n        Ok(())\n    }\n\n    /// Writes [`RecordBatchT`] to the stream\n    pub fn write(\n        &mut self,\n        columns: &RecordBatchT<Box<dyn Array>>,\n        ipc_fields: Option<&[IpcField]>,\n    ) -> PolarsResult<()> {\n        if self.finished {\n            let io_err = std::io::Error::new(\n                std::io::ErrorKind::UnexpectedEof,\n                \"Cannot write to a finished stream\".to_string(),\n            );\n            return Err(PolarsError::from(io_err));\n        }\n\n        // we can't make it a closure because it borrows (and it can't borrow mut and non-mut below)\n        #[allow(clippy::or_fun_call)]\n        let fields = ipc_fields.unwrap_or(self.ipc_fields.as_ref().unwrap());\n\n        let (encoded_dictionaries, encoded_message) = encode_chunk(\n            columns,\n            fields,\n            &mut self.dictionary_tracker,\n            &self.write_options,\n        )?;\n\n        for encoded_dictionary in encoded_dictionaries {","sourceCodeStart":75,"sourceCodeEnd":111,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/crates/polars-arrow/src/io/ipc/write/stream.rs#L75-L111","documentation":"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.","triggerScenarios":"Calling write() on an IpcStreamWriter or IpcFileWriter after finish()/into_inner() was already called (crates/polars-arrow/src/io/ipc/write/stream.rs:93).","commonSituations":"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.","solutions":["Restructure code so finish() is called exactly once, after all write() calls.","Collect all record batches first, then open a fresh writer if you need to re-emit them after finishing.","If you need the finished bytes, use the result of finish()/into_inner() instead of writing again."],"exampleFix":"// before\nfor batch in batches {\n    writer.write(&batch)?;\n    writer.finish()?; // stream finished on first iteration\n}\n\n// after\nfor batch in batches {\n    writer.write(&batch)?;\n}\nwriter.finish()?;","handlingStrategy":"try-catch","validationCode":"struct OnceWriter<'a, W: Write> { writer: IpcStreamWriter<'a, W>, done: bool }\nimpl<'a, W: Write> OnceWriter<'a, W> {\n    fn write_batch(&mut self, b: &RecordBatchT<Box<dyn Array>>) -> PolarsResult<()> {\n        if self.done { polars_bail!(opq = \"stream already finished\"); }\n        self.writer.write(b)\n    }\n    fn finish(&mut self) -> PolarsResult<()> { self.done = true; self.writer.finish() }\n}","typeGuard":null,"tryCatchPattern":"match writer.write(&batch) {\n    Ok(()) => {},\n    Err(e) if e.to_string().contains(\"finished stream\") => {\n        // recreate the writer and re-emit remaining batches\n    },\n    Err(e) => return Err(e),\n}","preventionTips":["Call finish() exactly once, after the last write().","Wrap writers in a state flag or RAII guard that forbids writes post-finish.","In retry logic, recreate the writer rather than reusing a finished one."],"tags":["arrow","ipc","stream","lifecycle"],"backgroundTag":"invalid-state-transition","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}