Skip to content

feat(postgres): define driver-neutral migration port - #323

Draft
seonghobae wants to merge 241 commits into
fix/python-support-matrix-b84f0c9from
feat/commercial-postgres-driver-port-b84f0c9
Draft

feat(postgres): define driver-neutral migration port#323
seonghobae wants to merge 241 commits into
fix/python-support-matrix-b84f0c9from
feat/commercial-postgres-driver-port-b84f0c9

Conversation

@seonghobae

@seonghobae seonghobae commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Addresses #322 through the existing PostgreSQL-driver migration stack without claiming commercial-license completion.

Exact current boundary

  • protected main: 5913c4bad79d6bc29d7cc1c624abb7db2ea6a77c (ci(actions): consolidate pull request workflows #335 merged);
  • exact predecessor/base: fix/python-support-matrix-b84f0c9@8de00aee07cf5a0a32d091f6b4819de2e5849bbd;
  • exact current head: 8cfba1d920f8079ea252e4a013be22e8d2aecd43;
  • state: Draft/open/mergeable;
  • pyproject.toml / uv.lock still retain Psycopg as the production default, so this branch is not commercial-license clean.

No force push, destructive rebase, protected-main direct write, predecessor-evidence transfer, mutable production dependency, self-approval, or gate weakening is used.

Driver-neutral migration boundary

This lane establishes PostgresDriverPort plus the retained PsycopgDriverAdapter so a permissively licensed replacement can be verified against the repository's real PostgreSQL contract before runtime promotion. Candidate-only pg8000 1.31.5 evidence covers parameter binding, tuple-row normalization, finite fetch budgets, exact/unknown row counts, transaction/context ownership, terminal connection state, thread-affine use, PostgreSQL RLS/session behavior, UUID/timestamp round-trip, SQLSTATE 42883 classification, recovery cleanup, JSONB adaptation, exact candidate dependency hashes, license/vulnerability pre-admission, strict single-host URI/keyword conninfo parsing, explicit service-file resolution without ambient PGSERVICEFILE discovery, and the packaged restore-catalog acceptance query. Unsupported multi-host/socket/query/LDAP/ambient service semantics remain fail closed rather than approximated.

The centralized runtime selector still constructs PsycopgDriverAdapter until the replacement is fully admitted. This is migration architecture, not final license replacement.

Service-file authority RED → GREEN lineage

Fresh source review first found that the caller-selected candidate pg_service.conf path used Path.open("rb") before proving file type. A FIFO or device could therefore block before the 64 KiB read budget applied, or supply bytes through a non-regular filesystem capability while being treated as service-file authority.

  • RED 857b0923bc510aaa14607348d587985bfea85e72 requires a nonblocking descriptor open where supported and rejection of a non-regular retained descriptor.
  • Production GREEN c88a36f7c43bd58e487a032903d88cb0f927f9ae opens the explicit path with read-only/nonblocking/close-on-exec/binary flags where available, proves the retained descriptor is regular before consuming bytes, and keeps the strict finite read/UTF-8/content-free error contract.
  • Test-only 8a816deb407c23dff3c0c84726656acf68491741 covers descriptor read failure, close-only failure, and preservation of a primary descriptor failure when cleanup also fails.

A second exact-source review then found a TOCTOU boundary: proving regular-file identity only before the bounded read did not reject in-place mutation while connection-selector bytes were being retained.

  • RED e33d622664fcc1b584be3b08915a978d860efdf0 deterministically changes retained descriptor metadata between inspection points and requires fail-closed rejection.
  • GREEN 5cf3c5778c06a275ee232f10eb864f281463a4f2 snapshots device/inode/mode/size/mtime/ctime before the read, re-observes the same retained descriptor afterward, requires exact metadata stability and byte-count agreement, and only then permits parsing. Path replacement cannot redirect the retained descriptor, and in-place mutation observed across the bounded read does not become connection-selector authority.

The repairs do not add ambient service lookup, LDAP/network lookup, production pg8000 dependency authority, or new service precedence semantics.

Restore-catalog candidate parity

Current head 8cfba1d920f8079ea252e4a013be22e8d2aecd43 adds a real-PostgreSQL candidate probe for the production inspect_postgres_restore_catalog() boundary. The exact pg8000 artifact must execute the packaged catalog query that binds finite Python lists through ANY(%s) and return the required catalog tuple/boolean semantics, two authenticated lifecycle indexes, and forced-RLS evidence. This closes a candidate-parity gap that adapter unit tests could not prove; it does not promote pg8000 into the production dependency graph or claim logical-restore completion by itself.

Exact-current validation / central owner path

Fresh exact-head workflows are non-passing:

  • CI 33914978050: queued;
  • Release Acceptance 33914978044: queued.

CI materialized seven jobs for exact 8cfba1d9...; all are pre-checkout with steps=[], labels=[ubuntu-latest], runner_id=0, and no assigned runner/group. Representative jobs are PostgreSQL/container 101159943718, coverage/package 101159943903, and Python 3.14 101159944009. The superseding exact-current specimen was advanced to the existing central runner owner .github#712 as comment 5545939374. Earlier runner evidence is predecessor-only now.

No remote GREEN is claimed until exact-current jobs acquire runners, prove checkout identity, and execute required repository/security/release gates. The leaf source must not be churned merely to retrigger allocation.

Descendant convergence

Documentation child #321 was non-force converged after this parent moved. Current child docs/public-surface-metadata@efa2b1206789a97548a8af151e2b47e5ceb75418 has merge base exactly 8cfba1d920f8079ea252e4a013be22e8d2aecd43, is behind 0, and retains only README.md plus docs/index.md as its relative semantic delta. No predecessor checks/reviews transfer.

Context Fabric / release boundary

Fresh GitHub release inventories remain empty for ContextualWisdomLab/context-graph-contracts, ContextualWisdomLab/enterprise-architecture-core, and ContextualWisdomLab/pg-llm-batch. Mutable producer PR heads remain candidate/test-only evidence and are never production dependency authority. Context Fabric consumer readiness remains owned by #319 while immutable upstream publication is absent.

Merge boundary

Keep Draft. Merge only after dependency ancestry is current, a commercially compatible replacement is fully admitted, the final unchanged head removes the disallowed runtime graph, package/lock/SBOM/license/provenance evidence is regenerated, exact-head CI/security/SAST/coverage/docstrings/release plus realistic PostgreSQL behavior pass, every valid current finding is resolved, and then-live protected governance is satisfied. No predecessor GREEN, routine bypass, or mutable dependency is accepted.

@coderabbitai

coderabbitai Bot commented Sep 2, 2026

Copy link
Copy Markdown

Review Change Stack

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
📝 Walkthrough

Walkthrough

PostgreSQL 접근을 PostgresDriverPort로 추상화했습니다. Psycopg 및 pg8000 어댑터와 후보 평가기를 추가했습니다. 데이터베이스, CLI, Compose, 헬스 체크 및 토큰 카운터가 주입된 드라이버를 사용합니다. CI는 후보 런타임 스모크 테스트를 실행합니다.

Changes

PostgreSQL 드라이버 계약과 어댑터

Layer / File(s) Summary
드라이버 포트와 어댑터
pg_llm_batch/postgres_driver_port.py, pg_llm_batch/psycopg_driver_adapter.py, pg_llm_batch/pg8000_driver_candidate_adapter.py, tests/test_postgres_driver_port.py, tests/test_psycopg_driver_adapter.py, tests/test_pg8000_driver_candidate_adapter.py
커서, 연결, 트랜잭션, conninfo, JSONB, 결과 행 및 오류 분류 계약을 추가했습니다. Psycopg 및 pg8000 어댑터와 계약 테스트를 추가했습니다.
드라이버 후보 증거 평가
pg_llm_batch/postgres_driver_candidate.py, tests/test_postgres_driver_candidate*.py, tests/test_postgres_driver_connection_context_contract.py
후보 증거의 형식, 불변성, provenance, 라이선스, 취약점, Python 버전 및 capability를 검증합니다. 평가 결과는 production 승인을 항상 거부합니다.

애플리케이션 데이터베이스 경로

Layer / File(s) Summary
저장소와 원격 상태 처리
pg_llm_batch/checkpoint_store.py, pg_llm_batch/config.py, pg_llm_batch/db.py, tests/test_checkpoint_store_driver_port.py, tests/test_config_driver_port.py, tests/test_db.py, tests/test_postgres_driver_remote_lifecycle.py, tests/test_postgres_driver_review_contracts.py
체크포인트, 설정, 비밀값 및 원격 상태 작업이 주입된 드라이버로 연결, tenant scope 및 row count 처리를 수행합니다.
오케스트레이터와 토큰 카운터 통합
pg_llm_batch/orchestrator.py, pg_llm_batch/token_counter.py, tests/test_orchestrator_driver_port.py, tests/test_token_counter_driver_port.py
오케스트레이터와 토큰 카운터가 연결, autocommit, JSONB, 모델 메타데이터 및 undefined-function 분류를 드라이버에 위임합니다. BatchAccumulator 인터페이스도 변경했습니다.

CLI, Compose, 헬스 및 후보 런타임

Layer / File(s) Summary
외부 경계의 드라이버 전달과 오류 제한
pg_llm_batch/cli.py, pg_llm_batch/compose_bootstrap.py, pg_llm_batch/health.py, tests/test_cli_postgres_driver_port.py, tests/test_compose_bootstrap_driver_port.py, tests/test_health*.py
CLI DSN 검증과 Compose DSN 생성을 선택된 드라이버로 수행합니다. 헬스 체크는 5초 연결 제한을 사용하고 데이터베이스 예외 세부 정보를 고정 메시지로 대체합니다.
pg8000 CI 스모크 검증
.github/workflows/ci.yml, tests/smoke_pg8000_candidate_postgres.py, tests/test_pg8000_driver_candidate_error_precedence.py, tests/test_pg8000_driver_candidate_fetch_bound.py, tests/test_workflow_contracts.py
CI가 고정된 pg8000 후보 아티팩트를 검증하고 PostgreSQL 컨테이너에서 DB-API, RLS, 타입 변환, rollback 및 정리 동작을 실행합니다.

Estimated code review effort: 5 (Critical) | ~120 minutes

Merge Risk: 🔵 Low · up to 162f6

The candidate-only dependency safeguard can be bypassed by a case-variant package name, allowing future runtime dependency drift to escape this check. Normalize package names before comparing them.

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant PostgresDriverPort
  participant PostgresBatchOrchestrator
  participant PostgresConnectionPort
  participant PostgresCursorPort
  CLI->>PostgresDriverPort: parse_conninfo(dsn)
  CLI->>PostgresBatchOrchestrator: create with postgres_driver
  PostgresBatchOrchestrator->>PostgresDriverPort: connect(dsn)
  PostgresDriverPort->>PostgresConnectionPort: return connection
  PostgresBatchOrchestrator->>PostgresConnectionPort: set_autocommit(False)
  PostgresConnectionPort->>PostgresCursorPort: execute(query, params)
  PostgresBatchOrchestrator->>PostgresDriverPort: jsonb(payload)
  PostgresConnectionPort->>PostgresConnectionPort: commit()
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 48.78% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 449 functions across 35 files. (1 skipped… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed PR 제목은 PostgreSQL 드라이버 중립 마이그레이션 포트 정의라는 주요 변경을 정확하고 간결하게 설명합니다.
Full details: Docstring Coverage

Explanation

Docstring coverage is 48.78% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 449 functions across 35 files. (1 skipped: 1 unsupported.)

✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/commercial-postgres-driver-port-b84f0c9

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@seonghobae seonghobae added enhancement New feature or request priority: high status: draft Draft pull request type: feature New or expanded product capability labels Sep 2, 2026 — with ChatGPT Codex Connector
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request priority: high status: draft Draft pull request type: feature New or expanded product capability

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant