{"record":{"id":"cf6d18c5262c51a9","repo":"nautechsystems/nautilus_trader","slug":"failed-to-load-position-snapshot-e","errorCode":null,"errorMessage":"Failed to load position snapshot: {e}","messagePattern":"Failed to load position snapshot: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/infrastructure/src/sql/queries.rs","lineNumber":568,"sourceCode":"            .await\n            .map_err(|e| anyhow::anyhow!(\"Failed to commit transaction: {e}\"))\n    }\n\n    /// Loads a `PositionSnapshot` entry by `position_id` via the provided `pool`.\n    ///\n    /// # Errors\n    ///\n    /// Returns an error if the SQL SELECT or deserialization fails.\n    pub async fn load_position_snapshot(\n        pool: &PgPool,\n        position_id: &PositionId,\n    ) -> anyhow::Result<Option<PositionSnapshot>> {\n        sqlx::query_as::<_, PositionSnapshotRow>(r#\"SELECT * FROM \"position\" WHERE id = $1\"#)\n            .bind(position_id.to_string())\n            .fetch_optional(pool)\n            .await\n            .map(|row| row.map(|row| row.0))\n            .map_err(|e| anyhow::anyhow!(\"Failed to load position snapshot: {e}\"))\n    }\n\n    /// Checks if an `OrderInitialized` event exists for the given `client_order_id` via the provided `pool`.\n    ///\n    /// # Errors\n    ///\n    /// Returns an error if the SQL SELECT operation fails.\n    pub async fn check_if_order_initialized_exists(\n        pool: &PgPool,\n        client_order_id: ClientOrderId,\n    ) -> anyhow::Result<bool> {\n        sqlx::query(r#\"\n            SELECT EXISTS(SELECT 1 FROM \"order_event\" WHERE client_order_id = $1 AND kind = 'OrderInitialized')\n        \"#)\n            .bind(client_order_id.to_string())\n            .fetch_one(pool)\n            .await\n            .map(|row| row.get(0))","sourceCodeStart":550,"sourceCodeEnd":586,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/infrastructure/src/sql/queries.rs#L550-L586","documentation":"This error wraps any sqlx failure that occurs when loading a single row from the `position` table by its id into a `PositionSnapshot`. The library throws it because the underlying database driver error (connection loss, missing table, type mismatch, etc.) is converted into an `anyhow::Error` with context so callers get a clear message. It indicates the SELECT query itself failed at the database level, not that the position was absent (absence returns `Ok(None)`).","triggerScenarios":"Calling `load_position_snapshot(pool, position_id)` when the database connection is broken, the `position` table/schema does not match `PositionSnapshotRow`, the id string cannot be compared to the column type, or the row fails to deserialize into `PositionSnapshotRow`.","commonSituations":"Postgres is down or restarting during reconciliation startup; a schema migration drifted from the Rust row struct; connecting to the wrong database (empty schema); wrong SSL credentials causing connection failures mid-query.","solutions":["Verify the database is reachable and the connection pool is healthy (run a trivial `SELECT 1` with the same pool).","Check the `position` table schema matches `PositionSnapshotRow` fields/column types; run pending migrations.","Confirm `position_id.to_string()` produces the exact id format stored in the table.","Inspect the wrapped sqlx error text in `{e}` to identify the precise driver cause.","Retry the snapshot load; transient network errors are common during reconciliation."],"exampleFix":"// before\nlet snap = load_position_snapshot(&pool, position_id).await?;\n// after\nlet snap = match load_position_snapshot(&pool, position_id).await {\n    Ok(s) => s,\n    Err(e) => { tracing::error!(\"snapshot load failed: {e:#}\"); return Err(e); }\n};","handlingStrategy":"try-catch","validationCode":"// Rust: verify connectivity before loading\nsqlx::query(\"SELECT 1\").execute(pool).await\n    .map_err(|e| anyhow::anyhow!(\"db unreachable: {e}\"))?;\nsqlx::query(r#\"SELECT EXISTS(SELECT 1 FROM \"position\")\"#)\n    .fetch_one(pool).await\n    .map_err(|e| anyhow::anyhow!(\"position table missing: {e}\"))?;","typeGuard":"fn is_connectivity_error(e: &anyhow::Error) -> bool {\n    e.to_string().contains(\"connection\") || e.to_string().contains(\"timed out\")\n}","tryCatchPattern":"match load_position_snapshot(&pool, position_id).await {\n    Ok(Some(snap)) => { /* use snapshot */ }\n    Ok(None) => { /* position absent — normal path */ }\n    Err(e) if is_connectivity_error(&e) => { /* retry with backoff */ }\n    Err(e) => return Err(e.context(\"position snapshot load\")),\n}","preventionTips":["Run schema migrations before starting reconciliation.","Health-check the pool with SELECT 1 before batch reads.","Pin database and driver versions across environments.","Log the full error chain ({e:#}) to preserve the sqlx cause."],"tags":["database","sqlx","postgres","anyhow"],"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"}