KB-E6A1

dot-iu-cutter v0.4 Real DB Adapter — Code Review Evidence (2026-05-17)

20 min read Revision 1
dot-iu-cutterv0.4db-adaptercode-reviewevidencedieu44

dot-iu-cutter v0.4 — Real DB Adapter Code Review Evidence

Date: 2026-05-17 Cycle: v0.4 Real DB Adapter — code-review evidence collection (read-only) Controlling file: knowledge/dev/laws/dieu44-trien-khai/reviews/dot-iu-cutter-v0.4-real-db-adapter-code-authoring-gpt-interim-review-2026-05-17.md Boundaries honoured: evidence collection only — no code change, no new commit, no DB connection, no secret read, no .env edit, no dry-run, no CUT/VERIFY, no deploy.


1. Git state

Item Value
Branch main
HEAD 56d3732cb74d07546c938242180a434ed1067a9a
Parent 689e53efa814f8dc9e30f3d95bcf8622c55d7250 (v0.4 dry-run-safe skeleton [DESIGN PASS])

git show --stat HEAD:

56d3732 feat(iu-cutter): v0.4 RealPostgresAdapter drop-in (code authoring, no prod)
 iu-cutter/cutter_agent/db_adapter.py          | 709 +++++++++++++++++++++++++-
 iu-cutter/tests/test_real_postgres_adapter.py | 527 +++++++++++++++++++
 2 files changed, 1234 insertions(+), 2 deletions(-)

git diff-tree --no-commit-id --name-only -r HEAD (exact files in the commit):

iu-cutter/cutter_agent/db_adapter.py
iu-cutter/tests/test_real_postgres_adapter.py

Scoped confirmation: the HEAD commit changed exactly two intended files; db_adapter.py net +707 / −2 (the only base edits are 2 additive lines: self._phase = None; optional transaction(phase=None)), test file new (+527).

git status --short (whole repo):

 M bin/dot-birth-trigger-setup
 M bin/dot-context-pack-build.sh
 M bin/dot-vector-audit
?? bin/dot-dot-health.bak.b3f1c-g.20260514T061811Z
?? bin/dot-search-canary
?? specs/

Explanation: these are pre-existing, unrelated working-tree items under bin/ and specs/ — outside iu-cutter/, not staged, not part of 56d3732, and untouched by this cycle. iu-cutter/ does not appear in git status at all → the iu-cutter working tree is clean and identical to HEAD, which independently proves no code was modified during evidence collection.

2. Blob integrity (SHA256)

File Working tree Committed blob (git cat-file blob HEAD:…) Local authoring copy
iu-cutter/cutter_agent/db_adapter.py 2a6ca4f1…2b4330 2a6ca4f1…2b4330 2a6ca4f1…2b4330
iu-cutter/tests/test_real_postgres_adapter.py 78b48525…132741 78b48525…132741 78b48525…132741

Full digests:

  • db_adapter.py = 2a6ca4f12869695ea42c4d9e2d8e6465bc0e59b0ec8b22ae2ae6d9280a2b4330
  • test_real_postgres_adapter.py = 78b48525d1d6a2162f7cd290fab65deadd79f43b86d8e3c116439a6621132741

Git blob OIDs: db_adapter.py a2c82303a289ef28fc98dec6ca2228546e4b0dc9; test e791b0b9c17b36fc504497b11a6ade7dd6dbba1f.

Result: triple match for both files — working tree == committed blob == local authoring copy (/Users/nmhuyen/iu-cutter-build/). No drift. Local authoring copy: present (compared, identical) — not N/A.

3. Source evidence (excerpts from the committed blob; line numbers in db_adapter.py, 948 lines total)

_Secret redaction (L104–120):

class _Secret:
    __slots__ = ("_v",)
    def __init__(self, value: str) -> None: self._v = value
    def reveal(self) -> str: return self._v
    def __repr__(self) -> str: return "<redacted-secret>"
    __str__ = __repr__

Connection config loading — fail-closed, principal-scoped, no DSN (L574–607):

