nautechsystems/nautilus_trader · info

writing to String should not fail

Error message

writing to String should not fail

What it means

This panic comes from `.expect("writing to String should not fail")` on the `write!(buf, ...)` result in `write_fixed_prefix` in crates/common/src/generators/position_id.rs. Formatting the date-time components into a `String` cannot fail under normal operation because `String`'s `fmt::Write` implementation only errors on allocation failure, so the code asserts the invariant with expect.

Source

Thrown at crates/common/src/generators/position_id.rs:150

        Timestamp::from_second(
            i64::try_from(epoch_second).expect("seconds timestamp should fit i64"),
        )
        .expect("seconds timestamp should be within valid range"),
    );

    buf.clear();

    write!(
        buf,
        "P-{:04}{:02}{:02}-{:02}{:02}{:02}-{trader_tag}-",
        now_utc.year(),
        now_utc.month(),
        now_utc.day(),
        now_utc.hour(),
        now_utc.minute(),
        now_utc.second(),
    )
    .expect("writing to String should not fail");
}

#[cfg(test)]
mod tests {
    use std::{cell::RefCell, rc::Rc};

    use nautilus_core::UnixNanos;
    use nautilus_model::{
        identifiers::{PositionId, StrategyId, TraderId},
        stubs::TestDefault,
    };
    use rstest::rstest;

    use crate::{clock::TestClock, generators::position_id::PositionIdGenerator};

    fn get_position_id_generator() -> PositionIdGenerator {
        PositionIdGenerator::new(
            TraderId::test_default(),

View on GitHub (pinned to 18893faf8b)

Solutions

  1. Treat it as an internal invariant assertion, not a user-facing error
  2. Check host memory if it ever fires; free memory or reduce allocation pressure
  3. Upstream alternative: return Result from write_fixed_prefix instead of expecting (library change)
Defensive patterns

Strategy: fallback

Try / catch

// infallible except OOM; no meaningful catch pattern

Prevention

When it happens

Trigger: Reached on every `refresh_fixed_prefix` call; only panics if the underlying String write fails, which in practice means memory allocation failure (OOM).

Common situations: Effectively never encountered by library users; would only appear under severe memory exhaustion in the host process.

Understand the failure class

Background: "This is a bug, please report it": internal invariant violations, unreachable panics, and SNH errors explained — this error's family across 47 libraries.

Related errors


AI-assisted analysis of nautechsystems/nautilus_trader@18893faf8b (2026-09-08). Data as JSON: /api/errors/c208812c456d53fb. Report an issue: GitHub.