{
  "id": "python/sqlalchemy-stale-data-race",
  "signature": "sqlalchemy.exc.StaleDataError: UPDATE statement on table 'users' expected to update 1 row(s); 0 were matched.",
  "signature_zh": "sqlalchemy.exc.StaleDataError: 对 'users' 表的 UPDATE 语句预期更新 1 行，但实际匹配到 0 行。",
  "regex": "sqlalchemy\\.exc\\.StaleDataError:\\ UPDATE\\ statement\\ on\\ table\\ 'users'\\ expected\\ to\\ update\\ 1\\ row\\(s\\);\\ 0\\ were\\ matched\\.",
  "domain": "python",
  "category": "data_error",
  "subcategory": null,
  "root_cause": "Another transaction deleted or modified the row between the SELECT and UPDATE, causing the ORM's version check or rowcount to fail.",
  "root_cause_type": "generic",
  "root_cause_zh": "在 SELECT 和 UPDATE 之间，另一个事务删除或修改了该行，导致 ORM 的版本检查或行计数失败。",
  "versions": [
    {
      "version": "1.4.x",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    },
    {
      "version": "2.0.x",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    }
  ],
  "os_specific": {},
  "dead_ends": [
    {
      "action": "",
      "why_fails": "Autoflush doesn't affect the underlying row version; the issue is concurrent modification, not flush timing.",
      "fail_rate": 0.7,
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "why_fails": "Refresh may still see stale data if the other transaction hasn't committed yet; it doesn't solve the race condition.",
      "fail_rate": 0.6,
      "condition": "",
      "sources": []
    }
  ],
  "workarounds": [
    {
      "action": "",
      "success_rate": 0.9,
      "how": "Implement optimistic locking with version_id_col: class User(Base): __mapper_args__ = {'version_id_col': version}",
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "success_rate": 0.85,
      "how": "Catch StaleDataError and retry the whole transaction with fresh data: for attempt in range(3): try: update() break except StaleDataError: session.rollback()",
      "condition": "",
      "sources": []
    }
  ],
  "workarounds_zh": [],
  "transition_graph": {
    "leads_to": [],
    "preceded_by": [],
    "frequently_confused_with": []
  },
  "official_doc_url": null,
  "official_doc_section": null,
  "error_code": null,
  "verification_tier": "ai_generated",
  "confidence": 0.82,
  "fix_success_rate": 0.8,
  "resolvable": "true",
  "first_seen": "2024-05-20",
  "last_confirmed": "2025-01-01",
  "last_updated": "2025-01-01",
  "evidence_count": 0,
  "tags": [],
  "locale": "en",
  "aliases": []
}