Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions docs/design/API_DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion news/+crashed-run-swept.breaking.rst
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions news/+native-basis.documentation.rst
Original file line number Diff line number Diff line change
@@ -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.
8 changes: 6 additions & 2 deletions src/calendaring/_async/conformance.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
8 changes: 6 additions & 2 deletions src/calendaring/_sync/conformance.py

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

56 changes: 56 additions & 0 deletions tests/_async/test_caldav_conformance.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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

Expand Down
21 changes: 21 additions & 0 deletions tests/_async/test_memory_conformance.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"):
Expand Down
56 changes: 56 additions & 0 deletions tests/_sync/test_caldav_conformance.py

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions tests/_sync/test_memory_conformance.py

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading