YongGoose opened a new issue, #1055:
URL: https://github.com/apache/burr/issues/1055
### Current behavior
When two `Application` instances resume the same `app_id` from the same
saved state (a double-submitted request, a retried job, two workers picking up
one conversation), both run the next step and both save it under the same
`sequence_id`. What happens to the second save depends on the persister:
| Persister | Second save, one after the other | Same step saved at the same
moment |
|---|---|---|
| `SQLitePersister` | `sqlite3.IntegrityError` | never both succeeded (0/200
rounds) |
| `PostgreSQLPersister` (psycopg2) | `psycopg2.errors.UniqueViolation`, and
the persister is unusable afterwards: its next `load()` raises
`InFailedSqlTransaction` | never both succeeded (0/200) |
| `RedisBasePersister` | `ValueError("... already exists.")` | **both
succeeded in 161/200 rounds**; the later `hset` overwrites the earlier one |
| `MongoDBBasePersister` | `ValueError("... already exists.")` | **both
succeeded in 199/200 rounds**; two documents for the same step |
Redis and MongoDB check for the key (`exists` / `find_one`) and then write
in a separate command, so two writers can both pass the check. The SQL
persisters are protected by the primary key but surface the driver's own
exception, and `PostgreSQLPersister.save()` never rolls back, so the shared
connection stays in an aborted transaction. In a web server that shares one
persister across requests, one conflict makes every later request on that
persister fail.
`AerospikePersister` already handles this: it writes with
`POLICY_EXISTS_CREATE` and raises `AerospikePersistenceConsistencyError` when
the existing record differs.
Retrying a failed step on the same `Application` does not reuse its
`sequence_id` (the failed attempt is saved as `0/failed`, the retry as
`1/completed`), so a second save of the same `sequence_id` always means another
writer got there first.
### Steps to replicate behavior
```python
import uuid
from burr.core import ApplicationBuilder, State, action
from burr.core.persistence import SQLitePersister
@action(reads=["chat"], writes=["chat"])
def human_input(state: State, prompt: str) -> State:
return state.append(chat=prompt)
def worker(persister, app_id):
return (
ApplicationBuilder()
.with_actions(human_input)
.with_transitions(("human_input", "human_input"))
.initialize_from(
persister,
resume_at_next_action=True,
default_state={"chat": []},
default_entrypoint="human_input",
)
.with_state_persister(persister)
.with_identifiers(app_id=app_id)
.build()
)
persister = SQLitePersister(db_path="race.db", table_name="burr_state")
persister.initialize()
app_id = str(uuid.uuid4())
worker(persister, app_id).run(halt_after=["human_input"], inputs={"prompt":
"hi"})
a, b = worker(persister, app_id), worker(persister, app_id) # both load the
same saved step
a.run(halt_after=["human_input"], inputs={"prompt": "A"})
b.run(halt_after=["human_input"], inputs={"prompt": "B"})
# sqlite3.IntegrityError: UNIQUE constraint failed: ... (raised after the
action ran)
```
The same script with `PostgreSQLPersister`, `RedisBasePersister` or
`MongoDBBasePersister` gives the second column of the table. For the third
column, two threads released by a `threading.Barrier` each call
`persister.save(None, app_id, 0, "human_input", State(...), "completed")` on
their own persister instance, for 200 fresh `app_id`s, and I counted the rounds
where both calls returned.
### Expected behavior
Every built-in persister treats a second save of the same `(partition_key,
app_id, sequence_id)` the same way:
- The check and the write are atomic, so exactly one writer wins, even when
both save at the same moment.
- The other writer gets one Burr exception instead of a driver-specific one,
so callers can catch it, reload, and retry.
- The persister stays usable after the conflict.
### Library & system information
- burr: `main` at 6cfac87
- Python 3.12 in a Linux container, against `postgres:15`, `redis:7` and
`mongo:7.0` (the images the persister CI job uses)
- I ran the sync persisters above. I have not run the async ones yet
(`AsyncSQLitePersister`, `AsyncPostgreSQLPersister`,
`AsyncRedisBasePersister`); their `save()` has the same structure.
### Proposed fix
- Add `burr.core.persistence.PersistenceConflictError`, a `ValueError`
subclass so code that catches the current Redis/MongoDB `ValueError` keeps
working.
- SQL persisters: turn the unique-key violation into that error. psycopg2
rolls back first, so the connection stays usable.
- Redis (sync and async): do the existence check and both writes in one
`WATCH`/`MULTI` transaction.
- MongoDB: add a unique index on `(partition_key, app_id, sequence_id)` and
map `DuplicateKeyError` to the new error. If existing duplicate documents
prevent creating the index, log a warning and keep today's check.
- Docs: a short note in the state persistence page on what to do when two
instances resume one app.
Out of scope: stopping the second action from running in the first place.
That needs a lock around the whole step (closer to #786). This change makes the
failure clear and safe, but the duplicate action's side effects still happen.
I'm working on a fix and will open a PR.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]