def load_connection_config(principal, env=None) -> ConnectionConfig:
    if principal not in _PRINCIPAL_ENV_KEYS:
        raise PrincipalCapabilityError(...)
    e = env if env is not None else os.environ
    user_key, pwd_key = _PRINCIPAL_ENV_KEYS[principal]   # this principal ONLY
    def _req(key):
        val = e.get(key)
        if val is None or str(val).strip() == "":
            raise ConfigMissing(f"required connection env key {key} is missing/empty (fail-closed; no default, no fallback)")
        return str(val)
    host=_req("DOT_CUTTER_DB_HOST"); port=_req("DOT_CUTTER_DB_PORT")
    dbname=_req("DOT_CUTTER_DB_NAME"); sslmode=_req("DOT_CUTTER_DB_SSLMODE")  # config-driven, NOT hardcoded
    user=_req(user_key); password=_Secret(_req(pwd_key))
    return ConnectionConfig(principal, host, port, dbname, sslmode, user, password)

ConnectionConfig — discrete kwargs, no DSN/URL, redacted repr (L547–569):

def connect_kwargs(self):
    return {"host":…, "port":…, "dbname":…, "user":…,
            "password": self._password.reveal(), "sslmode": self.sslmode}  # no dsn/conninfo, no URL
def redacted_kwargs(self):
    d = self.connect_kwargs(); d["password"] = "<redacted>"; return d
def __repr__(self):
    return (f"ConnectionConfig(principal=…, host=…, port=…, dbname=…, "
            f"sslmode=…, user=…, password=<redacted-secret>)")

RealPostgresAdapter class + __init__ (no connect on construction) (L662–701):

class RealPostgresAdapter(DBAdapter):
    def __init__(self, principal=PRINCIPAL_EXEC, *, env=None, connection_provider=None):
        super().__init__(principal)
        self._assert_writer()                       # cutter_ro/privileged rejected
        self._config = load_connection_config(principal, env)   # fail-closed, NO connect
        self._provider = connection_provider or _default_provider
        self._pool = _ConnPool(self._provider, self._config.connect_kwargs, env)
        self._retry = RetryPolicy(env)
        self._conn = None; self._conn_broken = False
    def __repr__(self):  # config repr is redacted
        return f"RealPostgresAdapter(principal={self.principal!r}, config={self._config!r})"

Principal routing (L372–377, L428–438, L704–718):

PHASE_PRINCIPAL = {"MARK":PRINCIPAL_EXEC,"REVIEW":PRINCIPAL_EXEC,
                   "CUT":PRINCIPAL_EXEC,"VERIFY":PRINCIPAL_VERIFY}
def principal_for_phase(phase):  # KeyError -> PrincipalCapabilityError("unknown phase")
def assert_can_run_phase(self, phase):
    want = principal_for_phase(phase)
    if want != self.principal:
        raise PrincipalCapabilityError("…cross-phase credential reuse refused")
def _assert_can_insert(self, table):
    if table not in _PRINCIPAL_INSERT_TABLES.get(self.principal, frozenset()):
        raise PrincipalCapabilityError("…refusing BEFORE issuing SQL")

Transaction / isolation selection (L379–385, L741–760):

PHASE_ISOLATION = {"MARK":"READ COMMITTED","REVIEW":"READ COMMITTED",
                   "CUT":"SERIALIZABLE","VERIFY":"SERIALIZABLE"}
def isolation_for_phase(phase): return PHASE_ISOLATION.get(phase or "", "SERIALIZABLE")  # strict default
def _begin(self):
    conn = self._pool.acquire(); self._conn = conn
    conn.autocommit = False                                  # autocommit OFF
    level = isolation_for_phase(self._phase)
    conn.execute(f"SET TRANSACTION ISOLATION LEVEL {level}")  # first stmt of txn
    cur = conn.execute("SELECT current_user"); who = (cur.fetchone() or [None])[0]
    if who != self.principal:
        raise ConfigMismatch("connected identity … != bound principal …; aborting phase with no write")

SQLSTATE mapping (L463–487):

