From 23637564c3adc6fca92f79dadf523e5c3c2e9ac3 Mon Sep 17 00:00:00 2001 From: Tobias Brox Date: Tue, 24 Nov 2026 15:01:56 +0100 Subject: [PATCH 1/2] docs: say where the remembered native basis lives MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit API_DESIGN §3.5 said a backend remembers the STATUS and PRIORITY it wrote next to native_status and native_priority and compares on save, but no field held that value. The section now puts it in a private _native_basis on the task, handed over as StoredObject.native_basis, says why it is not kept in the backend or recomputed from .native, and what a direct assignment to a native value means. This came up in the review of https://github.com/pycalendar/calendaring/pull/5. Prompt: [pick from the task list: "calendaring: say where the remembered native STATUS/PRIORITY lives (API_DESIGN §3.5)"] Assisted-By: Claude Opus 5.5 Reviewed-by: Tobias Brox --- docs/design/API_DESIGN.md | 26 ++++++++++++++++++++++++++ news/+native-basis.documentation.rst | 1 + 2 files changed, 27 insertions(+) create mode 100644 news/+native-basis.documentation.rst diff --git a/docs/design/API_DESIGN.md b/docs/design/API_DESIGN.md index d1f3950..837691b 100644 --- a/docs/design/API_DESIGN.md +++ b/docs/design/API_DESIGN.md @@ -820,6 +820,7 @@ class TaskStatus(StrEnum): # values are the iCalendar strings class Task(Item): # component is an icalendar.Todo native_status: str | None # see "Native passthrough"; not in the iCalendar data native_priority: str | None # likewise + _native_basis: tuple[str | None, str | None] # STATUS, PRIORITY the backend wrote with them; private planned_start: datetime | None # X-PYCAL-PLANNED-START (see "Properties with no standard home") planned_end: datetime | None # X-PYCAL-PLANNED-END # the time log: see "Time tracking" below, on every bound item @@ -1034,6 +1035,31 @@ wherever the backend maps `COMPLETED`. Comparing on save, rather than clearing the native value in a setter, also catches a change made through `item.icalendar` directly. +The remembered values live on the item, in the private +`_native_basis`: the `STATUS` and `PRIORITY` (as strings, `None` where +absent; `PRIORITY:0` counts as absent) that the backend wrote into the +component when it set `native_status` and `native_priority`. A +backend's primitives hand it over next to them, as +`StoredObject.native_basis`, and the generic layer sets all three +together. There is one basis per stored object: its occurrences share +it, as they share the native values. A task that was never read has +the basis `(None, None)`. + +Not kept in the backend, because an item is plain data +([A1](#1-layers-and-modes)) that outlives the collection object that +read it and may be saved through another one; and not recomputed from +`.native`, because `as_data()` drops that live object, and a backend +need not provide one at all +([§8](#8-the-escape-hatch)). + +A caller who assigns `native_status` or `native_priority` directly is +asking for that native value. Each half is compared on its own: the +backend uses the native value while `STATUS` (or `PRIORITY`) still +matches its half of the basis, and maps the property otherwise. So a +changed property wins, silently, over a native value assigned with it, +and on a new task a native value is used only where the property is +absent. + This answers [survey §4.4](TASK_MODEL_SURVEY.md#44-details-to-be-decided-later)'s question "plain string or typed object": a plain string. Legal transitions (RT, OpenProject) are reachable through `native` and are not part of the model. diff --git a/news/+native-basis.documentation.rst b/news/+native-basis.documentation.rst new file mode 100644 index 0000000..af35bc2 --- /dev/null +++ b/news/+native-basis.documentation.rst @@ -0,0 +1 @@ +The design document now says where a task keeps the ``STATUS`` and ``PRIORITY`` its backend wrote with ``native_status`` and ``native_priority``: in a private ``_native_basis``, which a save compares against. From c5dc3135f808e98dc440768747cee271033a2f2d Mon Sep 17 00:00:00 2001 From: Tobias Brox Date: Tue, 24 Nov 2026 16:55:49 +0100 Subject: [PATCH 2/2] test: retry the crash sweep's deletes on CalDAV The sweep in borrow() deleted a dead run's leftovers in one try, so a DELETE that robur dropped turned into a setup error for whatever test borrowed the collection. The deletes now go through a sweep() hook, which the CalDAV test module overrides to retry the way seed() retries writes; gone on a retry is taken for a lost answer to a DELETE that went through. Prompt: [pick from the task list: "calendaring: live conformance run on a server that cannot delete calendars; retry the sweep's deletes"] Assisted-By: Claude Opus 5.5 Reviewed-by: Tobias Brox --- news/+crashed-run-swept.breaking.rst | 2 +- src/calendaring/_async/conformance.py | 8 +++- src/calendaring/_sync/conformance.py | 8 +++- tests/_async/test_caldav_conformance.py | 56 +++++++++++++++++++++++++ tests/_async/test_memory_conformance.py | 21 ++++++++++ tests/_sync/test_caldav_conformance.py | 56 +++++++++++++++++++++++++ tests/_sync/test_memory_conformance.py | 21 ++++++++++ 7 files changed, 167 insertions(+), 5 deletions(-) diff --git a/news/+crashed-run-swept.breaking.rst b/news/+crashed-run-swept.breaking.rst index fd8957e..b4c46d9 100644 --- a/news/+crashed-run-swept.breaking.rst +++ b/news/+crashed-run-swept.breaking.rst @@ -1 +1 @@ -The conformance suite now cleans up after a run that was killed before it could: every UID it writes carries a mark with the time, and a later run deletes marked items older than ``stale_after`` (a day by default) from a collection it borrows, along with what earlier versions of the suite left there. A test in a subclass that writes to a borrowed collection must give its items a UID from ``calendaring.testing.fresh_uid()``, or the test fails. Backends that assign their own UIDs are not covered. +The conformance suite now cleans up after a run that was killed before it could: every UID it writes carries a mark with the time, and a later run deletes marked items older than ``stale_after`` (a day by default) from a collection it borrows, along with what earlier versions of the suite left there. A test in a subclass that writes to a borrowed collection must give its items a UID from ``calendaring.testing.fresh_uid()``, or the test fails. Backends that assign their own UIDs are not covered. A backend whose server drops requests can override ``sweep()`` to retry those deletes. diff --git a/src/calendaring/_async/conformance.py b/src/calendaring/_async/conformance.py index 40ece0f..1ea186a 100644 --- a/src/calendaring/_async/conformance.py +++ b/src/calendaring/_async/conformance.py @@ -436,8 +436,7 @@ async def borrow(self, collection: AsyncCollection) -> AsyncCollection: dead = {i.native_id for i in items if self.left_by_a_dead_run(i, cutoff)} for native_id in dead: assert native_id is not None - with contextlib.suppress(NotFoundError): # another run swept it first - await collection.delete(native_id) + await self.sweep(collection, native_id) if dead: items, broken = await readable(collection) before: set[str | None] = {i.native_id for i in items} | set(broken) @@ -468,6 +467,11 @@ async def seed(self, collection: AsyncCollection, items: Sequence[Item]) -> list """Store items the way a test needs them. A read-only backend overrides this to seed natively.""" return [await collection.add(item, loss=ALLOW) for item in items] + async def sweep(self, collection: AsyncCollection, native_id: str) -> None: + """Delete an item a dead run left in a borrowed collection; one already gone is fine. A flaky backend overrides this to retry.""" + with contextlib.suppress(NotFoundError): # another run swept it first + await collection.delete(native_id) + async def unseed(self, collection: AsyncCollection, item: AsyncItem) -> None: """Remove a seeded item. A read-only backend overrides this to remove it natively.""" await collection.delete(item) diff --git a/src/calendaring/_sync/conformance.py b/src/calendaring/_sync/conformance.py index ae5f1c3..91dde81 100644 --- a/src/calendaring/_sync/conformance.py +++ b/src/calendaring/_sync/conformance.py @@ -436,8 +436,7 @@ def borrow(self, collection: Collection) -> Collection: dead = {i.native_id for i in items if self.left_by_a_dead_run(i, cutoff)} for native_id in dead: assert native_id is not None - with contextlib.suppress(NotFoundError): # another run swept it first - collection.delete(native_id) + self.sweep(collection, native_id) if dead: items, broken = readable(collection) before: set[str | None] = {i.native_id for i in items} | set(broken) @@ -468,6 +467,11 @@ def seed(self, collection: Collection, items: Sequence[Item]) -> list[SyncItem]: """Store items the way a test needs them. A read-only backend overrides this to seed natively.""" return [collection.add(item, loss=ALLOW) for item in items] + def sweep(self, collection: Collection, native_id: str) -> None: + """Delete an item a dead run left in a borrowed collection; one already gone is fine. A flaky backend overrides this to retry.""" + with contextlib.suppress(NotFoundError): # another run swept it first + collection.delete(native_id) + def unseed(self, collection: Collection, item: SyncItem) -> None: """Remove a seeded item. A read-only backend overrides this to remove it natively.""" collection.delete(item) diff --git a/tests/_async/test_caldav_conformance.py b/tests/_async/test_caldav_conformance.py index d6af664..628e8be 100644 --- a/tests/_async/test_caldav_conformance.py +++ b/tests/_async/test_caldav_conformance.py @@ -75,6 +75,21 @@ async def seed(self, collection: AsyncCollection, items: Sequence[Item]) -> list raise return seeded + async def sweep(self, collection: AsyncCollection, native_id: str) -> None: + """Delete a dead run's leftover, again after a failed DELETE: robur drops requests as it does while seeding. + + Gone on a retry is taken for a lost answer to a DELETE that went through. + """ + for attempt in range(SEED_ATTEMPTS): + try: + await collection.delete(native_id) + return + except NotFoundError: # swept by another run, or by an earlier try whose answer was lost + return + except BackendError: + if attempt == SEED_ATTEMPTS - 1: + raise + @staticmethod async def _seeded(collection: AsyncCollection, item: Item, seeded: list[AsyncItem]) -> bool: """Whether a write whose answer was lost stored ``item``; if so it joins ``seeded``. A failed read says no.""" @@ -199,6 +214,47 @@ async def test_a_kept_calendar_is_reopened_from_its_url(caldav_server: Any, monk await suite.reopen(other, made) +class _FlakyDeletes: + """Answers ``delete`` as told: "ok", "deleted-then-lost" (gone, answer lost), "lost" (nothing deleted) or "refused" (a 500).""" + + def __init__(self, outcomes: list[str]) -> None: + self.outcomes = outcomes + self.present = True + self.deletes = 0 + + async def delete(self, native_id: str) -> None: + outcome = self.outcomes[self.deletes] if self.deletes < len(self.outcomes) else "ok" + self.deletes += 1 + if not self.present: + raise NotFoundError(native_id) + if outcome in ("ok", "deleted-then-lost"): + self.present = False + if outcome == "refused": + raise BackendError("DeleteError at '500 Internal Server Error'") + if outcome in ("lost", "deleted-then-lost"): + raise TransportError("read timed out") + + +@pytest.mark.parametrize( + ("outcomes", "deletes"), + [([], 1), (["lost"], 2), (["refused"], 2), (["deleted-then-lost"], 2), (["lost", "lost"], 3)], +) +async def test_the_sweep_gets_past_a_lost_answer(outcomes: list[str], deletes: int) -> None: + """A dropped DELETE while sweeping a dead run's leftovers is setup trouble, not a failure of the test.""" + collection = _FlakyDeletes(outcomes) + await CalDAVConformance().sweep(collection, "left-behind.ics") # type: ignore[arg-type] + assert not collection.present + assert collection.deletes == deletes + + +@pytest.mark.parametrize("outcome", ["lost", "refused"]) +async def test_the_sweep_gives_up_on_a_server_that_never_deletes(outcome: str) -> None: + collection = _FlakyDeletes([outcome] * 10) + with pytest.raises(BackendError): + await CalDAVConformance().sweep(collection, "left-behind.ics") # type: ignore[arg-type] + assert collection.deletes == SEED_ATTEMPTS + + def test_a_server_limiting_calendar_creation_keeps_its_calendars() -> None: from caldav.compatibility_hints import FeatureSet as Unannotated diff --git a/tests/_async/test_memory_conformance.py b/tests/_async/test_memory_conformance.py index 3a88f3b..c722b0e 100644 --- a/tests/_async/test_memory_conformance.py +++ b/tests/_async/test_memory_conformance.py @@ -447,6 +447,27 @@ async def test_a_crashed_runs_leftovers_are_swept(self) -> None: await suite.tidy_up(backend) assert len(backend.store.calendars["default"].objects) == 2 + async def test_the_sweep_goes_through_its_hook(self) -> None: + """A backend's override of sweep(), the CalDAV retry say, is what deletes the leftovers.""" + swept: list[str] = [] + + class Recording(AsyncConformance): + async def sweep(self, collection: AsyncCollection, native_id: str) -> None: + swept.append(native_id) + await super().sweep(collection, native_id) + + backend = sharing(MINIMAL) + crashed = Task.new( + summary="a crashed run's", uid=f"x-t{int(time_module.time()) - 2 * 86400}@conformance.invalid" + ) + backend.store.calendars["default"].put(crashed.to_ical()) + backend.store.calendars["default"].put(Task.new(summary="the user's").to_ical()) + suite = Recording() + suite._made, suite._borrowed = [], [] + collection = await suite.open_collection(backend) + assert len(swept) == 1 + assert [str(i.component["SUMMARY"]) for i in await collection.search()] == ["the user's"] + async def test_an_older_runs_unstamped_leftover_is_swept(self) -> None: backend = sharing(MINIMAL) for uid in ("corpus-task-0123456789ab@conformance.invalid", f"x-t{'9' * 30}@conformance.invalid"): diff --git a/tests/_sync/test_caldav_conformance.py b/tests/_sync/test_caldav_conformance.py index d716c05..cf506e3 100644 --- a/tests/_sync/test_caldav_conformance.py +++ b/tests/_sync/test_caldav_conformance.py @@ -75,6 +75,21 @@ def seed(self, collection: Collection, items: Sequence[Item]) -> list[SyncItem]: raise return seeded + def sweep(self, collection: Collection, native_id: str) -> None: + """Delete a dead run's leftover, again after a failed DELETE: robur drops requests as it does while seeding. + + Gone on a retry is taken for a lost answer to a DELETE that went through. + """ + for attempt in range(SEED_ATTEMPTS): + try: + collection.delete(native_id) + return + except NotFoundError: # swept by another run, or by an earlier try whose answer was lost + return + except BackendError: + if attempt == SEED_ATTEMPTS - 1: + raise + @staticmethod def _seeded(collection: Collection, item: Item, seeded: list[SyncItem]) -> bool: """Whether a write whose answer was lost stored ``item``; if so it joins ``seeded``. A failed read says no.""" @@ -199,6 +214,47 @@ def test_a_kept_calendar_is_reopened_from_its_url(caldav_server: Any, monkeypatc suite.reopen(other, made) +class _FlakyDeletes: + """Answers ``delete`` as told: "ok", "deleted-then-lost" (gone, answer lost), "lost" (nothing deleted) or "refused" (a 500).""" + + def __init__(self, outcomes: list[str]) -> None: + self.outcomes = outcomes + self.present = True + self.deletes = 0 + + def delete(self, native_id: str) -> None: + outcome = self.outcomes[self.deletes] if self.deletes < len(self.outcomes) else "ok" + self.deletes += 1 + if not self.present: + raise NotFoundError(native_id) + if outcome in ("ok", "deleted-then-lost"): + self.present = False + if outcome == "refused": + raise BackendError("DeleteError at '500 Internal Server Error'") + if outcome in ("lost", "deleted-then-lost"): + raise TransportError("read timed out") + + +@pytest.mark.parametrize( + ("outcomes", "deletes"), + [([], 1), (["lost"], 2), (["refused"], 2), (["deleted-then-lost"], 2), (["lost", "lost"], 3)], +) +def test_the_sweep_gets_past_a_lost_answer(outcomes: list[str], deletes: int) -> None: + """A dropped DELETE while sweeping a dead run's leftovers is setup trouble, not a failure of the test.""" + collection = _FlakyDeletes(outcomes) + CalDAVConformance().sweep(collection, "left-behind.ics") # type: ignore[arg-type] + assert not collection.present + assert collection.deletes == deletes + + +@pytest.mark.parametrize("outcome", ["lost", "refused"]) +def test_the_sweep_gives_up_on_a_server_that_never_deletes(outcome: str) -> None: + collection = _FlakyDeletes([outcome] * 10) + with pytest.raises(BackendError): + CalDAVConformance().sweep(collection, "left-behind.ics") # type: ignore[arg-type] + assert collection.deletes == SEED_ATTEMPTS + + def test_a_server_limiting_calendar_creation_keeps_its_calendars() -> None: from caldav.compatibility_hints import FeatureSet as Unannotated diff --git a/tests/_sync/test_memory_conformance.py b/tests/_sync/test_memory_conformance.py index d468990..5c703c2 100644 --- a/tests/_sync/test_memory_conformance.py +++ b/tests/_sync/test_memory_conformance.py @@ -447,6 +447,27 @@ def test_a_crashed_runs_leftovers_are_swept(self) -> None: suite.tidy_up(backend) assert len(backend.store.calendars["default"].objects) == 2 + def test_the_sweep_goes_through_its_hook(self) -> None: + """A backend's override of sweep(), the CalDAV retry say, is what deletes the leftovers.""" + swept: list[str] = [] + + class Recording(SyncConformance): + def sweep(self, collection: Collection, native_id: str) -> None: + swept.append(native_id) + super().sweep(collection, native_id) + + backend = sharing(MINIMAL) + crashed = Task.new( + summary="a crashed run's", uid=f"x-t{int(time_module.time()) - 2 * 86400}@conformance.invalid" + ) + backend.store.calendars["default"].put(crashed.to_ical()) + backend.store.calendars["default"].put(Task.new(summary="the user's").to_ical()) + suite = Recording() + suite._made, suite._borrowed = [], [] + collection = suite.open_collection(backend) + assert len(swept) == 1 + assert [str(i.component["SUMMARY"]) for i in collection.search()] == ["the user's"] + def test_an_older_runs_unstamped_leftover_is_swept(self) -> None: backend = sharing(MINIMAL) for uid in ("corpus-task-0123456789ab@conformance.invalid", f"x-t{'9' * 30}@conformance.invalid"):