Skip to content
catincloud-labsPublic

About

A bounded claim on a finite shared pool, granted for a period and refused rather than overdrawn.

Topics

Resources

Security policy

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

ration

A ration is a bounded claim on a finite shared pool, granted for a period, and refused rather than overdrawn.

A coordination substrate, and the lease, pool, addressing and publication services built on it, with the conformance suite that decides whether a store can carry them.

What is here: the contract in src/ration/contract.py; a suite that discriminates between a store that keeps it and stores that are wrong on purpose, one per property; a Postgres backend that passes every property, and a naive Postgres one that is rejected; src/ration/lease.py, which grants one holder per key; src/ration/pool.py, which grants a bounded number of holders over a set of keys; src/ration/addressing.py, which answers where a role is by reading the lease that says who holds it; src/ration/publish.py, which advances a versioned pointer to published state under the same compare-and-set; and src/ration/frame.py, the checked carrier beneath claims of authority and new payloads between nodes, with its own suite of frames built wrong on purpose. Treat every statement below as intent unless it points at a passing test.

Three of the services, built after the suite, each found something every green run before it had agreed with: the lease, the pool and the publication pointer. The lease found a defect in the contract's own remedy for an ambiguous write. The pool found that a retrying holder takes a second slot unless the scan looks for its own grant first, and that the obvious test for it cannot fail, which only a deliberately wrong implementation revealed. See What the first consumer found and src/ration/pool.py.

What this offers, and what it does not

The mechanism, and the suite that judges it. Nothing here is a guarantee, and nothing is supported beyond what SECURITY.md says. The suite is the contract: where this README and the suite disagree, the suite is right and this file is the defect.

The suite is evidence about ration's own code and about the stores it was run against, and about nothing else. A store's guarantee is shown by running the suite against that store; if you put ration in front of a store of your own, that run is yours to make. A store's own vendor test suite is evidence about the vendor, not about your deployment, and the same is true of this one. Running the suite against your own store, at the end of this file, is how to make that run.

Postgres passing is not Postgres being chosen. The contract makes the store a conformance result, and a conformance result is evidence, not a decision. Nothing in pyproject.toml's runtime dependencies names a driver, and in this repository ration.postgres is imported only by the suite. Which store a deployment uses is that deployment's decision.

What this is

Two things, in one repository because they own the same state:

  1. The coordination substrate: an atomic compare-and-set against a monotonically increasing version, on a single key, plus the backends that implement it and the suite that decides whether a backend qualifies.
  2. The services built on exactly that primitive: lease.py, a bounded, expiring claim on one key; pool.py, a bounded number of simultaneous claims over a set of them; addressing.py, which answers where a role is by reading the lease that says who holds it; and publish.py, which advances a generation pointer to published state. They are one thing rather than four: a pool is N keys, each one of these leases; an address is a lease's payload; and a publication is the same key discipline with the expiry refused. None of them adds an operation of its own.

And a third that owns no state at all: frame.py, the carrier a claim of authority or a new payload rides in between nodes, checked before the payload is looked at. It is here because it leans on the contract exactly once, for the epoch a restarted sender needs, and a lease version already is one. See The frame, and the suite of frames built wrong on purpose.

The repository is decomposed by state ownership: the substrate and the services share it because they own the same state. The contract they all rest on is stated once, in src/ration/contract.py, and decided by src/ration/conformance/:

Property What it fixes
The operation compare_and_set on a single key applies only at the expected version, the comparison and the write are one step, and a conflict is reported without writing
1 The version is monotonic per key and never reused, not even after the key is deleted
2 Expiry is evaluated by the store, when it is asked; a TTL is a duration, never a caller's deadline
3 A caller that cannot reach the store has acquired nothing: unreachable means refuse
4 A write whose answer was lost is resolvable by reading, because the caller's token is in the store

Addressing a role, and why it is not a name record

Services find each other by role rather than by hostname. ration.addressing turns a role into an endpoint by reading the lease on that role: the holder's endpoint is stored as the lease payload, so taking a role and publishing where it lives are a single write, and the module keeps no state beside the lease.

announce(store, "producer", "node-a.example:8080", holder="node-a", ttl=30.0)
resolve(store, "producer")
# Address(role='producer', endpoint='node-a.example:8080',
#         holder='node-a', version=7)

version in that answer is the lease version it was read at. A callee that has already seen a later one can turn away a caller carrying an earlier one, which a DNS record, having no generation at all, cannot offer. Why the address is not kept in a name service instead, and what reading it from the store costs, is argued in the module docstring of ration.addressing: in short, a lookup now needs the store to be reachable, so a partition that already stopped a peer taking leases also stops it finding roles.

announce insists on an expiry even though the lease layer accepts ttl=None, and its docstring says why. resolve goes to the store on every call and keeps nothing between calls.