def classify_sqlstate(sqlstate):
    ss = (sqlstate or "").upper()
    if ss == "42501": return Disposition(STOP, "privilege", ss)
    if ss == "23505": return Disposition(RESUME, "idempotency_collision", ss)
    if ss in ("23503","23502","23514"): return Disposition(STOP, "structural", ss)
    if ss.startswith("22"): return Disposition(STOP, "data_exception", ss)
    if ss in ("40001","40P01","55P03","57014"): return Disposition(RETRY, "transient", ss)
    if ss in ("53300","53400"): return Disposition(RETRY_BACKPRESSURE, "backpressure", ss)
    if ss.startswith("08"): return Disposition(RECONNECT_RETRY, "connection", ss)
    if ss in ("28P01","28000"): return Disposition(STOP, "credential", ss)
    return Disposition(STOP, "unknown", ss or "<none>")        # unknown -> STOP

Retry handling (L892–941) + connection-discard in _rollback (L770–789):

def run_phase(self, phase, work, *, sleep=time.sleep, rng=random.random):
    self.assert_can_run_phase(phase)
    attempt = 0
    while True:
        attempt += 1
        try:
            with self.transaction(phase=phase): return work(self)
        except (PrincipalCapabilityError, ConfigMismatch, ConfigMissing,
                WriteForbidden, AppendOnlyViolation, TransactionError):
            raise                                   # pre-SQL/structural: never retry
        except Exception as exc:
            ss = _sqlstate(exc)
            if ss is None: raise                    # non-DB error: propagate
            d = classify_sqlstate(ss)
            if d.disposition == STOP:  raise PhaseStop(d.sqlstate, d.error_class) from exc
            if d.disposition == RESUME: raise IdempotencyResume(...) from exc
            if attempt >= self._retry.max_attempts:  raise PhaseRetryExhausted(...) from exc
            sleep(self._retry.backoff_seconds(attempt,
                  backpressure=(d.disposition == RETRY_BACKPRESSURE), rng=rng))
# _rollback: exc = sys.exc_info()[1]; if SQLSTATE 08xx -> pool.discard(conn) else pool.release(conn)

ProductionDBAdapter refusal — preserved verbatim (L315–332):

class ProductionDBAdapter(DBAdapter):
    def __init__(self, *_a, **_k):
        raise ProductionAccessNotAuthorized(
            "v0.4 code-authoring: production DB writes are NOT authorized. "
            "This adapter intentionally refuses to connect. No DSN / env / secret is read. Dry-run only.")

No forbidden SQL helpers: delete()/truncate() inherited from base → raise AppendOnlyViolation (L198–202). RealPostgresAdapter defines only _begin/_commit/_rollback/_do_insert/_do_cas_status/_do_stamp_superseded/find/run_phase/assert_can_run_phase/_assert_can_insert/cross_check_grants/_safe_table. _do_insert builds parameterised INSERT; _do_cas_status builds column-scoped UPDATE … SET status=%s WHERE entry_id=%s AND status=%s (rowcount must == 1 else AppendOnlyViolation); _do_stamp_superseded builds UPDATE review_decision SET superseded_by_review_decision_id=%s WHERE …=%s AND … IS NULL and only for cutter_exec (else PrincipalCapabilityError). psycopg.types.json.Json used only when _HAVE_PSYCOPG (un-vendored). No CREATE/ALTER/DROP/GRANT/TRUNCATE/DELETE/COPY statement is ever constructed.

4. Test evidence

VPS — Python 3.12.3, full suite:

............................................................................................
Ran 92 tests in 0.020s
OK

(45 pre-existing + 47 new = 92, 0 fail / 0 error.)

Local parity — Python 3.11.6 (/Users/nmhuyen/iu-cutter-build/repo/iu-cutter): Ran 92 tests … OK (identical).

