nautechsystems/nautilus_trader · error

Invalid `usize` for 'limit'

Error message

Invalid `usize` for 'limit'

What it means

`Data::limit` prefers metadata["limit"] as a usize; if that's absent it tries the string form and `.parse::<usize>()`, panicking with "Invalid `usize` for 'limit'" when the string isn't a valid non-negative integer. This catches stringified limits that can't round-trip to a count, including negatives and floats.

Source

Thrown at crates/model/src/data/mod.rs:954

    pub fn end(&self) -> Option<UnixNanos> {
        let metadata = self.metadata.as_ref()?;
        let end_str = metadata.get_str("end")?;
        Some(UnixNanos::from_str(end_str).expect("Invalid `UnixNanos` for 'end'"))
    }

    /// Returns an [`Option<usize>`] parsed from the metadata `limit` field.
    ///
    /// # Panics
    ///
    /// This function panics if:
    /// - The `limit` value contained in the metadata is invalid.
    #[must_use]
    pub fn limit(&self) -> Option<usize> {
        let metadata = self.metadata.as_ref()?;
        metadata.get_usize("limit").or_else(|| {
            metadata
                .get_str("limit")
                .map(|s| s.parse::<usize>().expect("Invalid `usize` for 'limit'"))
        })
    }
}

impl PartialEq for DataType {
    fn eq(&self, other: &Self) -> bool {
        self.topic == other.topic
    }
}

impl Eq for DataType {}

impl PartialOrd for DataType {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

View on GitHub (pinned to 18893faf8b)

Solutions

  1. Set limit as a plain non-negative integer string, e.g. metadata["limit"] = "1000"
  2. Handle 'unlimited' by omitting the key (returns None) rather than a sentinel like "-1"
  3. Validate the string parses with int() before storing it in metadata

Example fix

// before
metadata["limit"] = "-1"  // unlimited sentinel — panics on parse
// after
# omit the key for unlimited, or:
metadata["limit"] = "1000"
Defensive patterns

Strategy: validation

Validate before calling

def validate_limit_metadata(metadata: dict) -> None:
    raw = metadata.get("limit")
    if raw is not None:
        value = int(raw)  # raises ValueError if malformed
        if value < 0:
            raise ValueError("limit must be a non-negative integer")

Type guard

def is_valid_limit_str(s: str) -> bool:
    return s.isdigit()

Try / catch

try:
    limit = data.limit()
except Exception as e:
    logger.error(f"malformed 'limit' metadata: {metadata.get('limit')!r}")
    raise

Prevention

When it happens

Trigger: Setting metadata["limit"] to "-1", "1.5", "1000 bars", or an empty string and then calling `.limit()` on the Data object.

Common situations: Config files with annotated numeric values (e.g. "limit: 1000 bars"); Python code storing ints with formatting; negative limits intended as 'unlimited' but represented as strings.

Understand the failure class

Background: "Invalid ... format", "must be in format X", "does not look like a ..." — invalid argument format errors across CLI tools and libraries — this error's family across 17 libraries.

Related errors


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