DECISION CHAIN · NO. 003
The construction and mechanisms of the decision chain
Every decision the ledger makes, to post an entry or refuse one, is recorded. Since August each record carries the hash of the one before it, and every night each chain's newest hash is stored outside the chain. The braid behind this page is the newest hash, drawn when the page is served.
> the chain cannot prove its own history. the anchor can. # test_decision_chain_anchor.py
An audit log that can be edited is a record of what somebody last decided it should say.
CommunityPay's ledger records a decision before every entry it posts and every one it refuses: the guards the policy required, the guards that ran, what each one found, the law the decision stood on, and the outcome. That log is how an auditor knows the ledger obeyed its own rules. This post is how the log came to prove it has not changed since it was written, in eight iterations. Three of them repaired checks that were quietly wrong: one raised false alarms, and two would have stayed green over a rewrite. The last two closed a fork this post found.
Earlier posts in the series covered a ledger that records its refusals (NO. 001) and the law underneath it (NO. 002). Panels marked ITERATION are abstracted from the production system. Panels with a wax rule are copied from the tree.
PART I
A record the application will not change
# iteration 0 — the application refuses to change a decision
class EnforcementDecision(ImmutableModelMixin, models.Model):
...
class ImmutableModelMixin:
def save(self, *args, **kwargs):
if not self._state.adding:
raise PermissionDenied # an update
def delete(self, *args, **kwargs):
raise PermissionDenied # always
In February the enforcement decisions, the eligibility evaluations, and the exclusion trigger hits became immutable in the application: an update raises, and so does a delete.
That promise is kept by the application, and only by the application. The database does not know it. Someone holding the database's credentials can edit a decision or delete one, and every row left behind is still a valid row. Individually valid rows are collectively silent: delete one and the survivors do not know it is gone. The nightly scan could find an entry missing its decision. It could not find a decision missing from the log.
PART II
Each decision seals the one before it
# iteration 1 — each decision hashes its content and its predecessor's hash
prev = newest_decision(hoa).record_hash # '' for an association's first
record_hash = sha256(canonical_json({**content, 'prev_record_hash': prev}))
# every night: recompute each association's chain, newest first; a break is CRITICAL
#: Fields whose values the record_hash covers. Deliberately the decision
#: itself and its evidence — not created_at, which the DB sets, and not
#: journal_entry, which is written on the POST_PERSIST row after the
#: entry exists.
HASHED_FIELDS = (
'hoa_id', 'correlation_id', 'event_type', 'decision', 'decision_seq',
'flow_name', 'entrypoint', 'transaction_type', 'policy_snapshot_hash',
'guards_expected', 'guards_ran', 'guard_results', 'blocking_guard',
'blocking_code', 'blocking_reason', 'amount_cents', 'funds_touched',
# The law the decision stood on is part of the decision. Hashing it
# means the provenance cannot be rewritten after the fact either.
'legal_authorities_snapshot', 'legal_drift_warnings',
)
def compute_record_hash(self) -> str:
"""SHA-256 over this decision's content plus prev_record_hash.
Canonical JSON (sorted keys, compact separators) so the digest is
reproducible from the stored row by anyone, in any language.
"""
import hashlib
import json
payload = {
field: _json_safe(getattr(self, field, None))
for field in self.HASHED_FIELDS
}
payload['prev_record_hash'] = self.prev_record_hash or ''
canonical = json.dumps(payload, sort_keys=True, separators=(',', ':'))
return hashlib.sha256(canonical.encode('utf-8')).hexdigest()
accounting/models/enforcement_decision.py · EnforcementDecision
The hash covers the decision and its evidence: the guards the policy expected and the guards that ran, each one's result, the policy snapshot, the amount, the funds touched, and the law the decision stood on. It leaves out created_at, which the database sets, and the journal entry, which is written on the second record after the entry exists. The JSON is canonical, with sorted keys and no spaces, so anyone can reproduce a digest from the stored row, in any language.
Each association keeps its own chain. A decision's prev_record_hash is the hash of the decision sealed before it in that association's chain, and the first decision of a chain carries an empty one. Edit a row and its own hash stops reproducing. Remove one and its successor points at a predecessor that is gone. Every night the scan runs verify_chain over each association's chain, newest first. It files a critical finding for each break, and the gate that watches the chain turns red.
Building the chain found two defects in the records it was about to seal. A decision's sequence number was unique across every association rather than within one, so two postings that shared a correlation id collided, and the helper that created the record swallowed the error and returned the other posting's row: one entry's decision, attributed to another. And a guard the policy required but the registry did not hold was recorded as skipped while the decision still read ALLOW. Nothing compared the guards that ran with the guards expected. Now an ALLOW on an incomplete set of guards becomes an error, GUARD_NOT_EVALUATED, and the posting is refused.
PART III
The chain cannot prove its own history
# iteration 2 — what a chain cannot see
delete(decision_4) # around the application
for d in decisions_after(decision_4):
d.prev_record_hash = d.predecessor().record_hash
d.record_hash = d.compute_record_hash() # every link reproduces again
assert verify_chain(hoa)['valid'] # and the chain agrees
verify_chain proves the log is consistent with itself. Consistency is exactly what someone with the database's credentials can restore: delete a decision, recompute every hash after it, and every link verifies. The chain cannot notice, because the evidence and the thing it attests to are the same rows. Everything built until then detected carelessness. None of it detected intent.
# iteration 3 — the head, recorded outside the chain
# every night, inside the snapshot's own hash:
snapshot.decision_chain_head = latest_chain_hash(hoa)
for head in heads_recorded_on_earlier_nights(hoa):
if head not in record_hashes(hoa):
finding(DECISION_CHAIN_REWRITTEN, CRITICAL)
Every night the scan writes an immutable snapshot for each association, and since August the snapshot carries the head of that association's chain inside its own hash. The next scan checks that every head an earlier night recorded still exists in the log. A rewrite changes every hash from the altered link forward, so a head recorded after that link stops existing, in a record the rewrite did not touch.
That separates two findings. DECISION_CHAIN_BROKEN is a gap someone left. DECISION_CHAIN_REWRITTEN is a gap someone closed.
def test_a_rewritten_history_is_caught_even_though_the_chain_verifies(self):
"""The whole point. Two assertions, and the first one must pass.
The chain is made self-consistent again after the deletion, exactly as
someone covering their tracks would. verify_chain is satisfied. The
anchor is not.
"""
self._decision('33333333-3333-3333-3333-333333333333')
first_scan = self._scan()
anchored = first_scan.decision_chain_head
self.assertNotEqual(anchored, '')
# Someone with database credentials removes a decision and rebuilds
# the chain so every remaining row reproduces its own hash. The ORM
# refuses this, which is the point of the immutability guard — the
# threat model here is the person who goes around the ORM, so the
# test takes the same escape a deliberate teardown would.
from accounting.models.mixins import allow_immutable_delete
with allow_immutable_delete():
EnforcementDecision.objects.filter(hoa=self.hoa).delete()
self._decision('44444444-4444-4444-4444-444444444444')
self.assertTrue(
EnforcementDecision.verify_chain(self.hoa.id)['valid'],
'precondition: the rewritten chain must look clean, or this test '
'is not testing the anchor',
)
self._scan()
finding = IntegrityFinding.objects.filter(
hoa=self.hoa,
finding_type=IntegrityFinding.DECISION_CHAIN_REWRITTEN,
).first()
self.assertIsNotNone(
finding, 'a rewritten history passed unnoticed')
self.assertEqual(finding.severity, IntegrityFinding.CRITICAL)
self.assertEqual(finding.context['prior_anchor'], anchored)
accounting/tests/test_decision_chain_anchor.py
The test performs the attack. It deletes the association's log, writes a new decision so the chain is consistent again, and asserts that verify_chain calls it valid. That assertion is a precondition: a rewritten chain that did not look clean would not test the anchor. Then it runs the scan and requires the finding. The deletion takes allow_immutable_delete(), because the application refuses it otherwise. The threat is the person who goes around the application.
The idea is older than the web. In 1991 Stuart Haber and W. Scott Stornetta linked each time-stamped document to the hash of the one before it, and the service built on their scheme, Surety, took a summary hash out of its own hands: from the 1990s it printed one each week in the classified pages of The New York Times. Certificate Transparency's logs sign the heads of their trees for the same reason, so that anyone who saw a head can hold the log to it. Scott Crosby and Dan Wallach put the requirement plainly in 2009: "a tamper-evident log requires frequent auditing."
Bruce Schneier and John Kelsey designed their 1999 audit log for the day an attacker captures the machine that keeps it. The anchor here is held in the same database as the chain. Someone with its credentials could rewrite the snapshots too, and recompute their hashes, which are SHA-256 with no key. The anchor makes a rewrite take two consistent forgeries instead of one. It does not make one impossible. A head held where the database cannot reach goes further, and this page is one such place: it prints the newest hash, and every saved copy of the page keeps it.
PART IV
Three checks that were quietly wrong
# iteration 4 — a snapshot is hashed over its own version's payload
payload = PAYLOAD[snapshot.content_hash_version] # 1: eight fields; 2: those and the head
assert snapshot.content_hash == sha256(canonical_json(payload))
The anchor went inside each snapshot's hash on 10 August. Two days later 196 of the last 200 production snapshots failed verification. Their digests had been computed before the field existed, so recomputing them with it could never match. A false tamper alarm on the artifact an auditor is handed is worse than none: a check that cries wolf is one people learn to wave through.
# Hash schema versions. A snapshot must remain verifiable under the schema
# it was written with: adding decision_chain_head to the payload silently
# invalidated every row hashed before it, and 196 of 200 production
# snapshots began reporting as tampered — a false alarm on precisely the
# artifacts an auditor is handed. Version 1 reproduces the original
# payload; anything hashed from here is version 2. Never edit an existing
# version's field list. Add a new one.
HASH_V1_ANCHORLESS = 1
HASH_V2_WITH_ANCHOR = 2
def _compute_content_hash(self) -> str:
"""SHA-256 over the payload for this row's own hash schema version."""
hash_data = {
'snapshot_id': str(self.snapshot_id),
'hoa_id': self.hoa_id,
'as_of_date': self.as_of_date.isoformat() if self.as_of_date else None,
'checks_run': self.checks_run,
'check_results': self.check_results,
'total_journal_entries': self.total_journal_entries,
'orphaned_je_count': self.orphaned_je_count,
'unbalanced_je_count': self.unbalanced_je_count,
}
if (self.content_hash_version or self.HASH_V1_ANCHORLESS) >= self.HASH_V2_WITH_ANCHOR:
# The anchor is inside the snapshot's own hash. An anchor that
# could be edited to match a rewritten chain would anchor nothing.
hash_data['decision_chain_head'] = self.decision_chain_head
hash_string = json.dumps(hash_data, sort_keys=True, default=str)
return hashlib.sha256(hash_string.encode('utf-8')).hexdigest()
accounting/models/integrity_snapshot.py · IntegritySnapshot
Each snapshot now records the version of the payload it was hashed with. Version 1 is the original eight fields, and version 2 adds the head. A version's field list is never edited; a change is a new version. Tampering is still caught at both versions, so compatibility was not bought by weakening detection.
# iteration 5 — every head ever recorded, not only the newest
heads = recorded_heads(hoa)[:1000] # newest first; reaching the cap is logged
gone = [h for h in heads if h not in record_hashes(hoa)]
report(oldest(gone)) # it bounds where the change can lie
The first anchor check read only the newest snapshot's head, and the evidence expired after one night. The scan after a rewrite failed, then recorded the rewritten head as the new anchor, and the scan the night after checked against that and went green, permanently. The rewrite would have survived in one resolved finding and nowhere else.
anchors = list(
IntegritySnapshot.objects
.filter(hoa=self.hoa)
.exclude(decision_chain_head='')
.order_by('-scanned_at')
.values('snapshot_id', 'decision_chain_head', 'scanned_at')[:self.ANCHOR_WINDOW]
)
check_result.details['chain_head'] = self._decision_chain_head
check_result.details['anchors_checked'] = len(anchors)
if len(anchors) == self.ANCHOR_WINDOW:
logger.warning(
'Decision-chain anchor check capped at %d anchors for HOA=%s; '
'older anchors were not verified this run.',
self.ANCHOR_WINDOW, self.hoa.id,
)
check_result.details['anchor_window_capped'] = True
if anchors:
live = set(
EnforcementDecision.objects.filter(
hoa_id=self.hoa.id,
record_hash__in=[a['decision_chain_head'] for a in anchors],
).values_list('record_hash', flat=True)
)
broken = [a for a in anchors if a['decision_chain_head'] not in live]
check_result.details['anchors_broken'] = len(broken)
# Oldest first: the earliest anchor that stopped resolving bounds
# when the rewrite happened.
prior = broken[-1] if broken else anchors[0]
still_present = not broken
accounting/services/ledger_integrity_scan.py · LedgerIntegrityScanService
A decision is never legitimately deleted, so every head ever recorded must resolve forever. The check now reads all of them, up to 1,000, and logs when it reaches the cap. It reports the oldest that broke: the altered link lies after the newest head that still resolves and no later than the oldest that does not. The gate on the monitoring board carried the same defect for one more day.
# iteration 6 — a check that stops short says so
return {'valid': not breaks, 'checked': verified, 'skipped': skipped,
'examined': len(rows), 'total': total, 'truncated': total > len(rows), ...}
verify_chain reported the rows it looked at as the rows it checked. It looked at 1,000 at most, and it skipped every row older than the chain without verifying it, so "3,000 decisions, chain intact" could mean 1,000 examined and 950 of those skipped. It now returns what it verified, what it skipped, what it examined, the total, and whether it stopped short, and both of its callers report a check that stopped short instead of passing over it.
PART V
Two writers, one predecessor
# iteration 7 — two postings for one association, in overlapping transactions
a.prev_record_hash = newest(hoa).record_hash # neither sees the other's uncommitted row,
b.prev_record_hash = newest(hoa).record_hash # so both take the same predecessor
# verify_chain walks b, then a: b does not follow a, and the fork reads as a break
Writing this post found a defect the nightly record had never shown. A decision read its association's newest hash when it was written. Two decisions written at once, in overlapping transactions, could not see each other's rows, so both took the same predecessor. The nightly check would read that fork as a break: a tamper alarm with nothing tampered. In eighty-nine nights it had not happened. The code allowed it.
The first fix held a lock on the association's chain from reading the head until the transaction committed. An independent review reproduced a deadlock in it. Recording a deposit holds the bank account's row and then writes its decision; voiding a payment writes its decision and then needs the same row. Each waited on the other, and the database ended one. The same lock would have held every posting for an association behind a month's invoicing, which runs in one transaction. It never shipped.
# iteration 8 — write first, link after the commit
decision.awaiting_seal = True
decision.save() # no hash, no lock
on_commit(lambda: seal(hoa))
def seal(hoa): # its own short transaction
lock_chain(hoa) # first, then nothing but decisions
for d in waiting(hoa, oldest_first):
d.prev_record_hash, d.chain_seq = head.record_hash, head.chain_seq + 1
d.record_hash = d.compute_record_hash()
head = d
A decision is now written unsealed, with no hash and no lock. When its transaction commits, a short transaction of its own takes the chain lock and links every waiting decision of the association, oldest first: the head's hash as its predecessor, its own hash, and the next position in the chain. It takes the lock before anything else and touches nothing but decisions, so it cannot join a cycle, and no posting waits on it. The database refuses two decisions at one position, so a fork cannot be stored even if the lock were bypassed. The chain's order is the order of sealing, not a server's clock.
A decision whose process ends between its commit and its seal waits. A sweep seals it within five minutes, the nightly scan seals before it verifies, and one still waiting after fifteen minutes turns the gate red.
PART VI
Why nothing before August is hashed
Every decision written since the chain's first link, dated 12 August 2026, carries a hash. The 7,593 written before it do not. Backfilling them was declined on 10 August 2026.
Every one of them could be hashed tomorrow. The rows are there, the fields are there, and the scan would run.
A hash written over a row today attests that the row has not changed since today. It says nothing about the months before. A backfilled chain would have a first link younger than almost everything it covers, and coverage that began on the day someone decided to add it, while looking as old as the log.
What a backfill would buy is watch over the older rows from that day forward: an edit to one of them afterwards would show. What it cannot buy is their history. The chain begins with the first decision written after the mechanism shipped, and that link carries its own date. The rows from before it are protected by the application's refusal to change them, and by nothing else.
PART VII
The braid behind this page
The braid in the margin is the newest record hash, drawn when the page is served. Each of the hash's thirty-two bytes is one crossing on nine strands: the top three bits choose which adjacent pair crosses, the next bit which of the two passes over, and the low four how tight the crossing is drawn. Nothing else goes into the shape.
A braid is not a metaphor for a chain. It is the same kind of object. A hash chain is an ordered sequence of commitments in which each link fixes everything before it. A braid is an ordered sequence of crossings in which each one permutes everything after it. Change any decision in the newest hash's chain and the hash changes, and every crossing with it.
Change one hex digit and one crossing moves. A digit is half of one byte, and a byte decides one crossing. The strands after it trade places, and because they are drawn alike, nothing else in the braid moves.
The newest hash is printed at the foot of this page. Anyone with read access to the log can check it:
from accounting.models import EnforcementDecision as E
newest = (E.objects.exclude(record_hash='')
.order_by('-created_at', '-record_hash')
.values_list('record_hash', flat=True).first())
print(newest) # the hash below, or a newer one
published = '...' # the hash on a saved copy of this page
print(E.objects.filter(record_hash=published).exists())
A newer hash than the one printed means the log moved, which is expected. A printed hash that no longer exists in the log means a chain was rewritten. The first is a date. The second is not.
The braid has thirty-two crossings whether a chain holds two links or two million. A drawing that grew with the log would look like a history, and its length would be a claim. This one is a single hash, so it makes none. What the page prints instead is the nightly record: the nights the chains have been checked, and how many passed.
Each new decision replaces the newest hash, and the next reader sees a different braid. An image made for sharing is drawn once, from the newest hash on the day it is posted, and matches the log as it stood that day and no later. Published articles are supposed to stay put. This one keeps its words and lets its picture move.
EVERY LINK SEALED.
EVERY HEAD KEPT.
CHECKED EVERY NIGHT SINCE 13 AUG 2026
105 OF 105 NIGHTS PASSED
LAST CHECK 25 NOV 2026, 2:00 AM PST · NO BREAKS · NO REWRITES
NEWEST HASH · 20 NOV 2026
81cafb8c9cbb45b61a8e1f43f53e6192df76b53088ce6f63c010156fe3f68f2c