47 new tests (tests/test_real_postgres_adapter.py) by category:

  • TestConfigSuccess (2): fake_env_success, construction_does_not_connect
  • TestFailClosed (4): missing_key_fails_closed_naming_key, empty_key_fails_closed, adapter_construction_fails_closed, no_default_no_fallback
  • TestPrincipalScopedSecrets (3): exec_config_has_no_verify_password, exec_works_without_verify_keys, forbidden_principal_rejected
  • TestSecretRedaction (4): adapter_repr_no_secret, config_repr_no_secret, config_missing_error_has_no_value, redacted_kwargs_masks_password
  • TestKwargsNoDSN (1): discrete_kwargs_not_dsn
  • TestPrincipalRouting (5): phase_principal_map, unknown_phase_refused, exec_adapter_refuses_verify_phase, verify_adapter_refuses_cut_phase, capability_refuses_cross_principal_table
  • TestIsolationSelection (4): isolation_map, unknown_phase_strictest, begin_sets_isolation, begin_read_committed_for_mark
  • TestIdentityAssertion (1): current_user_mismatch_aborts
  • TestSqlstateMapping (1): mapping (20 codes incl. None)
  • TestRunPhaseRetry (7): stop_no_retry, transient_retry_then_exhaust, transient_retry_then_success, backpressure_longer_backoff_then_escalate, reconnect_discards_and_retries, idempotency_resume, run_phase_routes_principal
  • TestAppendOnlyAndDDL (5): delete_truncate_forbidden, no_ddl_or_grant_helpers, cas_rowcount_zero_raises, stamp_superseded_verify_principal_refused, unknown_table_refused
  • TestDropInBehaviour (4): insert_commit_rollback, rollback_on_exception, outside_txn_write_forbidden, no_autocommit_phase_write
  • TestNoProductionConnection (3): production_adapter_still_refuses, zero_connections_without_transaction, psycopg_optional
  • TestRetryPolicyKnobs (3): defaults, env_override_and_clamp, no_secret_pattern_in_module_source

5. Static boundary proofs (fixed-string grep on cutter_agent/db_adapter.py)

