polycratia

Why an append-only journal checks a whole batch before the first write

· 9 min read

An append-only journal has no undo. Once an entry is kept it stays readable forever, so a batch that dies halfway leaves half a movement sitting in the record with no legal way to take the rest out. Every reason to refuse a write has to be found before the store is asked to keep anything, and that constraint, not taste, is what shapes the write path in ledger-core.

The constraint#

In a mutable store you answer a partial failure by putting things back. A ledger gives that up on purpose: you fix a mistake by writing the entry that cancels the first one, and both stay readable afterwards. The mechanism that fixes mistakes is the same mechanism that makes deletion illegal.

So "write three entries, fail on the third" has no recovery at the journal level. There is no entry you can write that un-writes the first two, and a reversal of a half-applied batch is not the same record as a batch that never landed. That leaves one option: find every refusal first, then write once.

One write path#

Everything funnels through extend. append wraps a single entry in a one-entry tuple, and the constructor passes whatever it was seeded with through the same function:

python
def __init__(self, entries: Iterable[Entry] = (), *, storage: Storage | None = None) -> None:
    self._storage: Storage = storage if storage is not None else InMemoryStorage()
    self.extend(entries)

def append(self, entry: Entry) -> Entry:
    self.extend((entry,))
    return entry

This is not a stylistic preference. A journal that validates in two places will eventually validate differently in two places. A single-entry append is a batch of one, and a journal built from a list of entries is a batch too, including the rules about what an entry may correct.

Two passes, then one call#

python
def extend(self, entries: Iterable[Entry]) -> tuple[Entry, ...]:
    """Write a batch under one rule: all of it, or none of it."""
    batch = tuple(entries)
    incoming: dict[str, Entry] = {}
    for entry in batch:
        if self._storage.has_entry(entry.entry_id) or entry.entry_id in incoming:
            raise DuplicateEntry(f"entry {entry.entry_id} is already written")
        incoming[entry.entry_id] = entry
    for entry in batch:
        corrects = entry.corrects
        if (
            corrects is not None
            and not self._storage.has_entry(corrects)
            and corrects not in incoming
        ):
            raise UnknownEntry(
                f"entry {entry.entry_id} corrects {corrects}, which is not written"
            )
    self._storage.append_entries(batch)
    return batch

Three things are doing work here.

tuple(entries) comes first for a reason beyond convenience. The argument is an Iterable, and callers pass generators: a comprehension over a day of parsed transactions, say. You cannot validate a generator and then hand the same generator to the store. Materialising the batch once is what makes "checked, then written" describable at all.

The first pass asks two questions in one condition: is this id already in the store, and has it already shown up in this batch. The second half is the one that gets forgotten. A batch assembled from two sources (a retry queue and a backfill) can carry the same entry twice without either source being wrong, and a journal that only checked the store would keep both.

The second pass is about corrections, and it is the only part of extend that looks at a field other than the id. Entries have already checked themselves by this point: Entry.__post_init__ raises UnbalancedEntry when the postings do not sum to zero, requires at least two postings, and refuses an entry whose corrects is its own id. A one-sided movement never becomes an object, so the journal never has to think about one. What an entry cannot know on its own is whether the thing it corrects exists, and that is a fact about the record rather than about the entry.

A refusal from either pass leaves the store untouched, because the store has not been called yet:

python
from ledger_core.journal import DuplicateEntry, Journal
from ledger_core.testing import an_entry

journal = Journal()
journal.append(an_entry("e-1"))

try:
    journal.extend((an_entry("e-2", "5.00"), an_entry("e-1")))
except DuplicateEntry:
    pass

assert [entry.entry_id for entry in journal.entries] == ["e-1"]

e-2 was perfectly good and it is not in the journal. The batch is the unit, and that is what being the unit costs you.

The batch counts as written#

Look at what the second pass accepts. A correction is valid if its target is in the store or in incoming, and incoming was filled from the whole batch during the first pass, before any correction was examined.

So a movement and the entry that cancels it can land in the same call, in either order. The correction may sit first in the tuple and still pass, because the first pass has already seen the entry it points at.

