Executable contract examples
A worker finishes late, a network chunk splits a character, and a publication fails halfway through. Each exercise isolates one failure you can reproduce.

Pick one row and predict the failure before running the example. In Rust, an old worker may finish after someone else has claimed the job. In JavaScript, one character may span two network chunks. In SQLite, a partially written publication can expose inconsistent evidence.
These synthetic teaching specifications were written for this repository. They use no private Ordo code and implement no application backend. The corresponding CI run is the evidence for which checks passed.
| Lab | Requirement | Related donor observation | What is deliberately missing |
|---|---|---|---|
| Lease ownership · Rust | A-10; TF-03/TF-08 | Historical completion guard lacks an attempt/expiry comparison | Database acceptance race, real workers and clock failure handling |
| Stream framing · JavaScript | A-09 | Current gateway decodes separate byte chunks; workshop uses incremental decoding | HTTP/proxy, authenticated reconnect, persistence and live cancellation |
| Atomic publication · SQLite/Python harness | A-03/A-06/A-14 | Candidate review needs exact content binding and a transaction-owned publication | Complete ontology, real source objects, reviewer authentication and disk/crash durability |
The Python example uses the standard library to exercise SQLite transactions. The JavaScript example runs where the client interprets bytes. The planned application remains Rust-first. All three fixtures run without a model account or a server.
Lease ownership
Question: what happens when worker-a finishes attempt 1 after attempt 2 has already been assigned to that same worker name?
From the repository root, run the fixture with the pinned compiler. The clean-build instructions cover toolchain installation.
rustc +1.90.0 --test docs/examples/lease.rs -o /tmp/ordo-lease-tests
/tmp/ordo-lease-testsThe test rejects_old_attempt_even_with_same_worker_name should pass. It hands the checker an attempt-1 receipt after attempt 2 has been assigned to worker-a and expects rejection. The complete fixture has seven tests.
A worker name alone cannot distinguish those claims. The original Rust example below compares the job, task, worker, monotonic epoch, deadline, input digest and running state. Expiry is exclusive: a result at the deadline is too late. A successful predicate is not sufficient by itself; the eventual store must perform this comparison and the conditional state update in the same transaction.
Inspect the Rust specification and its seven tests
//! Original, dependency-free teaching specification. Not a scheduler or authority service.
//! A production implementation must perform these checks and acceptance in one transaction.
#[derive(Clone, Debug)]
struct Lease<'a> {
job: &'a str,
task: &'a str,
worker: &'a str,
epoch: u64,
expires_at_ms: u64,
input_digest: &'a str,
running: bool,
}
#[derive(Clone, Debug)]
struct Receipt<'a> {
job: &'a str,
task: &'a str,
worker: &'a str,
epoch: u64,
input_digest: &'a str,
}
fn eligible(lease: &Lease<'_>, receipt: &Receipt<'_>, now_ms: u64) -> Result<(), &'static str> {
if !lease.running { return Err("task is not running"); }
if now_ms >= lease.expires_at_ms { return Err("lease expired"); }
if (lease.job, lease.task, lease.worker, lease.epoch)
!= (receipt.job, receipt.task, receipt.worker, receipt.epoch) {
return Err("claim identity or epoch does not match");
}
if lease.input_digest != receipt.input_digest { return Err("input digest changed"); }
Ok(())
}
fn parse_port(value: Option<&str>) -> Result<u16, &'static str> {
match value {
None => Ok(8080),
Some(raw) => raw.parse::<u16>().ok().filter(|port| *port > 0)
.ok_or("LAB_PORT must be an integer between 1 and 65535"),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn fixtures() -> (Lease<'static>, Receipt<'static>) {
(Lease { job: "job-1", task: "extract", worker: "worker-a", epoch: 2,
expires_at_ms: 100, input_digest: "synthetic-input-v1", running: true },
Receipt { job: "job-1", task: "extract", worker: "worker-a", epoch: 2,
input_digest: "synthetic-input-v1" })
}
#[test] fn accepts_current_claim() {
let (lease, receipt) = fixtures();
assert_eq!(eligible(&lease, &receipt, 99), Ok(()));
}
#[test] fn rejects_old_attempt_even_with_same_worker_name() {
let (lease, mut receipt) = fixtures(); receipt.epoch = 1;
assert!(eligible(&lease, &receipt, 99).is_err());
}
#[test] fn expiry_is_exclusive_even_before_reclamation() {
let (lease, receipt) = fixtures();
assert_eq!(eligible(&lease, &receipt, 100), Err("lease expired"));
}
#[test] fn rejects_wrong_task() {
let (lease, mut receipt) = fixtures(); receipt.task = "publish";
assert!(eligible(&lease, &receipt, 99).is_err());
}
#[test] fn rejects_changed_input() {
let (lease, mut receipt) = fixtures(); receipt.input_digest = "different-input";
assert!(eligible(&lease, &receipt, 99).is_err());
}
#[test] fn rejects_non_running_task() {
let (mut lease, receipt) = fixtures(); lease.running = false;
assert!(eligible(&lease, &receipt, 99).is_err());
}
#[test] fn configuration_distinguishes_missing_from_invalid() {
assert_eq!(parse_port(None), Ok(8080));
assert_eq!(parse_port(Some("9000")), Ok(9000));
for value in ["", "oops", "0", "65536", "-1"] {
assert!(parse_port(Some(value)).is_err());
}
}
}In a disposable branch, remove the epoch comparison: the stale-attempt test should fail. Restore the comparison after the exercise.
Transfer gate: race two real store clients, reuse a worker identity, reclaim an expired claim and deliver the old receipt. Exactly one attempt may be accepted. Clock representation and skew policy need explicit design; this lab's integer timestamps are synthetic.
Stream framing
Question: is receiving half of a multibyte character a provider failure?
No. Network boundaries and text/protocol boundaries are different. The fixture contains Café and an emoji, tries every byte split point, and also sends one byte per chunk. It tests LF/CRLF frames, explicit terminal outcomes, a missing completion, a changed run ID, invalid UTF-8 and size limits.
node --test docs/examples/stream.test.mjsInspect the bounded synthetic stream decoder
/** Original synchronous transport lab. It does not open a socket or implement replay/auth. */
export function decodeRun(chunks, { maxBytes = 1024 * 1024, maxFrameChars = 32768 } = {}) {
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0 ||
!Number.isSafeInteger(maxFrameChars) || maxFrameChars <= 0) throw Error('Invalid limits');
const decoder = new TextDecoder('utf-8', { fatal: true });
const events = [];
const outcomes = new Set(['complete', 'failed', 'cancelled', 'interrupted', 'incomplete', 'refused']);
let buffer = '', bytes = 0, runId, sequence = 0, terminal = false, text = '';
function drain() {
let boundary;
while ((boundary = /\r?\n\r?\n/.exec(buffer))) {
const raw = buffer.slice(0, boundary.index);
buffer = buffer.slice(boundary.index + boundary[0].length);
if (raw.length > maxFrameChars) throw Error('Frame limit exceeded');
let kind;
const data = [];
for (const line of raw.split(/\r?\n/)) {
if (line.startsWith('event:')) kind = line.slice(6).replace(/^ /, '');
if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, ''));
}
if (!kind && !data.length) continue;
if (!kind || !data.length) throw Error('Malformed frame');
const value = JSON.parse(data.join('\n'));
if (!value || typeof value !== 'object' || Array.isArray(value) ||
value.schemaVersion !== 1 || typeof value.runId !== 'string' ||
!/^[A-Za-z0-9_-]{1,64}$/.test(value.runId) || value.sequence !== sequence + 1) {
throw Error('Invalid envelope');
}
if (terminal || (!runId && kind !== 'started') || (runId && kind === 'started')) {
throw Error('Invalid sequence');
}
if (runId && value.runId !== runId) throw Error('Run changed');
runId = value.runId;
if (kind === 'delta') {
if (typeof value.text !== 'string') throw Error('Invalid delta');
text += value.text;
} else if (kind === 'completed') {
if (!outcomes.has(value.status)) throw Error('Invalid terminal');
terminal = true;
} else if (kind !== 'started') throw Error('Unknown event');
sequence = value.sequence;
events.push({ ...value, kind });
}
if (buffer.length > maxFrameChars) throw Error('Frame limit exceeded');
}
for (const chunk of chunks) {
if (!(chunk instanceof Uint8Array)) throw Error('Expected bytes');
bytes += chunk.byteLength;
if (bytes > maxBytes) throw Error('Run byte limit exceeded');
buffer += decoder.decode(chunk, { stream: true });
drain();
}
buffer += decoder.decode();
drain();
if (buffer.trim() || !terminal) throw Error('Stream ended before terminal completion');
return { events, text, outcome: events.at(-1).status };
}Inspect the ten transport tests
import test from 'node:test';
import assert from 'node:assert/strict';
import { decodeRun } from './stream.mjs';
const encoder = new TextEncoder();
const frame = (kind, sequence, payload = {}, newline = '\n') =>
`event: ${kind}${newline}data: ${JSON.stringify({ schemaVersion: 1, runId: 'run_1', sequence, ...payload })}${newline}${newline}`;
const fixture = (status = 'complete', newline = '\n') => encoder.encode(
frame('started', 1, {}, newline) + frame('delta', 2, { text: 'Café 🛸' }, newline) +
frame('completed', 3, { status }, newline));
test('all byte split points preserve Unicode and framing', () => {
const bytes = fixture();
for (let split = 0; split <= bytes.length; split++) {
const result = decodeRun([bytes.slice(0, split), bytes.slice(split)]);
assert.equal(result.text, 'Café 🛸');
assert.equal(result.outcome, 'complete');
}
});
test('one byte chunks and CRLF delimiters work', () => {
assert.equal(decodeRun([...fixture('complete', '\r\n')].map(b => Uint8Array.of(b))).text, 'Café 🛸');
});
test('independent lossy chunk decoding demonstrates the donor failure mode', () => {
const bytes = encoder.encode('é');
const wrong = new TextDecoder().decode(bytes.slice(0, 1)) + new TextDecoder().decode(bytes.slice(1));
assert.notEqual(wrong, 'é');
});
test('EOF is not success', () => {
assert.throws(() => decodeRun([encoder.encode(frame('started', 1))]), /terminal completion/);
});
test('incomplete and refused remain distinct terminal outcomes', () => {
for (const status of ['incomplete', 'refused', 'cancelled', 'interrupted', 'failed']) {
assert.equal(decodeRun([fixture(status)]).outcome, status);
}
});
test('a second completion is rejected', () => {
assert.throws(() => decodeRun([fixture(), encoder.encode(frame('completed', 4, { status: 'complete' }))]), /sequence/);
});
test('another run cannot append text', () => {
const value = frame('delta', 2, { text: 'other', runId: 'run_2' });
assert.throws(() => decodeRun([encoder.encode(frame('started', 1) + value)]), /Run changed/);
});
test('malformed UTF-8 is rejected, not replaced', () => {
assert.throws(() => decodeRun([Uint8Array.of(255)]));
});
test('size limits are enforced', () => {
assert.throws(() => decodeRun([fixture()], { maxBytes: 4 }), /byte limit/);
assert.throws(() => decodeRun([encoder.encode('data: too-long')], { maxFrameChars: 4 }), /Frame limit/);
});
test('missing sequence and unknown outcome are rejected', () => {
assert.throws(() => decodeRun([encoder.encode(frame('started', 2))]), /envelope/);
assert.throws(() => decodeRun([fixture('maybe')]), /terminal/);
});This intentionally narrow wire example uses schemaVersion, runId and a contiguous per-run sequence. It is not a general-purpose SSE parser or a resumable subscriber. An authorized replay protocol may begin from a later cursor and must use an explicit snapshot/resume contract rather than pretending this from-start test covers reconnection.
The lab validates our normalized terminal event. A real provider adapter must still distinguish success, length-limited output, refusal and failure before producing that event; [DONE] alone does not perform that translation. Partial output persistence, cancellation during blocked sends, slow clients and session changes require additional integration/browser tests.
Atomic publication
Question: can a promotion leave new entities behind when writing the evidence or publication event fails?
The transaction lab creates an in-memory SQLite database and binds a review to a SHA-256 digest of the exact synthetic proposal. Publication checks the base revision, records canonical rows and evidence, advances the revision, stores an idempotency receipt, and appends an event in one transaction. An injected exception after claim insertion must roll all of it back.
python3 docs/examples/publication.pyInspect the SQLite harness and its eight tests
"""Original SQLite transaction lab, not the application backend or a full ontology.
Uses synthetic records and an in-memory database. Review authentication, media storage,
canonical entity resolution and crash/disk-failure recovery are intentionally out of scope.
"""
from copy import deepcopy
import hashlib
import json
import sqlite3
import unittest
def digest(proposal: dict) -> str:
# A defined Python fixture encoding, NOT a claim of cross-language canonical JSON.
encoded = json.dumps(proposal, sort_keys=True, separators=(",", ":"),
ensure_ascii=False, allow_nan=False).encode("utf-8")
return hashlib.sha256(encoded).hexdigest()
def database() -> sqlite3.Connection:
db = sqlite3.connect(":memory:", isolation_level=None)
db.execute("PRAGMA foreign_keys = ON")
db.executescript("""
CREATE TABLE graph_state(id INTEGER PRIMARY KEY CHECK(id=1), revision INTEGER NOT NULL);
INSERT INTO graph_state VALUES(1,0);
CREATE TABLE entities(id TEXT PRIMARY KEY, kind TEXT NOT NULL);
CREATE TABLE aliases(entity_id TEXT REFERENCES entities(id), name TEXT, scope TEXT,
PRIMARY KEY(entity_id,name,scope));
CREATE TABLE claims(id TEXT PRIMARY KEY, subject TEXT REFERENCES entities(id),
predicate TEXT, object_text TEXT, qualifiers TEXT);
CREATE TABLE evidence(id TEXT PRIMARY KEY, claim_id TEXT REFERENCES claims(id),
source_id TEXT, locator TEXT,
UNIQUE(claim_id,source_id,locator));
CREATE TABLE publications(request_key TEXT PRIMARY KEY, digest TEXT, revision INTEGER);
CREATE TABLE events(cursor INTEGER PRIMARY KEY AUTOINCREMENT, revision INTEGER, kind TEXT);
""")
return db
TABLES = {
"entities": ("id", "kind"),
"claims": ("id", "subject", "predicate", "object_text", "qualifiers"),
"evidence": ("id", "claim_id", "source_id", "locator"),
}
def insert_or_verify(db: sqlite3.Connection, table: str, row: dict) -> None:
fields = TABLES[table]
values = tuple(row[field] for field in fields)
existing = db.execute(f"SELECT {','.join(fields)} FROM {table} WHERE id=?", (row["id"],)).fetchone()
if existing is not None:
if tuple(existing) != values:
raise ValueError("stable ID conflicts with different content")
return
db.execute(f"INSERT INTO {table} ({','.join(fields)}) VALUES ({','.join('?' for _ in fields)})", values)
def publish(db: sqlite3.Connection, proposal: dict, reviewed_digest: str,
request_key: str, *, inject_failure: bool = False) -> int:
current_digest = digest(proposal)
if current_digest != reviewed_digest:
raise ValueError("review no longer matches the proposal")
if not request_key.strip():
raise ValueError("request key required")
db.execute("BEGIN IMMEDIATE")
try:
previous = db.execute("SELECT digest,revision FROM publications WHERE request_key=?",
(request_key,)).fetchone()
if previous:
if previous[0] != current_digest:
raise ValueError("request key conflicts with a different request")
db.execute("COMMIT")
return previous[1]
revision = db.execute("SELECT revision FROM graph_state WHERE id=1").fetchone()[0]
if revision != proposal["base_revision"]:
raise ValueError("stale graph revision; review again")
for row in proposal["entities"]:
insert_or_verify(db, "entities", row)
for alias in proposal["aliases"]:
db.execute("INSERT OR IGNORE INTO aliases VALUES(?,?,?)", tuple(alias))
for row in proposal["claims"]:
insert_or_verify(db, "claims", row)
if inject_failure:
raise RuntimeError("synthetic fault after claim insertion")
for row in proposal["evidence"]:
insert_or_verify(db, "evidence", row)
next_revision = revision + 1
db.execute("UPDATE graph_state SET revision=? WHERE id=1", (next_revision,))
db.execute("INSERT INTO publications VALUES(?,?,?)", (request_key, current_digest, next_revision))
db.execute("INSERT INTO events(revision,kind) VALUES(?,?)", (next_revision, "graph.published"))
db.execute("COMMIT")
return next_revision
except Exception:
db.execute("ROLLBACK")
raise
def fixture() -> dict:
return {
"base_revision": 0,
"entities": [{"id": "person-a", "kind": "person"}, {"id": "person-b", "kind": "person"}],
"aliases": [["person-a", "Alex Lee", "en"], ["person-b", "Alex Lee", "en"]],
"claims": [{"id": "claim-1", "subject": "person-a", "predicate": "reported_color",
"object_text": "red", "qualifiers": '{"status":"reported"}'}],
"evidence": [{"id": "evidence-1", "claim_id": "claim-1", "source_id": "synthetic-report-1",
"locator": "chars:0:26"}],
}
class PublicationTests(unittest.TestCase):
def setUp(self):
self.db = database()
self.addCleanup(self.db.close)
self.proposal = fixture()
def test_alias_is_not_globally_unique(self):
publish(self.db, self.proposal, digest(self.proposal), "request-1")
self.assertEqual(self.db.execute("SELECT count(*) FROM aliases WHERE name='Alex Lee'").fetchone()[0], 2)
def test_repeated_delivery_does_not_repeat_publication(self):
self.assertEqual(publish(self.db, self.proposal, digest(self.proposal), "request-1"), 1)
self.assertEqual(publish(self.db, self.proposal, digest(self.proposal), "request-1"), 1)
self.assertEqual(self.db.execute("SELECT count(*) FROM events").fetchone()[0], 1)
def test_changed_request_key_is_rejected(self):
publish(self.db, self.proposal, digest(self.proposal), "request-1")
changed = deepcopy(self.proposal)
changed["claims"][0]["object_text"] = "blue"
with self.assertRaisesRegex(ValueError, "request key conflicts"):
publish(self.db, changed, digest(changed), "request-1")
def test_review_is_bound_to_exact_fixture_content(self):
reviewed = digest(self.proposal)
self.proposal["claims"][0]["object_text"] = "blue"
with self.assertRaisesRegex(ValueError, "review no longer"):
publish(self.db, self.proposal, reviewed, "request-1")
def test_stale_revision_requires_review(self):
publish(self.db, self.proposal, digest(self.proposal), "request-1")
with self.assertRaisesRegex(ValueError, "stale graph"):
publish(self.db, self.proposal, digest(self.proposal), "request-2")
def test_failure_rolls_back_records_revision_and_event(self):
with self.assertRaisesRegex(RuntimeError, "synthetic fault"):
publish(self.db, self.proposal, digest(self.proposal), "request-1", inject_failure=True)
for table in ["entities", "aliases", "claims", "evidence", "publications", "events"]:
self.assertEqual(self.db.execute(f"SELECT count(*) FROM {table}").fetchone()[0], 0)
self.assertEqual(self.db.execute("SELECT revision FROM graph_state").fetchone()[0], 0)
def test_new_review_does_not_duplicate_existing_evidence(self):
publish(self.db, self.proposal, digest(self.proposal), "request-1")
changed = deepcopy(self.proposal)
changed["base_revision"] = 1
publish(self.db, changed, digest(changed), "request-2")
self.assertEqual(self.db.execute("SELECT count(*) FROM evidence").fetchone()[0], 1)
def test_same_entity_id_cannot_change_kind_silently(self):
publish(self.db, self.proposal, digest(self.proposal), "request-1")
changed = deepcopy(self.proposal)
changed["base_revision"] = 1
changed["entities"][0]["kind"] = "vessel"
with self.assertRaisesRegex(ValueError, "stable ID conflicts"):
publish(self.db, changed, digest(changed), "request-2")
if __name__ == "__main__":
unittest.main(verbosity=2)The two people named Alex Lee deliberately have distinct IDs and the same alias. Their names do not determine identity. A second delivery of one request does not append another publication event. The same request key with changed content is a conflict; changed proposal content invalidates its old review.
This fixture's JSON encoding is explicitly Python-defined; it is not a cross-language canonicalization standard. A production wire contract needs test vectors for its chosen encoding and hash rules. The minimal evidence rows use synthetic source IDs and locators; they do not prove source-object existence or integrity. The real publisher must additionally verify rights, visibility, immutable source objects, all endpoints, actor permissions, schema versions and publication scope.
How an IS373 review uses these examples
Show a classmate one prediction, the command you ran, and what changed when you made a deliberate repair. Link the requirement and the donor revision you examined. End with one integration question the example leaves open. A passing in-memory transaction, for instance, leaves disk and crash recovery to a different test.
The roadmap assigns each remaining proof to a specific implementation slice. These examples are maintained documentation: CI compiles/runs them alongside the site build.