The expiry tests carry a control built to fail them. Most of tests/test_addressing.py checks that an address stops resolving, and a test of an absence can pass while looking at nothing. So the same file runs a resolver that caches on purpose and requires it to keep answering after a role's lease has lapsed; were it ever to stop, the other tests would be timing the clock rather than reading the store.

Publishing a generation pointer, and why it is not a lease

When a producer publishes something consumers act on, a reader has to be able to say whether what it holds is the latest. ration.publish keeps one key per topic, holding the publisher's token and a reference to the artefact, and the topic's generation is that key's store version: the same counter Address.version reports for a role.

made = publish(store, "config", "sha256:9f2c...", "producer", generation=UNPUBLISHED)
current(store, "config")
# Publication(topic='config', publisher='producer',
#             generation=1, artefact='sha256:9f2c...')

Only the pointer is coordinated. An artefact named by its content cannot change once written, so there is nothing about it to lock.

It differs from a lease in two ways, and both are refusals. publish has no TTL parameter at all, where announce demands one: a role describes a running process that can vanish, a publication describes content, and a pointer that lapsed would look exactly like a topic nobody had published. And nothing retracts a publication; a newer one replaces it. Since nothing here deletes, the release edge lease.py records, where an applied delete and a key someone else took read alike, never comes up. The test for non-expiry checks its own clock first: an address leased in the same store has to lapse over the same advance, so a publication still standing afterwards shows a decision and not a clock that never moved.

Building it found that recovering an ambiguous advance takes two checks, each settling a case the other cannot. Every advance after the first rewrites a key that already carries this publisher's token, usually with a new artefact, which no lease does. When two writers share one publisher identity, as two replicas do, or a retry and its original, the contract's verdict alone can credit the lost write with the one that landed, and only comparing the stored artefact tells them apart. The other way round, an ambiguous republish of the artefact already in place leaves token and artefact both matching, and only the version that did not move shows the write never landed, so judging by the read-back alone gets it wrong. tests/test_publish.py pins both cases, the module docstring of ration.publish walks through them, and the contract did not change: everything needed was already stored.

Readers poll. The contract has no watch, so noticing a new generation means reading again and comparing. A stale pointer can be detected, never announced, and the same docstring says why no cache is added to hide the polling.

Where it stops: publishing an artefact together with its index would need two keys to change atomically, which the contract does not offer, so that would be a change to the contract rather than to this module.

The frame, and the suite of frames built wrong on purpose

ration.frame is the envelope one node wraps around a message to another when that message asserts authority, such as a fencing claim, a vote or a command, and around every new payload one node sends another. It keeps no state, and it knows nothing of routes, transports or consumers: its whole job is to be checked before the payload inside is looked at. The module's docstring (help(ration.frame)) is where each choice below is argued, with the header's layout and the order its checks run in; this section is the outline.

  • What is left out, deliberately. A record in the store already has an order, property 1's version, so framing it would order one record twice. Telemetry from an existing shipper claims nothing, and the frame's strict sequence would turn one lost batch into a run of refusals.
  • The header is eighteen bytes, big-endian: the frame's own version, the payload kind, a 64-bit sequence per sender, the length of the body, and a CRC-32 that covers the header too, not only the body. What the body means is not the module's business.
  • One ceiling for every kind: 1 MiB of body, 1,048,576 bytes. A header that declares more is refused as oversized, the tenth control, without reading on, and encode will not build a frame that large.
  • A text form, for a route whose request has no HTTP body: the same v1 frame, written as unpadded base64url into a request header, with the same checks run on the bytes it decodes to. The read is strict to the point of canonical, so each frame has one text. A string past 1,398,126 characters, the largest frame's text, is oversized by its length; any other string that is not a frame's one text is malformed-text, the ninth control. The standard library's base64 decoders, its strict settings included, each accept some text this read refuses, so its default read and its strict base64url setting are both registered as violators.
  • The sequence puts an epoch in its high word and a count in its low one. A receiver takes the next count, or count zero of a newer epoch. A lease version serves as the epoch, so a sender that restarts and re-announces its role needs nothing saved. The ledger moves only when a frame is accepted: resending a refused frame succeeds, and resending an accepted one is caught as a duplicate.
  • What it costs, stated. An empty ledger trusts its first frame, so a replay to a receiver starting from a fresh ledger gets through. The header names no sender. The registry of kinds is closed, at five codes.

The suite is what checked has to cost. For each check there is a reader that leaves exactly that check out, shaped like the shortcut someone would take, and the suite must reject it while the reference reader passes:

Frame property What it fixes Hostile cases The codec that must fail it
1 The length in the header matches the bytes that arrived, and stays under the ceiling a header cut short; a body cut short; a length that claims more, or less, than arrived; a body at the ceiling (taken) and one byte over it; a lone header that declares too much; an honest header with more bytes behind it than the largest frame holds unchecked-length, which believes the transport; ignores-trailing, which keeps what the length names and drops the remainder; no-ceiling, whose only limit is what four bytes can count
2 Any single flipped bit is caught as corruption one bit changed in the body, the sequence, the epoch or the kind byte unchecked-crc, which never checks the CRC it carries; body-only-crc, whose CRC leaves the header out
3 An unknown version is refused under that name, before any v1 layout is assumed a version above the reader's, the same with the CRC moved, a lone header of a later version whose length slot exceeds v1's ceiling, version zero unchecked-version; crc-before-version, every check present in the wrong order
4 A kind missing from the registry is refused a kind the registry lacks, kind zero unchecked-kind
5 A sender's next frame is the next count, or count zero of a newer epoch a repeat, a skip, an earlier count, a clean restart, an old epoch replayed, a new epoch not at zero, resending a refused frame unchecked-sequence; counter-only, a 32-bit count that rejects an honest restart; sequences-before-checking, the right rule at the wrong moment
6 A header string is read only when it is a frame's one canonical text characters outside the alphabet, whitespace, non-ASCII, = padding, + and /, a length one over a multiple of four, every variant spelling of a frame through its unused bits; a string one over the longest text whose last character is invalid, which must be oversized; a clean text of damaged bytes, which the frame must refuse lenient-text (the library's default read); library-strict (its strict base64url flag); skips-text-decode (no decode at all); accepts-non-canonical (no round trip); drops-dangling-character (Node's habit); collapses-layers (every refusal named as text); walks-before-bounding (length checked last)

Frame property 1 to 6 are these rows, in this order, and each module in src/ration/conformance/test_frame_*.py cites its row by that number. The reader's own checks are a separate, longer list, numbered in the module docstring, which says how the two line up.

One hostile case, a character outside ASCII, has no reader that fails it: every reader here is built on a decoder that raises there. The text property's module docstring says why no normalising reader is registered.

The machinery is the store suite's: one marker, one strict xfail, one set of bookkeeping assertions in tests/test_the_suite_discriminates.py, run over both registries. A run reports one xfailed line per codec per property it drops, so one per class in the violators module (grep -c '^class .*(FrameCodec)' src/ration/conformance/frame_violators.py); the run is the count, not this sentence.

What building it found. On its first run sequences-before-checking, written to break the sequence property, also broke length, integrity, version and kind. Each property test ends a refusal by offering the healthy frame again, and a reader that spends a sequence on a refused frame turns down that healthy frame every time. A violator that every test rejects says nothing about which check rejected it. The repair, in the codec registry: every property but the sequence's decodes against an empty ledger, and the sequence property names a sender for each decode. On the same run unchecked-crc failed the sequence property, because the frame that test refused was refused by its CRC; it is now a truncated frame, which every reader refuses whatever check it is missing. It is the store suite's conflict-writes lesson again, from the other side: the property is the unit, and its test has to hold every other property still.

The text property taught it a third time. Its arm for bad bytes under good text expected crc-mismatch, so the two CRC violators failed a text property for a CRC defect. The arm now asks only that the refusal be the frame's rather than the text's, and the reference reader's exact control is pinned in tests/test_frame.py. A second run found body-only-crc passing the standard-alphabet arm vacuously: the frame's one - sat in the CRC's characters, which that reader writes differently, and the arm's own guard reported it. The epoch was then chosen to put a _ in the sequence, where every reader writes the same bytes.

The kinds. Five codes: a consumer's fingerprint envelope, named as the envelope names itself; one for each of three body-carrying routes of a consumer's service; and role-claim, a body holding only the fencing claim a sender presents, which is what a body-less route sends as text. A code is on the wire and never changes meaning. A new kind is registered here before anyone sends it, since an unused code harms nothing while a decoder keyed on an unregistered one sees every frame refused; the comments beside KINDS in src/ration/frame.py give the full reasoning, including why role-claim is one code rather than one per route.

The name

A ration is a bounded portion of a finite pool, issued for a period. The word already carries the property the system needs most: rationing over-refuses rather than overdraws. The error direction is fail-closed, and here it is in the name rather than in a comment.

The first piece of work, and why it is not the service

The conformance suite comes before any backend, and before the lease service. The contract's central claim is unproven by construction: that a backend can be held to the contract, and that a suite can reject one.

So the suite's job is not to validate a backend. It is to discriminate between backends, and the design follows from that: a deliberately violating implementation per property, each breaking as little as it can:

Property The implementation that must fail it
Compare-and-set applies only at the expected version create-always - absence is not a version, so creation is an upsert
...and a conflict does not write conflict-writes - reports the conflict honestly, writes anyway
...and a conflict carries a version the key has held echoes-expected - hands the caller's expected version back, which the key may never have held
The comparison and the write are one step naive - read-then-write, exactly what the operation must not be
Version monotonic, never reused, not even after deletion recycling - drops the key's counter when the value goes
...and per key, not per store global-counter - monotonic, never reused, and a statement about unrelated traffic
Expiry evaluated by the store client-expiry - asks the caller what time it is, so skew is a lease held twice
...when it is asked, not when it last looked stale-clock - the store's own clock, fetched and then acted on later
Unreachable means refuse fail-open - a layer in front of a correct store that treats silence as "nothing there"
An ambiguous write is resolvable by reading token-dropping - keeps the payload, substitutes the token
...and all of the above, in a store that is not a fake postgres-naive - SELECT then UPDATE, exactly as the operation reads in English

If a violating implementation passes, that property is not being tested. The suite states that as a mechanism rather than a hope: a violator is marked xfail(strict=True) against its own property, so a violator that passes is a failing run. Same standard as the guards under scripts/, each of which runs its own self-test before it runs in CI: proof it can fire and proof it can go quiet.

Two of those rows are one implementation short of the ideal, and it is worth knowing which. conflict-writes breaks atomicity as well as the reply, and is registered for both; ConflictWritesStore's docstring in src/ration/conformance/violators.py says why no narrower violator exists.

The version property is still short its most likely violator. Restoring a store from a backup can replay or invalidate lease versions, so a restore is not an ordinary database restore. Both violators above are one process misbehaving; reuse-after-restore is an ordinary recovery, run by someone who believes they are restoring a database. It is harder to reach, a lifecycle event between store instances rather than a defect inside one, so no in-process implementation expresses it, and the suite does not cover it. Stated here so the gap is a known absence rather than a discovery made during a recovery.

A claim the suite did not cover was false for as long as nobody looked. Conflict and the Postgres compare_and_set both once said that a conflict carries the version the key had moved to. Under concurrency it does not: PostgresStore hands back the version the losing caller started from, both for updaters and for creators racing from absence. Conflict's docstring in src/ration/contract.py gives the two cases and why the server behaves so; here the part worth adding is that only the UPDATE half of the statement gets EvalPlanQual.

Not a contract defect. What the contract asks of a conflict is stated on Conflict, and both demands hold. src/ration/conformance/test_compare_and_set.py decides both, accepting any version the key has held, and echoes-expected is the store it rejects for reporting one the key never held. The acceptance has a store of its own. previous-version (src/ration/conformance/permitted.py) is registered with no violations; its docstring says what it answers and why a store like it exists. To watch it, replace the assertion after the stale-expectation refusal with assert refused == Conflict(created.version) and run pytest -rA src/ration/conformance/test_compare_and_set.py. An exact version would take either another round trip or an upsert that writes in order to read, which is precisely what conflict-writes exists to fail; Conflict's docstring prices both. So the claims were corrected and the behaviour pinned by tests/test_postgres_conflict_version.py, deterministically, with a held row lock rather than a race. A caller needing the current version must read.

The lesson is about the suite, not the store. Two docstrings agreed with each other and disagreed with the server, and every test passed throughout, because nothing asserted in that area at all. A property the suite does not decide is a property the prose is free to be wrong about, and prose is what a reader trusts.

The hard part is concurrency. A lost update only appears under concurrent access, and a concurrency test that has never been run against an implementation known to lose updates can run green while not looking. So the instrument here is calibrated against a known-bad implementation before it is trusted. The calibration is what turned "the hammer passes" from a result into a question: at the interpreter's default switch interval the probe ran green against naive, the one implementation that must never pass, at the rate recorded under The first calibration below. A suite that had merely run it would have shipped that green as evidence.

Threads or a deterministic interleaving? Both, doing different jobs, and the module docstring of src/ration/conformance/test_atomicity.py is where each job, and the order the two checks run in, is argued. In brief: the interleaving is the gate, deterministic because its seam holds no lock, and it proves the interleaving it arranged took place. Two properties need it, the second being stale-clock: a store that reads its own clock and then judges expiry somewhere else defeats clock injection entirely, because the reading it used was never the caller's. Threads are a probe, not a gate: they reach non-atomicity inside a real store that no client-side stepper can, they can show that a race happened but not that it landed where a violator is weak, and the false-pass rate they carry is stated by the suite, not implied.

The first calibration is the finding worth keeping. On the interpreter's default switch interval, the hammer never once caught the naive backend: it ran green against the implementation that must never pass. The window between a naive read and its write is about a microsecond and the interpreter was switching every five milliseconds, so the probe was not unlucky; it was not looking. Forcing preemption to a microsecond, the same counts caught it every run. The thread count, the iteration count and both rates live in src/ration/conformance/test_atomicity.py, beside the probe they describe, and are deliberately not repeated here. That rate is a measurement, not a guarantee: no false pass was observed, which is not the same as none being possible, and it is precisely why the property does not rest on it. The naive backend stays in the hammer run: if the hammer ever passes it, the hammer is measuring nothing and fails on that basis.

Neither of these is written into the contract as a requirement on future backends. A seam invented before any backend exists would be a contract clause with no caller, and it does not need to be a clause, because AGENTS.md already covers the case: a backend that needs a special case to pass is a finding about the backend or the contract, not a fixture to be written.

Every service is one compare-and-set

  • The lease (ration.lease): acquire, renew and release are one compare-and-set apiece, and Store gained no method for them. What a contract's first real consumer is missing is the test of the contract, and here it was missing nothing: the refusals held, and the only price was a second read when an answer is lost.
  • The pool (ration.pool), the thing the name promises: N separate leases, one key each, with no renew or release of its own. Why the contract forces that shape is pool.py's module docstring.
  • The generation pointer (ration.publish): published state with a version, kept on one key by the same compare-and-set a lease uses.
  • The frame adds no key and no operation, and leans on the contract exactly once, for the epoch a restarted sender needs.

What the real backend cost, and what it found

Two things came out of running the suite against something that is not a fake, and both were about the suite rather than about Postgres:

  • A fake clock is not a clock, and an in-process seam does not cross a socket. The harness had been written when only fakes existed. Time is now passed by advance_store_time(), moving a fake clock or actually waiting, and the deterministic stepper skips where a store's atomic step is one SQL statement. That skip removes an instrument, never a verdict: postgres-naive has no seam either and is still expected to fail, on the threaded probe.
  • A store that passed every property still could not survive being asked. The first backend opened a connection per operation. The threaded probe put about 1,600 connections through it, and the next run failed on Address already in use; PostgresStore's docstring gives the mechanism and why reuse is now required. Nothing in the contract catches that; there is no property about exhausting the machine. It was found by running the real thing under real load, which is the whole argument for deciding a backend by conformance result rather than by comparison. PostgresStore reuses one connection per thread.

What a second real backend found, and why it does not qualify

duckdb is registered as a case alongside postgres, with an empty violates set. It passes every conformance test. That is the result, and on its own it would qualify the backend.

It cannot be a coordination store for more than one process, and the suite is structurally unable to say so. DuckDB is embedded: the database is a file and one process owns it. A second process cannot open it. That is measured from a real interpreter under spawn and asserted, not described, in tests/test_duckdb_single_process.py, with a control proving the same child succeeds once the holder lets go. A coordination store exists so that other processes, and other hosts, can reach it, and there is nothing here to reach. It does not fail at the second host. It fails at the second process, which is where a pool's contenders live.

This is not a defect the contract can name, and the contract should not grow one. Every violator in src/ration/conformance/violators.py is wrong logically: it computes an answer the contract forbids, in one process, where the suite is looking. DuckDB is wrong about deployment topology, which the contract deliberately does not govern. Adding a property for it would be inventing a clause with no caller. So the suite's verdict on DuckDB is correct and incomplete, and the single-process test is the part that completes it.

What it was actually worth: it found a hole in the suite, and a consumer found it first. DuckDB's creation path raised Duplicate key ... violates primary key constraint under load, from tests/test_lease.py, after the conformance run had pronounced the same path correct. The cause was in the suite's own instruments: every concurrent test seeded its key single-threaded and then raced from that version, so the suite had only ever raced updaters. The INSERT branch had never been raced at all. test_two_creators_racing_from_absence_do_not_both_apply closes it, and the control is the usual one: with the defect reintroduced the new test goes red while the entire pre-existing suite passes green.

The second-order lesson is about probes, not about DuckDB. The first draft of that test was threaded only. It caught naive every run in isolation and then let it through inside the full suite. So the test now gates through the deterministic stepper wherever a seam exists and probes with threads only where none does; its docstring says why a creation race forces that split.

What the first consumer found

Both findings are the same lesson as the Conflict correction above, arriving from a new direction: a property nothing asserts on is a property the code is free to be wrong about, and the prose will agree with it the whole time.

resolve decided by token before version, which is wrong for a lease renewing itself. The renewing holder's token was already in the store from the grant before, so a renewal whose reply was lost came back APPLIED, and the holder was told it had a TTL the store had never been given. It was fixed by testing the version first; the argument for that order, and why property 1 makes it decisive, is resolve's docstring in src/ration/contract.py.

  • The suite as it then stood could not have caught it. test_ambiguity.py created and never rewrote, and the token stops identifying a write only once a caller writes the same key twice. Nothing did until the lease did; test_a_rewriters_lost_answer_is_resolved now reaches that case.
  • The contract is untouched. The information needed was in the store the whole time and the procedure was reading it in the wrong order. This is a defect in the remedy, not in the contract.
  • Calibrated before it was trusted: the regression test was run against the old ordering and fails there, returning a lease at the unchanged version. A test that has only ever been seen to pass has not been shown to test anything.

The exclusivity check was green while never racing, and the negative control is the only reason that is known. Starting eight threads in a loop is not a race: an in-memory acquire finishes in microseconds, so the first claimant was done before the last was started. Exclusivity passed, on a window it never entered. The control, the same contention against naive, which must double-grant, failed, which is what a control failing is for.

It then took two more shapes to get right, and the second failure is the instructive one:

  • A threading.Barrier fixed it on a machine with many cores and failed on a smaller one. A barrier synchronises arrival, and arrival is not overlap: on a smaller machine the winner finishes its whole compare-and-set before the loser is scheduled, so sampling has to catch the overlap in the instant it exists.
  • Counting a violation per operation rather than sampling a moment does work, catching naive in roughly half the rounds.

So it was replaced by a deterministic gate anyway, and not because it failed. naive's seam sits exactly in its gap, so one claimant can be parked there while another runs to completion. Where a store has a seam, a gate beats any per-round rate: a probe that catches a known-bad store half the time is evidence about the probe; a parked thread is a verdict. The threaded probe keeps its place because postgres has no seam, and there it is the only instrument there is. The gate is proven both ways: the identical interleaving against the correct store grants one holder.

Threads or processes, answered with a number instead of a paragraph

The threaded probe is eight threads in one interpreter, and a lease service's real population is processes, often on more than one host. Whether that difference matters is a question the suite answers rather than assumes.

tests/test_postgres_cross_process.py is the same arithmetic, eight contenders with one hundred increments each, run as eight operating-system processes under spawn, each building its own store from nothing but a DSN.

For detection it makes no difference, and that is a measurement. Both populations were pointed at postgres-naive, which has no version predicate in its write and must lose increments. One set of runs on a development machine:

Population Increments lost of 800 Runs
8 threads, one interpreter 673, 687, 689 3
8 processes, spawn 662, 668, 669, 671, 673, 686 6

The ranges overlap. Against the real store, postgres returned 800 of 800 in every run of both. The thread count was never the interesting variable here: every operation is a round trip, so the writers already interleaved at the socket without the interpreter needing to be persuaded to switch, which is the reason the threaded hammer catches this store so much more reliably than it catches the in-memory naive.

What the process version does buy is structural, and it is not the contention. The threaded hammer shares one PostgresStore instance across its eight workers; that instance holds a threading.local() connection registry, so the workers are eight clients of one store object. A deployment is not that. Any defect living in state accidentally shared inside a store instance is invisible where there is only one instance to share it, and this probe has one store per process, so it cannot inherit that blindness. The claim is narrow on purpose: it removes a caveat, it does not raise the catch rate.

The harness is calibrated before either verdict is read, because a spawn pool that quietly ran every task in the parent would produce a perfect counter and prove nothing: it would be the threaded result wearing this test's name. Each worker reports its PID and the test asserts it saw eight distinct ones.

Still a probe. It has no seam to park in either, so a run that finds nothing has not shown there was nothing to find. What keeps it honest is that the identical harness is required to catch postgres-naive, as a plain assertion rather than an xfail, because there the subject is the harness.

A refusal that arrives late

PostgresStore reuses a thread's connection while conn.closed is false, and conn.closed stays false on a connection the server has killed (the store's _connect docstring says when it changes). A store restart therefore cost each idle reader one refusal whenever it next called, which can be hours later, reported as a store failure about a store that had been back the whole time.

  • read() redials once when the statement fails on a reused connection. A store that is really down still refuses, because the redial is a real connect: property 3 is not traded for it.
  • compare_and_set() never does, including on a connection that was dead before the statement left. The client cannot tell that from a write that applied and lost its answer, and repeating the second is a double write, which property 4 exists to prevent. The caller resolves it by reading, and the read is what redials.
  • Pinned by the event itself. tests/test_postgres_killed_connection.py kills the store's backend with pg_terminate_backend against the server CI already runs, so the sequence is replayed on every pull request. Its fakes cover only what no server can stage.
  • And each of its tests runs against the stores built wrong on purpose that break its rule, under the same strict xfail the contract's violators get. Four are built: the store as it stood before, one that redials until it works, one that forgets which connections it opened itself, and one that gives a write the read's courtesy. A test that stops rejecting is a failure on the next run.