That matters more than it looks. Reversals are built by Entry.reversal(), which reverses every posting and sets corrects to the original entry id, and the places that produce reversals rarely produce them one at a time:

  • an importer replaying a period in which a transfer and its reversal both happened, where the order is whatever the upstream file says;
  • a reconciliation pass that discovers a bad entry and composes its fix in the same unit of work;
  • a migration writing a historical movement and immediately cancelling it, so the record shows what happened rather than a tidied-up version of it.

If the correction check consulted only the store, each of those would need two round trips in a fixed order, and the journal would be briefly readable in a state where a wrong movement exists and its cancellation does not. Letting the batch vouch for itself removes the ordering requirement, and the window goes with it.

Note what is still refused: a correction pointing at an id nobody wrote, in this batch or ever. That check is cheap and it catches the realistic failure, which is a stale or mistyped id in a generated fix.

What the store never has to do#

The payoff of checking up front sits on the other side of the protocol. append_entries is described in the Storage contract as keeping a batch that has already been checked, in the order given, so a backend's write path is a write:

python
def append_entries(self, entries: Sequence[Entry]) -> None:
    for entry in entries:
        self._entries.append(entry)
        self._by_id[entry.entry_id] = entry

def entry(self, entry_id: str) -> Entry | None:
    return self._by_id.get(entry_id)

def has_entry(self, entry_id: str) -> bool:
    return entry_id in self._by_id

def entries_since(self, index: int) -> tuple[Entry, ...]:
    return tuple(self._entries[index:])

def entry_count(self) -> int:
    return len(self._entries)

That is the whole entry surface of the in-memory store. A database backend is the same handful of operations: an insert, two lookups, a slice from a position, a count. No backend reimplements the duplicate rule or the correction rule, which means no two backends can disagree about what a legal batch is. That disagreement is the failure mode you get the moment validation lives next to the storage engine instead of above it.

It also narrows what a conformance suite has to prove. StorageConformance checks the contract (entries come back in append order, an empty batch keeps nothing, an entry reads back by its id) and not the journal's rules. The rules are tested once, against the journal.

Where the guarantee actually ends#

The honest version of "all of it, or none of it" is narrower than it sounds. extend guarantees that a refusal it can find happens before the store is touched. It does not guarantee that append_entries is itself all-or-nothing. One call is the smallest unit the journal can ask for, and whether that call can partially apply is the backend's property. No amount of up-front checking fixes a store that appends two rows and then fails.

Which is why anything needing a wider promise takes it from the store explicitly. Idempotent posting is the clear case: reading whether a key is already settled and writing the batch under it have to be one step, or a crash in between loses the record and keeps the entries.

python
mark = fingerprint_of(batch)
with self._storage.atomic():
    known = self._storage.operation(key)
    if known is not None:
        if known.fingerprint != mark:
            raise OperationMismatch(
                f"operation {key} already wrote {', '.join(known.entry_ids)}; "
                f"the same key cannot carry different entries"
            )
        return self.entries(key)
    written = self._journal.extend(batch)
    self._storage.put_operation(Operation.of(key, written))
    return written

How wide atomic reaches is the store's business. The in-memory one keeps its records aside, puts them back when the block is left by an exception, and lets one writer through at a time; a backend holding rows in a database makes it the transaction it already has. The journal's job is to ensure that by the time a block like this reaches extend, the only thing left that can go wrong is the write.

What I would change#

extend calls has_entry once per entry, and twice over the batch in the worst case. Against a dict that is free. Against a database it is a round trip per entry, and a large import pays for every one of them. The fix is a bulk existence check on the protocol with the per-entry call kept as the default implementation, so a small backend stays small. I would add it the first time a backend's latency showed up in a profile, probably not before...

The error types I would leave alone. DuplicateEntry is a ValueError and UnknownEntry is a KeyError, so calling code can catch the specific class or the ordinary Python one it already handles; an importer that treats bad input as ValueError does not need to learn ledger vocabulary to behave correctly.

The shape is the part worth copying. Append-only removes repair as an option, which turns every validation question into a scheduling question: not what do I check, but what do I know before the first entry is kept. Answer that once, in one function, and the storage layer underneath gets to be boring.

react

$ new-project --brief

or email hey@polycratia.com