Pattern Result Explanation
/opt/incomex/docker/.env NONE no real .env path anywhere
open( NONE zero filesystem IO
dotenv NONE no dotenv lib
postgres:// NONE no DSN/URL literal
PGPASSWORD NONE no env-password literal
requests / urllib / http NONE no HTTP client
socket 5 hits benign: all in docstrings/comments ("no production socket", "before any socket is opened", "the socket is dead") — no import socket, no socket call
import socket / socket. NONE no socket usage
directus 1 hit (L10) benign: docstring listing forbidden principals "cutter_ro / workflow_admin / directus / postgres"
qdrant / asyncpg / psycopg2 NONE no other DB/vector client
subprocess / os.system NONE no shell-out
.env 5 hits benign: docstrings ("no real .env") + 3× os.environ (process env default, not a file)
DELETE / TRUNCATE 5 hits benign: docstrings + the AppendOnlyViolation refusal messages in delete()/truncate()/class doc
GRANT 1 hit (L667) benign: docstring "no DDL/GRANT/COPY/DELETE/TRUNCATE"
DROP / ALTER NONE no DDL

No SQL-mutating verb (DELETE/TRUNCATE/GRANT/DROP/ALTER/CREATE/COPY) is ever emitted; the only occurrences are documentation or the explicit append-only refusal text.

6. No production connection proof

  • All 47 tests inject a FakeProvider (connection counter) + fake fixture env. test_construction_does_not_connect / test_zero_connections_without_transaction assert prov.count == 0 after construction, repr, redacted_kwargs, assert_can_run_phase.
  • The only psycopg call-site is _default_provider (L614, # pragma: no cover), invoked only inside _pool.acquire() from _begin — never reached by any test (all use the fake) and never during construction.
  • _HAVE_PSYCOPG = False on the VPS (psycopg3 absent); test_psycopg_optional asserts _default_provider raises AdapterError(PSYCOPG_INSTALL_HINT) rather than connecting.
  • No socket/requests/urllib/http/psycopg2/asyncpg import or call (grep §5).

7. Secret handling proof

  • load_connection_config(principal, env) reads only the supplied Mapping; default fallback is os.environ (process env, never a file). Module has no open( and no .env path (grep §5) → no dotenv file read.
  • Principal-scoped: _PRINCIPAL_ENV_KEYS[principal] selects only that principal's USER/PASSWORD keys; a cutter_exec config never reads DOT_CUTTER_VERIFY_*. No single object holds both passwords (test_exec_config_has_no_verify_password, test_exec_works_without_verify_keys).
  • Password wrapped in _Secret (repr/str <redacted-secret>); ConnectionConfig.__repr__, RealPostgresAdapter.__repr__, redacted_kwargs(), and ConfigMissing carry key names only, never the value (TestSecretRedaction 4 tests + test_config_missing_error_has_no_value).
  • connect_kwargs() returns discrete keys only — set == {host,port,dbname,user,password,sslmode}, no dsn/conninfo, no value containing :// (test_discrete_kwargs_not_dsn). No DSN string with password is ever assembled.

8. Design conformance proof

Requirement Evidence
MARK/REVIEW/CUT → cutter_exec PHASE_PRINCIPAL (L372–377); test_phase_principal_map
VERIFY → cutter_verify same; test_verify_adapter_refuses_cut_phase, test_exec_adapter_refuses_verify_phase
READ COMMITTED for MARK/REVIEW PHASE_ISOLATION (L380–385); test_isolation_map, test_begin_read_committed_for_mark
SERIALIZABLE for CUT/VERIFY same; test_begin_sets_isolation; unknown/None → SERIALIZABLE (test_unknown_phase_strictest)
42501 → STOP classify_sqlstate (L469); test_stop_no_retry (no retry, prov.count==1); test_mapping
23505 → RESUME L471–474 → IdempotencyResume (test_idempotency_resume)
transient retry (40001/40P01/55P03/57014) L479–480 RETRY; test_transient_retry_then_{exhaust,success}
backpressure (53300/53400) longer backoff then escalate L481–482; test_backpressure_longer_backoff_then_escalate (hits cap ≥5s, then PhaseRetryExhausted)
08xxx discard + whole-phase retry _rollback L770–789 + run_phase; test_reconnect_discards_and_retries (fresh conn, old closed)
unknown SQLSTATE → STOP L487; test_mapping (99999, None → STOP)
one txn / phase, autocommit OFF _begin sets autocommit=False; nested → TransactionError; test_no_autocommit_phase_write
append-only, no DDL/GRANT delete/truncateAppendOnlyViolation; test_no_ddl_or_grant_helpers, test_delete_truncate_forbidden
ProductionDBAdapter still refuses L328–332; test_production_adapter_still_refuses + existing security tests

9. Limitations

  • RealPostgresAdapter is not wired into CutterRuntime (phases.py unchanged) — runtime binding deferred to a separate GPT-gated cycle.
  • Never executed against a real PostgreSQL: SERIALIZABLE behaviour, pg_advisory_xact_lock, real jsonb adaptation, SET TRANSACTION ISOLATION LEVEL server semantics proven only via the fake connection contract.
  • psycopg3 not installed on the VPS (_HAVE_PSYCOPG=False) — install is a future runtime-image concern; un-vendored by design.
  • cross_check_grants implemented (advisory information_schema.role_table_grants cross-check) but uncalled (no live connection this cycle).
  • A separately-authorized, GPT-reviewed PG-backed dry-run cycle remains required before any production binding.

10. Final statement

  • Evidence supports final GPT code PASS: the package satisfies every required_section of the interim review — scoped 2-file commit, triple SHA256 integrity, 92/92 on VPS + local parity, full design/secret/boundary conformance, ProductionDBAdapter refusal preserved.
  • Defect found: none. No code revision identified.
  • Code changed during evidence collection: noiu-cutter/ absent from git status (working tree clean == HEAD); working-tree, committed-blob and local-authoring SHA256 all match; no commit created; no DB connection, secret read, .env edit, dry-run, CUT/VERIFY, or deploy performed.

Next gate: GPT final code-review decision. Self-advance PROHIBITED — no runtime binding, no PG-backed dry-run, no CUT/VERIFY, no deploy until separately authorized.

Back to Knowledge Hub knowledge/dev/laws/dieu44-trien-khai/v0.4-db-adapter-code/dot-iu-cutter-v0.4-real-db-adapter-code-review-evidence-2026-05-17.md