Skip to content

Migrations, Pruning, and Observability

Saved data outlives the code that wrote it. This page covers changing what a panel saves, rows whose message stays out of reach, removing saved data, and watching the writes.

Changing a Panel's Arguments

A panel's row keeps the arguments its constructor got. When the constructor changes, the rows posted before still hold the old ones, so raise the class's kwargs_schema_version and register a migrator for the step:

from cascadeui import PersistentLayoutView, register_kwargs_migrator


class TicketDesk(PersistentLayoutView):
    kwargs_schema_version = 2  # 1 took target_channel_id=

    def __init__(self, *, channel_id, **kwargs):
        super().__init__(**kwargs)
        self.channel_id = channel_id


@register_kwargs_migrator("bot.cogs.tickets.TicketDesk", from_version=1)
def rename_channel(kwargs):
    kwargs["channel_id"] = kwargs.pop("target_channel_id")
    return kwargs

At the next start, a restore compares each row's version with the class's:

The row What the restore does
Saved at the class's version Builds the panel from the saved arguments
Saved at an older version, with a migrator for each step Runs the migrators in order, then builds the panel
Saved at an older version, with a step that has no migrator Logs a WARNING naming the class, the step, and the key, and keeps the row (skipped)
A migrator raises, or returns anything but a dict Logs at ERROR and keeps the row (failed)
Saved at a later version, after the code was rolled back Builds the panel from the saved arguments as they are

The restore leaves the row as it was saved, so the migrator runs at every start until the panel is posted again. Keep it registered while rows at the old version remain: without it, the next start skips them with a WARNING.

Diagram: the desk:22 row of the page's TicketDesk across the change to its arguments. Posted while version 1 took target_channel_id=, the row is saved at version 1 with {"target_channel_id": 900}. At the next start, with version 2 and no migrator registered, the panel is not restored: the row is skipped and kept, and a WARNING names the missing step, bot.cogs.tickets.TicketDesk v1 -> v2. Once rename_channel is registered, the next start turns {"target_channel_id": 900} into {"channel_id": 900} and TicketDesk(channel_id=900) is back on message 7001. The row on disk is unchanged, so rename_channel runs again at every start. Posted again, the row is saved at version 2 with {"channel_id": 900}, and the next start builds the panel from it with no migrator call.

The first argument names the class as its rows do: f"{module}.{qualname}" when the panel was posted, or the class's session_class_key. A migrator registered under any other name never runs, so after moving a class, pin its old name and key the migrator by it.

Versions start at 1: a kwargs_schema_version that is not an int raises TypeError when the class is defined, and one below 1 raises ValueError. A migrator may be a plain def or an async def. One that cannot be called with (kwargs) raises TypeError when it is registered, and a second migrator for the same class and step raises ValueError.

Registering Migrators as Data

When migrators are built as data rather than written as functions, pass them to the middleware:

from cascadeui import PersistenceMiddleware, setup_middleware

await setup_middleware(
    PersistenceMiddleware(
        bot=self,
        migrators={"kwargs": {("bot.cogs.tickets.TicketDesk", 1): rename_channel}},
    ),
)

Each (class name, from_version) key is checked as the decorator checks it when the middleware is built, and each migrator when setup_middleware() registers it. A step that already has another migrator keeps it, and the one passed here is ignored with a WARNING. The same migrator passed again is skipped quietly, so building the middleware again in a later setup_hook never raises.

The Library's Own Tables

The library migrates its own two tables at each start, before reading them (What setup_middleware() Runs). A new database starts at the current version, an older one is brought up to it, and a table holding rows with no recorded version counts as version 1. A step that fails stops the start with PersistenceSchemaError naming the table and the step. The stored version is unchanged, so the next start tries again.

On PostgreSQL a step changes the table, which takes its owner (Database Privileges). A database a later release migrated stops the start with PersistenceSchemaError, so an older release never reads data it does not understand. On a backend of your own, Upgrades says what it must declare for a step to run.

Every step is the library's, so register_migrator() refuses any step passed to it with ValueError, and so does a "schema" entry in migrators=. Your own tables are migrated by your own code (Custom Backends and Raw SQL).

