From e2732f5e8a93971525149c550ee73aef9c8a7a91 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 09:34:49 -0600 Subject: [PATCH] Risk batches: a decision that collides with another of the same batch is a 409 Two decisions of one batch at the same moment (a double click reaching both workers) wrote the same evaluation version and the second surfaced as a server error. --- tests/test_risk_batches.py | 14 ++++++++++++++ webapi/risk_batches.py | 6 +++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/tests/test_risk_batches.py b/tests/test_risk_batches.py index 14b7e5a..a374c88 100644 --- a/tests/test_risk_batches.py +++ b/tests/test_risk_batches.py @@ -100,3 +100,17 @@ def test_an_unknown_batch_is_404(client): """Pins down: a `lote_id` with no evaluations is 404, not a silent no-op. Fails if it answers 200 having changed nothing.""" assert client.post("/cacu/riesgos/lotes/987654321/confirmar", json={"reason": "revisado"}).status_code == 404 + + +def test_a_decision_that_collides_with_another_is_409(client, monkeypatch): + """Pins down: two decisions of one batch at the same moment (a double click reaching both workers) give the + second a 409 instead of a server error. Fails if the unique version of an evaluation surfaces as a 500.""" + from persistance import cacu + from sqlalchemy.exc import IntegrityError + + def collide(*args, **kwargs): + raise IntegrityError("INSERT", {}, Exception("UNIQUE constraint failed")) + + monkeypatch.setattr(cacu.cohort_repository, "change_state", collide) + + assert client.post("/cacu/riesgos/lotes/1/confirmar", json={"reason": "revisado"}).status_code == 409 diff --git a/webapi/risk_batches.py b/webapi/risk_batches.py index 8e739fe..f6b1afb 100644 --- a/webapi/risk_batches.py +++ b/webapi/risk_batches.py @@ -6,6 +6,7 @@ to be defined. """ from flask import Blueprint, jsonify, request +from sqlalchemy.exc import IntegrityError from persistance.edges.gold import ERROR, FINAL @@ -34,7 +35,10 @@ def risk_batches_blueprint(repositories, name: str = "risk_batches") -> Blueprin reason = (request.get_json(silent=True) or {}).get("reason", "").strip() if not reason: return jsonify({"error": "se requiere un motivo"}), 400 - changed = repositories.cohort_repository.change_state(lote_id, estado, reason) + try: + changed = repositories.cohort_repository.change_state(lote_id, estado, reason) + except IntegrityError: # another request decided the same batch at the same moment + return jsonify({"error": f"el lote {lote_id} ya se está decidiendo en otra solicitud"}), 409 if not changed: return jsonify({"error": f"el lote {lote_id} no existe o ya no tiene evaluaciones vigentes"}), 404 return jsonify({"lote_id": lote_id, "evaluaciones_cambiadas": changed})