Installation guide · Run the service
Check an audit export
Check that the chains of an audit export hold, with a Python script.
Check an export
To check exports, save the script below as check_audit.py. It needs Python 3 and nothing else. Give it the exports oldest first. It checks that each log's events follow one another and that each event's prev is the hash of the one before, across files too, and it recomputes the hash of each event given whole. With --data and the data volume, it also reads each log whole, recomputes every hash, checks each log's head, and checks each exported event against the log. The image has Python 3, so the second check can run there with the volume read-only:
python3 check_audit.py sequences-audit-2026-11-12.jsonl sequences-audit-2026-11-13.jsonl
docker run --rm -v sequences-data:/data:ro -v "$PWD":/check:ro --entrypoint python3 \
conductscience/sequences:<version> /check/check_audit.py /check/sequences-audit-2026-11-12.jsonl --data /data
It prints each problem it finds and exits with 1, or ends with "the chains hold" and exits with 0. The script:
# check_audit.py checks Sequences audit exports with Python 3 and its standard library alone.
# python3 check_audit.py EXPORT [EXPORT ...] [--data FOLDER]
# Give exports oldest first. In each log it checks that the events follow one another, that each event's prev is the
# hash of the event before it, across exports too, and that each event exported whole still has its own hash. With
# --data and the data folder, it reads each log whole, recomputes every hash, checks the log's head, and checks that
# each exported event is the log's.
import argparse, decimal, hashlib, json, os, re, sys
SURROGATE = re.compile('[\ud800-\udfff]')
LOG = re.compile(r'(service|case/[0-9a-f-]{36}|joins/([0-9a-f]{64}|local))$')
NO_HEAD = {'seq': 0, 'hash': None}
def number(x):
# A float as JavaScript writes it, the shortest digits that read back the same.
if x == 0:
return '0'
t = decimal.Decimal(repr(abs(x))).as_tuple()
digits = ''.join(map(str, t.digits))
n = len(digits) + t.exponent
digits = digits.rstrip('0')
k, sign = len(digits), '-' if x < 0 else ''
if k <= n <= 21:
return sign + digits + '0' * (n - k)
if 0 < n <= 21:
return sign + digits[:n] + '.' + digits[n:]
if -6 < n <= 0:
return sign + '0.' + '0' * -n + digits
e = n - 1
return sign + digits[0] + ('.' + digits[1:] if k > 1 else '') + 'e' + ('+' if e >= 0 else '-') + str(abs(e))
def text(s):
return SURROGATE.sub(lambda m: '\\u%04x' % ord(m.group()), json.dumps(s, ensure_ascii=False))
def canonical(v):
# JSON as the service hashes it: as JavaScript writes it, with the keys of every object sorted.
if v is None or isinstance(v, bool):
return json.dumps(v)
if isinstance(v, int):
return str(v)
if isinstance(v, float):
return number(v)
if isinstance(v, str):
return text(v)
if isinstance(v, list):
return '[' + ','.join(map(canonical, v)) + ']'
keys = sorted(v, key=lambda key: key.encode('utf-16-be'))
return '{' + ','.join(text(key) + ':' + canonical(v[key]) for key in keys) + '}'
def sealed(event):
rest = {key: value for key, value in event.items() if key != 'hash'}
return hashlib.sha256(canonical(rest).encode('utf-8')).hexdigest() == event.get('hash')
def lines_of(path):
lines = []
with open(path, encoding='utf-8', newline='') as f:
for n, line in enumerate(f.read().split('\n'), 1):
if line.strip():
try:
value = json.loads(line)
except ValueError:
value = None
lines.append(value if isinstance(value, dict) else {'invalidLine': n})
return lines
def check_exports(exports, problems):
seen = {}
for n, lines in enumerate(exports, 1):
def say(log, seq, reason):
problems.append('export %d%s%s: %s' % (n, ', ' + log if log else '', ', event %s' % seq if seq else '', reason))
if any('invalidLine' in line for line in lines):
say(None, None, 'a line is not a JSON object')
tail = lines[-1] if lines else {}
if tail.get('record') != 'export' or tail.get('format') != 'sequences-audit':
say(None, None, 'it has no export line at its end, so it may be cut short')
logs = {}
for line in lines:
if line.get('record') in ('event', 'chain'):
logs.setdefault(line.get('log'), []).append(line)
for log, group in logs.items():
events = [line for line in group if line['record'] == 'event']
chain = next((line for line in group if line['record'] == 'chain'), None)
if chain is None:
say(log, None, 'it has no chain line')
continue
known = seen.setdefault(log, {})
first, prev, last = chain.get('first') or 0, chain.get('prev'), max(known, default=0)
if last and first > last + 1:
say(log, last + 1, 'events %d to %d are in none of the exports given' % (last + 1, first - 1))
if first - 1 in known and known[first - 1] != prev:
say(log, first, 'it does not follow the event an earlier export gave before it')
if len(events) != (chain.get('last') or 0) - first + 1:
say(log, None, 'its chain line and its events disagree on how many there are')
for seq, line in enumerate(events, first):
event = line.get('event')
if not isinstance(event, dict) or event.get('seq') != seq:
say(log, seq, 'this line is not the event with this number')
break
if event.get('prev') != prev:
say(log, seq, 'it does not follow the event before it')
if not line.get('withheld') and not sealed(event):
say(log, seq, 'it changed after it was written')
if known.get(seq, event.get('hash')) != event.get('hash'):
say(log, seq, 'an earlier export gave it another hash')
known[seq] = prev = event.get('hash')
check = chain.get('check') or {}
if check.get('ok') is False:
say(log, None, 'the server found the log broken when it exported it: %s' % (check.get('broken') or {}).get('reason'))
def read_log(data, log):
if not LOG.match(log or ''):
return None
kind, _, name = log.partition('/')
folder = os.path.join(data, {'service': 'audit', 'case': 'cases', 'joins': 'applicants'}[kind], name)
if not os.path.exists(os.path.join(folder, 'events.jsonl')):
return None
if kind == 'case':
with open(os.path.join(folder, 'case.json'), encoding='utf-8') as f:
head = json.load(f).get('head') or NO_HEAD
elif os.path.exists(os.path.join(folder, 'head.json')):
with open(os.path.join(folder, 'head.json'), encoding='utf-8') as f:
head = json.load(f)
else:
head = NO_HEAD
return lines_of(os.path.join(folder, 'events.jsonl')), head
def broken(events, head):
prev = None
for seq, event in enumerate(events, 1):
if event.get('seq') != seq:
return seq, 'this line is not the event with this number'
if event.get('prev') != prev:
return seq, 'it does not follow the event before it'
if not sealed(event):
return seq, 'it changed after it was written'
prev = event['hash']
if (head.get('seq'), head.get('hash')) != (len(events), prev):
return min(head.get('seq') or 0, len(events)) + 1, 'the log\'s head does not name its last event'
return None
def check_data(exports, data, problems):
logs = {}
for lines in exports:
for line in lines:
if line.get('record') == 'event':
logs.setdefault(line.get('log'), []).append(line)
for log, group in logs.items():
found = read_log(data, log)
if found is None:
problems.append('%s: the data folder has no such log' % log)
continue
events, head = found
fault = broken(events, head)
if fault:
problems.append('%s, event %d: %s' % (log, fault[0], fault[1]))
for line in group:
event = line.get('event') or {}
seq, withheld = event.get('seq'), line.get('withheld') or []
stored = events[seq - 1] if isinstance(seq, int) and 0 < seq <= len(events) else {}
if not event or stored.get('hash') != event.get('hash'):
problems.append('%s, event %s: the log does not hold it' % (log, seq))
continue
for key in set(stored) | set(event) | set(withheld):
if (key in event) == (key in withheld) or key not in stored or (key in event and canonical(event[key]) != canonical(stored[key])):
problems.append('%s, event %d: its %s does not match the log' % (log, seq, key))
def main():
parser = argparse.ArgumentParser(description='Check Sequences audit exports.')
parser.add_argument('exports', nargs='+', help='the export files, oldest first')
parser.add_argument('--data', help='the data folder, to check the logs themselves')
args = parser.parse_args()
exports = [lines_of(path) for path in args.exports]
problems = []
check_exports(exports, problems)
if args.data:
check_data(exports, args.data, problems)
for problem in problems:
print(problem)
events = sum(line.get('record') == 'event' for lines in exports for line in lines)
print('%d exports, %d events: %s' % (len(exports), events, '%d problems' % len(problems) if problems else 'the chains hold' + (', and every event matches the data folder' if args.data else '')))
return 1 if problems else 0
if __name__ == '__main__':
sys.exit(main())
Guide version 1.63.0 · For Sequences 0.155.0