Rows That Stay Unreachable

A restore keeps a row whose message it cannot fetch for any reason but a 404 (unreachable in What the Restore Reports): a 403 at a start can be a permission change undone an hour later, and deleting the row would lose a live panel. The cost is a row for a channel the bot will never see again, fetched at every start for good.

Diagram: the desk:22 row's life when its channel stops answering. At the first start the fetch is refused with 403: the row is kept, listed unreachable, and stamped with the time of that failure. At the next start the fetch is refused again, and the stamp keeps the first failure's time. A month later, prune_unreachable(older_than_days=30) takes a second look, and the row ends one of three ways. The message answers and the panel is put back on it, the stamp cleared (recovered). The channel answers 404 and the row is deleted whatever its age (pruned and gone). Or the channel still answers 403 and the row, stamped more than 30 days ago, is deleted (pruned).

The first failed fetch stamps the row with the time (first_unreachable_at), and a later failure leaves the stamp alone, so its age counts from the first one. A start whose fetch succeeds clears it, even when the panel's constructor then raises (failed): the message was there. unreachable_since maps each stamped key to its stamp.

prune_unreachable() takes a second look before it deletes anything:

from cascadeui import get_store

result = await get_store().persistence_manager.prune_unreachable(older_than_days=30)
# {"pruned": [...], "gone": [...], "recovered": [...], "kept": [...], "messages": {...}}
The second look finds The row Listed in
The message Kept, and the panel put back as a restore puts it back, so it answers clicks without a restart. The stamp clears recovered
A 404 for the channel or the message Deleted, whatever its age pruned and gone
A 403, or a channel that holds no messages Deleted when the stamp is older than the cutoff, kept otherwise pruned or kept
No answer, a rate limit, or a server error Kept for the next sweep kept
The key held by a live panel in this process Kept without a fetch kept

A panel whose message answers but whose restore fails is stamped again with the time of the check and listed kept, so the next sweep tries it again. The deletions dispatch REGISTRY_PRUNED with source="prune_unreachable": reason="gone" for the 404s and reason="unreachable" for the rows that aged out. messages maps each pruned key to the message and channel its row named, in the action and in the result.

older_than_days=0 is allowed, since the second look is what makes a deletion safe, and a fraction of a day works too. A cutoff that is not an int or a float, a bool included, raises TypeError, a negative or non-finite one ValueError, and a call on a middleware built without bot= raises RuntimeError. /cascadeui unreachable lists the stamped rows with their ages and, given prune_older_than_days, runs the same prune from Discord.

Sweeping Every Day

await setup_middleware(PersistenceMiddleware(bot=self, prune_unreachable_after_days=30))

The first sweep runs once the gateway is ready, after every reattach() in setup_hook has finished, so a fetch that fails with the gateway up points at the channel rather than the host. Then it runs once a day until persistence closes. A sweep and a restore never run at the same time. The setting is off by default and needs bot=.

It takes days as prune_unreachable() does, a fraction such as 1.5 included, but at least 1: less raises ValueError. The first sweep comes minutes after a start, so a shorter cutoff would delete a row on two failed fetches made close together. For a shorter cutoff, call prune_unreachable() yourself. A bot split into processes by shard sweeps each process's own shards, and processes running the same shards each sweep them.

A REGISTRY_PRUNED hook runs inside the sweep or restore that dispatched it, so calling prune_unreachable() or reattach() there raises RuntimeError. Start the call on a task of its own, and do not await that task from the hook: the two would wait on each other for good, with a WARNING after a minute.

Cleaning Up Your Own Records

A bot that keeps its own record of a panel, such as a ticket row naming the desk's message, is left holding it when the panel's row goes. A REGISTRY_PRUNED hook hears every deletion: a restore's, a sweep's, and prune_registry()'s:

async def forget_desks(action, state):
    for key, where in action["payload"]["messages"].items():
        message_id = where["message_id"]
        await tickets.forget_desk(key, message_id=None if message_id is None else int(message_id))  # (1)!