Installing

The distribution is catincloud-ration, and it imports as ration. .github/workflows/publish.yml uploads each release to PyPI from v0.2.1 on. An earlier release installs from a clone at its tag, as under Versions and releases. From PyPI:

pip install catincloud-ration
pip install "catincloud-ration[conformance]"

The first installs the services and stores alone. The second adds pytest, the one dependency of the suite the package ships as ration.conformance (Running the suite against your own store, below).

pip install ration installs a different project. The bare name on PyPI belongs to an unrelated window manager for Python 2.6, last released as 0.1.3 in 2010. Its setup.py installs a top-level ration package of its own, so the two cannot share an environment.

publish.yml uploads a release from its signed tag only once the checks under Versions and releases have passed and the stranger-shaped projects in .github/strangers/ have judged the wheel it uploads. Each file it uploads carries a PEP 740 attestation. After the upload, the same run reads each file's provenance back from the index. A provenance that names any publisher but that workflow, in this repository, in its pypi environment, turns the run red, and the run then creates no GitHub release. v0.1.0 and v0.2.0 are GitHub releases only, and their trees name the distribution ration.

Versions and releases

Releases are listed at https://github.com/catincloud-labs/ration/releases, and the first is v0.1.0. Install a release from a clone at its tag, then as in Running it, below; for another release, put its tag in place of v0.1.0:

git clone https://github.com/catincloud-labs/ration.git
cd ration
git switch --detach v0.1.0

A clone at a tag holds this README as it stood at that tag. The one at v0.1.0 still says no release had been cut, which is what it said before the tag existed; CHANGELOG.md at main records that sentence and when it died.

A GitHub release carries no files of its own. The source archives GitHub attaches to every release hold no .git, so the tag cannot be checked from one; use the clone. A release is a signed v* tag, its upload to PyPI from v0.2.1 on, and its GitHub release, both made by .github/workflows/publish.yml from the tag only after .github/workflows/release.yml, which it calls, has verified the tag's SSH signature against .github/allowed_signers, read the tag's name as exactly v and the version pyproject.toml carries at the tagged commit, and run the suite there. The same workflow runs both checks on tags built wrong on purpose (unsigned, lightweight, a gpg signature, signed by another key, a signature moved from another tag, no summary line; a name that is not the version, only begins with it or is cut short of it, a version from another table, a commit with no version, and a parser that cannot run) and fails unless each is refused, on every pull request and before every release. v0.1.0's release run predates the version check and its arms; see below. The version in pyproject.toml at a commit no tag names is not a release. While the major version is 0, a change to what the suite decides moves the minor version and may break a caller; a patch release never changes what the suite decides.

