{"record":{"id":"3b5aabdab7eb6242","repo":"nautechsystems/nautilus_trader","slug":"failed-to-load-instrument-with-id-instrument-id","errorCode":null,"errorMessage":"Failed to load instrument with id {instrument_id},error is: {e}","messagePattern":"Failed to load instrument with id (.+?),error is: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/infrastructure/src/sql/queries.rs","lineNumber":225,"sourceCode":"            .map_err(|e| anyhow::anyhow!(\"Failed to insert item {} into instrument table: {:?}\", instrument.id(), e))\n    }\n\n    /// Loads a single `InstrumentAny` entry by `instrument_id` via the provided `pool`.\n    ///\n    /// # Errors\n    ///\n    /// Returns an error if the SELECT operation fails.\n    pub async fn load_instrument(\n        pool: &PgPool,\n        instrument_id: &InstrumentId,\n    ) -> anyhow::Result<Option<InstrumentAny>> {\n        sqlx::query_as::<_, InstrumentAnyRow>(\"SELECT * FROM instrument WHERE id = $1\")\n            .bind(instrument_id.to_string())\n            .fetch_optional(pool)\n            .await\n            .map(|instrument| instrument.map(|row| row.0))\n            .map_err(|e| {\n                anyhow::anyhow!(\"Failed to load instrument with id {instrument_id},error is: {e}\")\n            })\n    }\n\n    /// Loads all `InstrumentAny` entries via the provided `pool`.\n    ///\n    /// # Errors\n    ///\n    /// Returns an error if the SELECT operation fails.\n    pub async fn load_instruments(pool: &PgPool) -> anyhow::Result<Vec<InstrumentAny>> {\n        sqlx::query_as::<_, InstrumentAnyRow>(\"SELECT * FROM instrument\")\n            .fetch_all(pool)\n            .await\n            .map(|rows| rows.into_iter().map(|row| row.0).collect())\n            .map_err(|e| anyhow::anyhow!(\"Failed to load instruments: {e}\"))\n    }\n\n    /// Inserts or replaces an `InstrumentClose`.\n    ///","sourceCodeStart":207,"sourceCodeEnd":243,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/infrastructure/src/sql/queries.rs#L207-L243","documentation":"`DatabaseQueries::load_instrument` runs `SELECT * FROM instrument WHERE id = $1` and returns Ok(None) for a missing row — not-found is not an error. This anyhow error is raised only on execution failure (connectivity, missing table) or row-decoding failure, where a stored instrument row can't be converted into `InstrumentAny`, typically due to schema drift or an enum/kind value written by a different version.","triggerScenarios":"Calling `DatabaseQueries::load_instrument(pool, instrument_id)` when the connection fails, the `instrument` table doesn't exist, or the row fails to decode (e.g. a newer instrument kind or asset_class value the current decoder rejects, or a malformed numeric column).","commonSituations":"Loading instruments at strategy startup from a database written by a different Nautilus version; fresh DB without migrations; rows containing new enum variants; transient network failure during the lookup.","solutions":["Run migrations matching this code version so the table and enum types decode correctly.","Identify the undecodable row from the inner sqlx decode error; upgrade the binary or re-write the row with the current version.","Confirm DATABASE_URL targets the correct cache database.","Treat Ok(None) as 'instrument not cached' and handle it separately from this error."],"exampleFix":"// before\nlet instrument = DatabaseQueries::load_instrument(&pool, &instrument_id).await?;\n// after\nlet instrument = match DatabaseQueries::load_instrument(&pool, &instrument_id).await? {\n    Some(instrument) => Some(instrument),\n    None => {\n        tracing::warn!(\"instrument {instrument_id} not in cache\");\n        None\n    }\n};","handlingStrategy":"try-catch","validationCode":"let exists: bool = sqlx::query_scalar(\n    \"SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'instrument')\",\n).fetch_one(pool).await?;\nif !exists {\n    return Err(anyhow::anyhow!(\"'instrument' table missing — run migrations\"));\n}","typeGuard":null,"tryCatchPattern":"match DatabaseQueries::load_instrument(&pool, &instrument_id).await {\n    Ok(Some(instrument)) => Some(instrument),\n    Ok(None) => {\n        tracing::warn!(\"instrument {instrument_id} not in cache\");\n        None\n    }\n    Err(e) => return Err(e),\n}","preventionTips":["Run matching migrations before loading instruments from the cache.","Handle Ok(None) as 'not cached' separately from execution/decode errors.","Keep reader and writer application versions aligned to avoid decode failures from new enum/kind values.","Log the instrument_id together with the inner sqlx error to pinpoint schema drift."],"tags":["postgres","sqlx","database","select","instrument"],"backgroundTag":"database-query-failed","analyzedSha":"18893faf8b356be3320add8de2f861b0b647cf06","analyzedAt":"2026-09-08T20:49:34.690Z","contentChangedAt":"2026-09-08T20:49:34.690Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}