get_store().on("REGISTRY_PRUNED", forget_desks)
  1. Your own lookup: with a message id it forgets the record only while it names that message, and with None it forgets the key's record whatever it names.

Delete a record only while it names that message: a key posted again keeps its new message, and two prunes racing on one row can both report it. The ids in messages are strings. A message_id of None means the deleted row named no message. The library always writes one (both SQL backends require it), so only a row other code wrote to the in-memory or a custom backend lacks it, and its delete matched the key alone: the key's row is gone whatever message your record names, so the record goes too.

A restore runs inside setup_middleware(), so a hook registered in a cog's setup() hears its deletions, and one registered in on_ready does not: the action is sent once. Code that starts later reads total_reattach_summary["removed"] and reattach_removed_messages (What the Restore Reports). Take a restore's deletions from one of the two, not both: the action's source is "reattach" for them. Clean up only from removed, never from unreachable, whose panels may still be on screen.

Pruning

Call Removes Dispatches
prune_application(slot="search") One slot, whatever its age: its row, a write waiting for it, and its value in the store APPLICATION_SLOTS_PRUNED
prune_application(older_than_days=7) The slots whose expiry passed more than 7 days ago (0: every expired slot), from the database and the store APPLICATION_SLOTS_PRUNED
prune_registry(persistence_keys=["desk:22"]) Those panels' rows, whatever holds the key (Closing a Panel for Good). With no keys, every row REGISTRY_PRUNED, reason="explicit" ("clear_all" with no keys)
prune_unreachable(older_than_days=30) The rows out of reach past the cutoff, after a second look (above) REGISTRY_PRUNED

All four are on get_store().persistence_manager. The first three return the number of rows deleted, and each dispatches only when something was removed. prune_application() takes one of slot= and older_than_days=: passing both raises ValueError, and passing neither returns 0. Its older_than_days is checked as prune_unreachable()'s is (above), before anything is deleted.

A prune or an expiry leaves undo history alone. Undoing a step taken before the slot went brings back what that step changed (for a dict slot, only the keys it touched) and saves the slot again.

Automatic TTL Sweeping

A slot whose SlotPolicy has ttl_days expires that many days after its last change (Expiry).

Expired rows go at two moments. A start deletes them before reading the slots, so none is loaded. While the bot runs, a sweep deletes them once a day, the first a day after the start, removes the same slots from the store, and dispatches APPLICATION_SLOTS_PRUNED naming them. The sweep starts with the middleware when a saved slot has ttl_days, or when register_slot_policy() adds one later.

The expiry is a time stored on the row. Saving the same value again keeps it, a change moves it, and a restart changes neither.

Observability

manager = get_store().persistence_manager


def on_flush(namespace, upsert_count, delete_count):
    metrics.count(f"persistence.{namespace}.writes", upsert_count + delete_count)


def on_error(namespace, exc):
    alerts.fire(f"persistence.{namespace}", repr(exc))


manager.register_hook("on_flush", on_flush)
manager.register_hook("on_error", on_error)

namespace is "registry" or "application". These are the only two hook names: any other raises ValueError, and a callback that cannot take the arguments shown raises TypeError. Hooks run under their namespace's write lock, so a slow hook holds back the next write, and a manager call that waits for that lock (flush_all(), close(), or from an application hook rehydrate() and prune_application(slot=)) raises RuntimeError from a hook rather than waiting on itself. A hook that needs one starts it with asyncio.create_task() and does not await the task, which runs once the hook returns.

Awaited, that task waits on the hook just as the call would, and after 30 seconds a WARNING names the hook and the call. A hook may close the bot: bot.close() returns there without waiting, and persistence closes once the hook returns.

A write that fails keeps its rows queued and tries again:

Failures in a row What happens
1 to 4 An ERROR line with the count, on_error, and another try after 1, 2, 4, then 8 seconds
5 An ERROR line, on_error, and a CRITICAL line. No more tries until the next action, which writes the waiting rows with its own
A success on_flush, and the count starts again

A write still running after 30 seconds is cancelled and counts as a failure. A close tries one last write, and rows still waiting when the process ends after that are lost.