From cd6c6856e02da2876ceda6af0980a7fb45bcae70 Mon Sep 17 00:00:00 2001 From: JeyBee Date: Mon, 28 Sep 2026 08:22:25 +0000 Subject: [PATCH] Make the first S3 write create-only With if_match=None, S3Storage omitted IfMatch and did an unconditional PutObject. Two processes bootstrapping an empty key both read (b"", None) and both wrote, so the loser's first operation (e.g. an enqueue) was silently overwritten. InMemoryStorage, LocalFileSystemStorage and GCSStorage already treat if_match=None as "must not exist". Send IfNoneMatch="*" when if_match is None so S3 rejects the second creator with PreconditionFailed, and also map 409 ConditionalRequestConflict to CASConflictError. Document if_match=None as create-only in the port contract and README. --- README.md | 16 +++--- jqueue/adapters/storage/s3.py | 19 +++++-- jqueue/ports/storage.py | 13 +++-- tests/test_storage_s3.py | 100 +++++++++++++++++++++++++++++++++- 4 files changed, 130 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 3a29313..d00feb3 100644 --- a/README.md +++ b/README.md @@ -497,7 +497,7 @@ class MyStorage: async def write(self, content: bytes, if_match: str | None = None) -> str: """ Conditional write. - - if_match=None → unconditional put (first write) + - if_match=None → create-only put (first write); raise CASConflictError if it exists - if_match=etag → only write if current etag matches; raise CASConflictError otherwise Returns the new etag. """ @@ -749,16 +749,14 @@ trade-off is one hash computation per read and write, but for the file sizes jqu produces (kilobytes) this is negligible. **First-write semantics.** When the queue is brand new and no blob exists yet, the -adapter receives `if_match=None`. S3 and GCS handle this differently. S3 simply omits -the `IfMatch` header, making the first write unconditional — if two processes race to -create the blob, the last one wins silently. GCS uses `if_generation_match=0`, which is -a GCS convention meaning "only succeed if the object does not exist yet." This means -GCS's first write is itself conditional — a useful extra safety net against concurrent -initialisers, but it also means you can get a `CASConflictError` on the very first write -if two processes start simultaneously. +adapter receives `if_match=None`, meaning "create the object; fail if it already +exists". S3 sends `IfNoneMatch: *`; GCS uses `if_generation_match=0`, the GCS +convention for the same thing. Either way the first write is conditional, so two +processes racing to create the blob can't silently overwrite each other's first +operation — the loser gets a `CASConflictError` and retries against the winner's state. In practice this rarely matters because the retry loop handles it, but it's worth -understanding if you're debugging queue initialisation issues on GCS. +understanding if you're debugging queue initialisation issues. **Error classification.** The adapters distinguish three kinds of failures: `CASConflictError` (expected, retried automatically), `StorageError` (I/O problem with diff --git a/jqueue/adapters/storage/s3.py b/jqueue/adapters/storage/s3.py index ecbe2e5..fe6c10d 100644 --- a/jqueue/adapters/storage/s3.py +++ b/jqueue/adapters/storage/s3.py @@ -12,7 +12,12 @@ → CASConflictError First write (if_match=None): - IfMatch is omitted — unconditional put. + IfNoneMatch="*" — create-only put; S3 rejects it with PreconditionFailed if + the object already exists, so concurrent initialisers cannot overwrite each + other. + +Concurrent conditional writes to the same key may also be rejected with +409 ConditionalRequestConflict; that is mapped to CASConflictError as well. Compatible with S3-compatible storage that supports conditional writes: MinIO, Cloudflare R2, Tigris, etc. @@ -103,16 +108,19 @@ async def write( "Body": content, "ContentType": "application/json", } - if if_match is not None: + if if_match is None: + put_kwargs["IfNoneMatch"] = "*" + else: put_kwargs["IfMatch"] = if_match try: response = await s3.put_object(**put_kwargs) return str(response["ETag"]) except Exception as exc: - if _s3_error_code(exc) == "PreconditionFailed": + code = _s3_error_code(exc) + if code in _CAS_CONFLICT_CODES: raise CASConflictError( - "S3 ETag mismatch (PreconditionFailed)" + f"S3 conditional write failed ({code})" ) from exc raise except (CASConflictError, StorageError): @@ -121,6 +129,9 @@ async def write( raise StorageError("S3 write failed", exc) from exc +_CAS_CONFLICT_CODES = frozenset({"PreconditionFailed", "ConditionalRequestConflict"}) + + def _s3_error_code(exc: Exception) -> str: """Extract the error code from a botocore ClientError, or return ''.""" try: diff --git a/jqueue/ports/storage.py b/jqueue/ports/storage.py index f55e80e..0413ee0 100644 --- a/jqueue/ports/storage.py +++ b/jqueue/ports/storage.py @@ -8,8 +8,11 @@ CAS write contract ------------------ write(content, if_match=None) - - if if_match is None → unconditional put (used for the very first write) - - if if_match is given → conditional put + - if if_match is None → create-only put: succeeds only if the object does + not exist yet (used for the very first write) + - if if_match is given → conditional put: succeeds only if the current + etag matches + Either way: succeeds → storage returns the new etag (opaque str) fails → raises CASConflictError @@ -67,7 +70,8 @@ async def write( Parameters ---------- content : new object body - if_match : etag from the previous read(), or None for unconditional write + if_match : etag from the previous read(), or None to create the object + (fails if it already exists) Returns ------- @@ -75,7 +79,8 @@ async def write( Raises ------ - CASConflictError if if_match is provided but does not match the current etag + CASConflictError if if_match does not match the current etag, or + if_match is None and the object already exists StorageError for any other I/O failure """ ... diff --git a/tests/test_storage_s3.py b/tests/test_storage_s3.py index 7820ef1..d42e7d5 100644 --- a/tests/test_storage_s3.py +++ b/tests/test_storage_s3.py @@ -1,8 +1,10 @@ +import asyncio from unittest.mock import AsyncMock, MagicMock import pytest from jqueue.adapters.storage.s3 import S3Storage, _s3_error_code +from jqueue.core.direct import DirectQueue from jqueue.domain.errors import CASConflictError, StorageError # --------------------------------------------------------------------------- @@ -96,7 +98,7 @@ async def test_read_generic_exception_raises_storage_error(): # --------------------------------------------------------------------------- -async def test_write_without_if_match_no_condition_header(): +async def test_write_without_if_match_is_create_only(): storage, s3 = _make_storage() s3.put_object.return_value = {"ETag": '"new-etag"'} @@ -104,6 +106,7 @@ async def test_write_without_if_match_no_condition_header(): assert etag == '"new-etag"' call_kwargs = s3.put_object.call_args.kwargs + assert call_kwargs["IfNoneMatch"] == "*" assert "IfMatch" not in call_kwargs @@ -116,6 +119,7 @@ async def test_write_with_if_match_sends_condition(): assert etag == '"new-etag"' call_kwargs = s3.put_object.call_args.kwargs assert call_kwargs["IfMatch"] == '"old-etag"' + assert "IfNoneMatch" not in call_kwargs async def test_write_sends_correct_bucket_and_key(): @@ -138,6 +142,33 @@ async def test_write_precondition_failed_raises_cas_conflict(): await storage.write(b"data", if_match='"etag"') +async def test_create_when_object_exists_raises_cas_conflict(): + storage, s3 = _make_storage() + s3.put_object.side_effect = _client_error("PreconditionFailed") + + with pytest.raises(CASConflictError): + await storage.write(b"data") + + +@pytest.mark.parametrize("if_match", [None, '"etag"']) +async def test_write_conditional_request_conflict_raises_cas_conflict( + if_match: str | None, +) -> None: + storage, s3 = _make_storage() + s3.put_object.side_effect = _client_error("ConditionalRequestConflict") + + with pytest.raises(CASConflictError): + await storage.write(b"data", if_match=if_match) + + +async def test_write_other_client_error_is_not_cas_conflict(): + storage, s3 = _make_storage() + s3.put_object.side_effect = _client_error("AccessDenied") + + with pytest.raises(StorageError): + await storage.write(b"data") + + async def test_write_other_error_raises_storage_error(): storage, s3 = _make_storage() s3.put_object.side_effect = RuntimeError("network failure") @@ -216,3 +247,70 @@ def test_s3_error_code_empty_code(): exc = Exception() exc.response = {"Error": {"Code": ""}} # type: ignore[attr-defined] assert _s3_error_code(exc) == "" + + +# --------------------------------------------------------------------------- +# Concurrent first write (conditional-write-aware fake S3) +# --------------------------------------------------------------------------- + + +class _FakeS3: + """Single-object S3 double that honours IfMatch / IfNoneMatch.""" + + def __init__(self) -> None: + self.body: bytes | None = None + self.etag: str | None = None + self._n = 0 + + async def get_object(self, **kwargs: object) -> dict[str, object]: + snapshot, etag = self.body, self.etag + # Yield after snapshotting so concurrent callers both observe the + # same (missing) object before either writes. + await asyncio.sleep(0) + if snapshot is None: + raise _client_error("NoSuchKey") + body = AsyncMock() + body.read.return_value = snapshot + return {"Body": body, "ETag": etag} + + async def put_object(self, **kwargs: object) -> dict[str, object]: + if kwargs.get("IfNoneMatch") == "*" and self.body is not None: + raise _client_error("PreconditionFailed") + if "IfMatch" in kwargs and kwargs["IfMatch"] != self.etag: + raise _client_error("PreconditionFailed") + self._n += 1 + self.body = kwargs["Body"] # type: ignore[assignment] + self.etag = f'"{self._n}"' + return {"ETag": self.etag} + + +def _fake_s3_storage(fake: _FakeS3) -> S3Storage: + session = MagicMock() + session.client.side_effect = lambda *a, **k: _AsyncCM(fake) + return S3Storage(bucket="b", key="k", session=session) + + +async def test_racing_first_writes_second_gets_cas_conflict(): + fake = _FakeS3() + a, b = _fake_s3_storage(fake), _fake_s3_storage(fake) + + # Both initialisers observe "no object yet". + assert await a.read() == (b"", None) + assert await b.read() == (b"", None) + + await a.write(b"first") + with pytest.raises(CASConflictError): + await b.write(b"second") + assert fake.body == b"first" + + +async def test_racing_first_enqueues_both_survive(): + """Two DirectQueues bootstrapping the same key must not lose a job.""" + fake = _FakeS3() + q1 = DirectQueue(_fake_s3_storage(fake)) + q2 = DirectQueue(_fake_s3_storage(fake)) + + j1, j2 = await asyncio.gather(q1.enqueue("t", b"1"), q2.enqueue("t", b"2")) + + state = await q1.read_state() + assert {j.id for j in state.jobs} == {j1.id, j2.id}