# A worker can open SQLite successfully with foreign keys disabled

A queue worker can connect to a database and still accept a result for a job that does not exist. Foreign-key enforcement is set on each SQLite connection. If the writer and the verification script open different connections, checking one tells you nothing about the other.

Put the check in the connection factory used by every writer. Run it before the connection enters a transaction. The fixture below explicitly chooses opposite settings on two connections to the same temporary file, so it does not depend on the library's default.

```python
import sqlite3
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    db = Path(folder) / "jobs.db"
    guarded = sqlite3.connect(db, isolation_level=None)
    loose = sqlite3.connect(db, isolation_level=None)
    try:
        guarded.execute("PRAGMA foreign_keys = ON")
        loose.execute("PRAGMA foreign_keys = OFF")
        assert guarded.execute("PRAGMA foreign_keys").fetchone() == (1,)
        assert loose.execute("PRAGMA foreign_keys").fetchone() == (0,)

        guarded.execute("CREATE TABLE job(id INTEGER PRIMARY KEY)")
        guarded.execute(
            "CREATE TABLE result(job_id INTEGER NOT NULL REFERENCES job(id))"
        )
        try:
            guarded.execute("INSERT INTO result VALUES (999)")
        except sqlite3.IntegrityError:
            print("guarded connection rejected the orphan")
        else:
            raise AssertionError("guarded connection accepted the orphan")

        loose.execute("INSERT INTO result VALUES (999)")
        violations = guarded.execute("PRAGMA foreign_key_check").fetchall()
        assert len(violations) == 1 and violations[0][0] == "result"
        print("audit found one orphan written by the other connection")
    finally:
        loose.close()
        guarded.close()
```

For a worker pool, run the setup and read back `(1,)` whenever a new physical write connection is created. If the check fails, close that connection and fail before accepting work. An integration test can try writing a missing parent ID through the same connection path the worker uses.

Enabling checks on a connection leaves older rows in place. Audit existing data separately before assuming every result belongs to a job. The sample uses a temporary local file and deliberately makes a bad row. Both the rejection and audit were reproduced locally.

[SQLite documentation · Enabling foreign-key support](https://sqlite.org/foreignkeys.html#fk_enable)

AI assisted with drafting. The fixture uses synthetic rows and does not read a production database.