A tag is checked from a clone at that tag, with the script the workflow runs:

bash .github/release/verify-tag.sh v0.1.0 .github/allowed_signers

A bare git verify-tag is not the same check: it passes a signature made for another tag and moved to this one. The script's exit 0 shows that a key .github/allowed_signers names signed a tag object carrying this tag's own name. The file travels in the same tree as the tag it vouches for, so it says nothing on its own about who holds that key.

The version is checked with bash .github/release/check-version.sh <tag>, which reads pyproject.toml from the commit the tag names, not from the working tree. v0.1.0 was released before that script existed, so its tree does not carry it and its release run did not compare its version; from a clone at main, bash .github/release/check-version.sh v0.1.0 admits it.

Do not install by the bare name. ration on PyPI is an unrelated project. .github/workflows/publish.yml uploads this package's releases to PyPI as catincloud-ration from v0.2.1 on (Installing, above). Its wheel carries the suite that judges a store, as ration.conformance, and the suite's one dependency, pytest, is the conformance extra rather than a dependency of the package. The one module of the suite that needs more is ration.conformance.postgres_violators, the Postgres violator, which needs psycopg and is imported only by a caller that registers it.

Running it

pip install -e ".[dev]"
pytest                                   # the fakes only

The Postgres cases are registered only when a server is named, so a run without one silently drops the only store in the suite that more than one process can share. That is fine locally and unacceptable in CI, where RATION_REQUIRE_POSTGRES=1 makes its absence a failure:

docker run -d --name ration-pg -e POSTGRES_PASSWORD=ration \
  -e POSTGRES_USER=ration -e POSTGRES_DB=ration -p 55432:5432 postgres:17-alpine
until docker exec ration-pg pg_isready -h 127.0.0.1 -U ration -d ration; do sleep 1; done
RATION_POSTGRES_DSN=postgresql://ration:ration@localhost:55432/ration pytest

The wait is load-bearing, and -h 127.0.0.1 is what makes it one. On a new container the image's entrypoint first runs a temporary server for its init with listen_addresses='': a unix socket and no TCP (docker-entrypoint.sh, docker_temp_server_start). It then stops that server and starts the real one. Over TCP, pg_isready answers only once the real server listens. Over the socket it can answer during the temporary one; that is read from the entrypoint, not observed. Without the wait, a run started against a new container can fail with server closed the connection unexpectedly, while the same suite against a server that has finished starting is green.

A run reports xfailed once per violator per property it is expected to break. Those are the suite working. A passing violator is reported as a failure, which is the only outcome that means the suite has stopped measuring anything.

Running the suite against your own store

The suite ships in the package as ration.conformance, and a store of yours joins it through a pytest plugin, ration.conformance.plugin. The plugin has no entry point, so installing ration never enables it: a project that holds a lease with ration runs its own tests as it did. A project that judges a store installs the package with its conformance extra, from a clone at a release's tag as in Versions and releases, and enables the plugin by name. From the directory holding the clone:

pip install "./ration[conformance]"

From v0.2.1 on, the same package and extra install from PyPI, with pip install "catincloud-ration[conformance]".

A tag whose tree has src/ration/conformance/plugin.py has the plugin; v0.1.0 does not.

Every run through the plugin judges the package's own cases beside yours. They are the in-memory store, the correct store with an unusual answer, every violator in the table under The first piece of work but postgres-naive, which needs a server, and every frame codec. Each violator is strict-xfailed against the property it breaks, so a run in which one passes in your environment is red, whatever your store did. Frame codecs take no case of a caller's: the frame is this package's wire format and ration.frame its reader, and a hook for them would be a public name with nothing yet to carry.

In the conftest.py at the root of the directory you run pytest from, enable the plugin and answer its one hook, pytest_ration_cases, with your cases. This is the shape .github/strangers/common/stranger.py builds for the installed wheel job, for a store in one process:

import time

from ration.conformance.support.backends import BackendUnderTest, Case
from ration.conformance.support.faults import FaultInjector

from yourpackage import YourStore  # a `ration.contract.Store`

pytest_plugins = ["ration.conformance.plugin"]


def your_case() -> Case:
    def build() -> BackendUnderTest:
        faults = FaultInjector(YourStore())
        return BackendUnderTest(
            case=case,
            store=faults,
            advance_store_time=time.sleep,
            skew_client_clock=lambda _seconds: None,
            partition=faults.partition,
            ambiguity=faults.ambiguity,
        )

    case = Case(name="your-store", violates=frozenset(), build=build)
    return case


def pytest_ration_cases() -> list[Case]:
    return [your_case()]

Then run the suite the package ships, naming the case the run must judge:

pytest --pyargs ration.conformance --ration-require your-store

The report header names the package's cases, yours and what is required, and each test's id names the case it ran.

--ration-require NAME is the switch that keeps a lost store from reading green. Repeat it for each case the run must judge; it is modelled on this repository's RATION_REQUIRE_POSTGRES. If no collected test runs a case of yours by that name, because none was registered (a CI job that lost the variable naming your server, say), because the suite was not collected, or because -k, -m or a node id left it out, the run ends as a usage error, exit 4, before any test runs. A name of the package's own cases does not satisfy it, and a case named like one of the package's is refused, because the name is how the report and the switch tell cases apart.

The case contract

A Case and the BackendUnderTest its build returns are in ration.conformance.support.backends; FaultInjector is in ration.conformance.support.faults.

Field What it must do
Case.name Name one case in the run. It is each test's id and what --ration-require takes.
Case.violates Name the properties the store is expected to fail, as each suite module's conformance marker names them; empty for a store you claim is correct. Each test of a named property is strict-xfailed, so a store that passes one is a failing run. A name no test declares marks nothing, and the check that catches one, tests/test_the_suite_discriminates.py, is this repository's and not in the package.
Case.build Return a fresh BackendUnderTest, called with no arguments for each test that runs the case. key() hands each build keys nothing else has touched, so a persistent store may serve every build.
case The Case it was built from.
store Your store, wrapped in FaultInjector, so ambiguity can lose a write's answer.
advance_store_time(seconds) Return once at least seconds of the store's own time has passed: time.sleep for a store that reads its own clock. The suite's leases last REAL_TTL, half a second, so the waits stay short.
skew_client_clock(seconds) Move the clock on the caller's side of the store. A store never told the caller's time takes a no-op, and that the expiry tests then hold trivially is the result, not a gap.
partition() A context manager inside which every read and write raises Unreachable, with the store reachable again after it. For a store with a server, point it somewhere that refuses a connection, as postgres_case in the same module does, so the suite sees your store translate the failure. FaultInjector.partition refuses on the store's behalf and shows only that the layers above it refuse.
ambiguity(applied=...) A context manager that makes the next write raise Ambiguous, having applied or not as applied says. Every registered case uses FaultInjector.ambiguity.
_stepped Leave it out. The stepped build parks an operation in the memory store's own _staged seam, which no other store has. A case without one skips the test that needs it, and atomicity is decided for it by the threaded probe, at the false-pass rate test_atomicity.py states; a probe that never raced reports a skip rather than a verdict.

What a green run shows, and what it does not. Your case passed every test of every property, in your environment, in a run in which the package's correct stores passed and each of its violators failed its own property. It shows nothing the suite does not decide: the gaps stated above, such as a version reused across a restore and a store only one process can open, are gaps for your store too.

Licence

Apache-2.0. See LICENSE.

About

A bounded claim on a finite shared pool, granted for a period and refused rather than overdrawn.

Topics

Resources

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages