Chương 03 — Kỹ nghệ OOP, Đánh đổi SQL/NoSQL, Nội tại PostgreSQL MVCC/Chỉ mục & SQLAlchemy 2.0
Từ SOLID/Repository/UoW, 5 Nhóm SQL (DDL/DML/DQL/DCL/TCL) & Phim cách ly Write Skew SSI (40001) đến HOT Update (100% vs 0%), VACUUM/XID, UUIDv7 (-94.7% WAL), Covering B-Tree + Keyset Pagination (21.6x), N+1 -> selectinload (101->2 SQL), PgBouncer & pgvector HNSW iterative_scan.
Unit ID:
T2-P1-U03
Track & Part: Track 2 (EDAI) — Part 1: Software, Backend & Container Engineering Foundations (part-01-software-systems-foundations)
Truy xuất Giáo trình Gốc (R25): Bài 3 Fundamentals of Engineering — Database (OOP for engineering,Database concepts,SQL and NoSQL databases,SQL command groups: DDL, DML, DQL, DCL and TCL,Optimization techniques: cost and performance,Setup SQL database and practice SQL queries,SQLAlchemy ORM) trong 02-track-edai-raw-curriculum.md và đề cương nâng cấp 02-track-2-edai-sota-syllabus.md
Bài thực hành Song hành (Lab 03):labs/lab-03-postgres-sqlalchemy-optimization/(db_internals_lab)
Tình huống Mở đầu: Năm Thảm họa Cơ sở Dữ liệu Làm Sập Dịch vụ AI Sản xuất#
Trong giáo trình nhập môn, cơ sở dữ liệu thường được dạy qua vài câu SELECT * FROM users và một lớp ORM sinh tự động. Ở quy mô sản xuất phục vụ hàng chục nghìn yêu cầu mỗi giây hoặc hàng trăm triệu vector embedding cho hệ thống RAG, sự thiếu hiểu biết về cơ chế trang 8 KiB, khóa hàng đợi và giao thức driver ORM biến những câu lệnh tưởng chừng vô hại thành năm thảm họa hạ tầng kinh điển:
- Khuếch đại Ghi
Non-HOT& Bão WAL Full-Page Images (Sự cố Uber Engineering): MỗiUPDATEtrên bảng có4chỉ mục nếu chạm vào cột được đánh chỉ mục hoặc trang8 KiBđã đầy (fillfactor = 100) buộc PostgreSQL phải viết lại toàn bộ4chỉ mục phụ (4,000lần ghi chỉ mục trên1,000lầnUPDATEtrong Lab 03 — so với0lần ghi chỉ mục cập nhật khi đạt100.0%HOTởfillfactor = 75!) và phát8 KiBFull-Page Images vào WAL sau mỗi checkpoint, bóp nghẹt IOPS SSD và băng thông nhân bản. - Ngạt
Autovacuum& Đóng băng Toàn cụm DoXID Wraparound(Sentry 2015 & Mailchimp/Mandrill40h 34m2019): Một phiên giao dịch bỏ quên ở trạng tháiidle in transactiongiữ ghim chân trờiGlobalXmin, khiếnVACUUMkhông thể thu hồi tuple chết và đóng băng Transaction ID 32-bit. Khi tuổiage(datfrozenxid)vượt ngưỡng \(2^{31}\) (~2.147 tỷ), PostgreSQL buộc phải tự ngắt toàn bộ quyền ghi để bảo vệ dữ liệu khỏi biến mất âm thầm. - Dồn Hàng đợi Khóa FIFO
ACCESS EXCLUSIVETừ Một LệnhALTER TABLE(GoCardless): Một lệnhALTER TABLE ... ADD CONSTRAINTchạy trên bảng gần như rỗng nhưng thiếulock_timeoutđứng xếp hàng chờ sau một câuSELECTphân tích dài60 giây. Do hàng đợi khóa FIFO của PostgreSQL, 100% lưu lượngSELECT/INSERTcủa API phía sau bị chặn đứng dây chuyền, làm cạn sạch bể kết nối ứng dụng chỉ trong vài giây. - Bão Truy vấn
N+1, Cạnmax_connections& Va chạm Prepared Statement trênPgBouncer: Vòng lặp đọcorder.itemstrên100đơn hàng vớilazy="select"âm thầm bắn101lượt khứ hồi SQL (152.19 msở RTT1.5 msthay vì3.55 msvớiselectinload), còn500kết nối trực tiếp từ các pod FastAPI đâm sầm vàomax_connections = 200(ngốn1,700 MiBRAM backend và từ chối300kết nối) hoặc làmasyncpgsập vớiDuplicatePreparedStatementErrorkhi chạy sauPgBouncerchế độ giao dịch. - Phân mảnh
UUIDv4, Thoái hóaOFFSETTuyến tính & Sụp đổ RecallpgvectorHNSW: Chèn khóa chính ngẫu nhiênUUIDv4làm lá B-Tree phình rỗng (71.4%vs89.6%vớiUUIDv7), kéo tỷ lệ trúng cache từ98.9%xuống64.7%và thổi phồng WALFPItừ0.91 MiBlên17.17 MiB(+1,787%); phân trangOFFSET 15000chậm hơn23.5xso với Keyset Seek; và lọc đa khách hàngWHERE tenant_id = 42(s = 2%) sau HNSWef_search = 40làmRecall@10rơi tự do về0.20(2/10kết quả) trước khi đượchnsw.iterative_scancứu về1.00.
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn tất Chương 03 và gói thực hành db_internals_lab, kỹ sư Dữ liệu & AI có đủ năng lực để:
- Thiết kế Kiến trúc OOP Tách lớp Bền vững (
SOLID,Protocol,Repository,Unit of Work): Vận dụng 5 nguyên lý SOLID cho tầng lưu trữ AI/Dữ liệu, phân biệt rạch ròityping.Protocol(structural typing, PEP 544) vớiabc.ABC, xây dựngRepository+Unit of Workkhép kín giao dịch (tự độngrollbackkhi có ngoại lệ hoặc quêncommit), và áp dụng mẫu Transactional Outbox loại bỏ hoàn toàn lỗi ghi kép (dual-write). - Đánh đổi Hệ quản trị Dữ liệu Theo Bản chất Lưu trữ & Giả thuyết RUM: Phân tích định lượng mô hình hàng
NSMvs. cộtDSM/PAX(tính toán lãng phí cache line64 B, nén RLE/Dictionary, SIMD), đối chiếuPostgreSQLvs.MongoDB,Redis/Valkey,Cassandra/ScyllaDB(quorum \(R + W > N\), bẫy tombstone) vàpgvectorthông qua hệ phương trình khuếch đại đọc–ghi–không gian (\(RA, WA, SA\)) của B-Tree và LSM-Tree. - Làm chủ 5 Nhóm lệnh SQL (
DDL,DML,DQL,DCL,TCL) & Truy vấn Biểu cảm: Thành thạoTRUNCATEvs.DELETE,INSERT ... ON CONFLICT DO UPDATEchống race condition TOCTOU, thứ tự thực thi logic 9 bước củaSELECT, CTEMATERIALIZEDvs.NOT MATERIALIZED, hàm cửa sổ (tránh bẫyRANGEmặc định bằngROWS BETWEEN), nốiLATERAL, bảo mật hàngRLS(FORCE+InitPlan), vàSAVEPOINT(cùng giới hạn64subtransactionPGPROC). - Giải phẫu Nội tại PostgreSQL 16–18 (
8 KiBPage, MVCC, SSI, HOT,VACUUM& B-Tree/GIN/BRIN/HNSW): Đọc hiểu cấu trúc trang8192 B(PageHeaderData24 B,ItemIdData4 B,HeapTupleHeaderData23 B/24 B), thuật toán hiển thị snapshot (xmin,xmax,xip_list), tái hiện và chặn Write Skew (A5B) bằngSERIALIZABLESSI (SQLSTATE 40001), tối ưuHOT(fillfactor = 75), giám sát tuổi XID chốngXID Wraparound, vận dụngTidStore(PG 17) và Native Async I/O /uuidv7()/ B-Tree Skip Scan (PG 18), tính toán chiều cao B-Tree \(h = \lceil \log_B N \rceil\), và chọn chuẩn giữaCovering INCLUDE,Partial,GIN,BRINvàpgvectorHNSWhalfvec/iterative_scan. - Làm chủ
SQLAlchemy 2.0,PgBouncer& Di trú Không Thời gian chết (Alembic Expand–Contract): Lập trình ORM định kiểu tĩnh (DeclarativeBase,Mapped[],AsyncSession,expire_on_commit=False), khóa đứng bãoN+1bằnglazy="raise"+selectinload/joinedload(được kiểm chứng thực thi trực tiếp trênSQLAlchemy 2.xsqlite:///:memory:), cấu hình an toànNullPool+statement_cache_sizequaPgBouncer, thiết kế di trúCREATE INDEX CONCURRENTLY+lock_timeout+NOT VALID, xử lýSIGTERM/ đầu dò sẵn sàng--healthcheck, và kiểm chứng16/16capytesttrêndb_internals_lab.
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T2-P1-U03, R25)#
Nội dung Gốc (02-track-edai-raw-curriculum.md, R25) |
Nâng cấp Chuẩn SOTA 2026 (ch-03) |
Mục trong Chương 03 | Tạo tác & Kiểm thử (db_internals_lab) |
|---|---|---|---|
| 1. OOP for engineering | SOLID (SRP, OCP, LSP, ISP, DIP) trong tầng dữ liệu/AI; typing.Protocol (PEP 544) vs. abc.ABC (@runtime_checkable caveat); Repository + Unit of Work (fail-closed rollback + Identity Map + Transactional Outbox) |
Trụ cột 1 (§1.1) + Trụ cột 2 (§2.1) + Mermaid 1 | repository_and_uow.py (OrderRepositoryProtocol, UnitOfWorkProtocol, InMemoryUnitOfWork, SqliteUnitOfWork, PlaceOrderService), Test 1 |
| 2. Database concepts | Trang slotted 8 KiB (24 B page header, 4 B line pointer, 23/24 B tuple header, t_ctid, hint bits); MVCC Snapshot (xmin, xmax, xip_list); ANSI + Berenson isolation & Write Skew (A5B) vs. SSI (40001); HOT vs. Non-HOT (fillfactor); VACUUM/Autovacuum, PG 17 TidStore (20x RAM), PG 18 autovacuum_vacuum_max_threshold, Visibility Map & 32-bit XID Wraparound (\(2^{31}\)) |
Trụ cột 1 (§1.4) + Trụ cột 2 (§2.2) + Trụ cột 3 (Cases 1, 2) + Mermaid 2 + Widget 1 | mvcc_and_query_engine.py (MVCCPageEngine, simulate_isolation_anomalies, simulate_hot_vs_non_hot_updates, simulate_vacuum_and_xid_wraparound), Tests 3, 4, 5, 6 |
| 3. SQL and NoSQL databases | OLTP NSM vs. OLAP DSM/PAX (lãng phí cache line 64 B, Zone Map, RLE/Dict, SIMD); PostgreSQL vs. MongoDB vs. Redis/Valkey vs. Cassandra/ScyllaDB (\(R+W>N\) quorum) vs. pgvector; Giả thuyết RUM (\(RA, WA, SA\)) & B-Tree vs. LSM-Tree; Hybrid OLTP/OLAP (DuckDB, ClickHouse PeerDB CDC, Neon) |
Trụ cột 1 (§1.2) + Trụ cột 2 (§2.5) + Trụ cột 3 (Playbook A) | mvcc_and_query_engine.py (simulate_pgvector_filtered_recall), sql/001_schema_and_indexes.sql, Tests 10, 12 |
4. SQL command groups: DDL, DML, DQL, DCL, TCL |
DDL (TRUNCATE vs. DELETE, DDL giao dịch, FIFO ACCESS EXCLUSIVE, PG 11+ metadata DEFAULT, PG 18 NOT NULL NOT VALID); DML (INSERT ... ON CONFLICT, MERGE); DQL (9 bước thực thi, CTE MATERIALIZED/NOT MATERIALIZED, Window ROWS vs. RANGE, LATERAL); DCL (GRANT/REVOKE, RLS + InitPlan); TCL (BEGIN/SAVEPOINT 64 subxid trap/COMMIT) |
Trụ cột 1 (§1.3) + Trụ cột 2 (§2.1, §2.4) + Trụ cột 3 (Case 3) + Mermaid 1 | repository_and_uow.py (upsert_inventory_item, demonstrate_tcl_savepoint_and_ddl_truncate), sql/001_*.sql, sql/002_*.sql, Tests 2, 9, 12 |
| 5. Optimization techniques: cost and performance | B-Tree Lehman–Yao fanout \(B\) & chiều cao \(h\); quy tắc ESR & tiền tố trái nhất; Covering INCLUDE + Index-Only Scan (Heap Fetches); Partial, GIN (fastupdate), BRIN (1 MiB); PG 17 SAOP/Streaming I/O & PG 18 io_method AIO / Skip Scan; UUIDv7 vs. UUIDv4 WAL FPI; EXPLAIN (ANALYZE, BUFFERS), SARGability, Nested Loop / Grace Hash / Merge Join; Keyset vs. OFFSET \(\Theta(N^2/m)\); PgBouncer & pgvector iterative_scan |
Trụ cột 1 (§1.5) + Trụ cột 2 (§2.3–§2.4) + Trụ cột 3 (Cases 4, 5 + Playbook B) + Mermaid 3 + Widgets 2, 3 | mvcc_and_query_engine.py (compute_btree_geometry, simulate_uuid_v4_vs_v7, benchmark_sqlite_indexes_and_pagination, simulate_pgbouncer_pool_collapse), Tests 7, 8, 9, 10 |
6. Lab: Setup SQL DB, SQL queries & SQLAlchemy ORM |
Tạo tác PostgreSQL (sql/*.sql) + SQLAlchemy 2.0 (DeclarativeBase, Mapped[], lazy="raise", selectinload/joinedload, NullPool) + Alembic Expand–Contract kiểm định cả AST lẫn thực thi sqlite:///:memory:; gói db_internals_lab (sqlite3, sqlalchemy>=2.0, pydantic v2, numpy, pandas), uv.lock, SIGTERM & check_db_readiness |
Trụ cột 2 (§2.4) + Trụ cột 3 (Case 4 + Playbook C) + Trụ cột 4 (§4.1–§4.3) + Mermaid 3 + Widget 3 | sql/*.sql, sqlalchemy2_reference/models_and_uow.py, src/db_internals_lab/*, scripts/run_lab_demo.py, Tests 1..16 |
Bảng Ký hiệu Thống nhất Xuyên suốt Chương 03 (Unified Notation)#
| Ký hiệu | Miền / Kiểu | Định nghĩa Chính xác Trong Chương 03 & db_internals_lab |
Quy ước Phân biệt |
|---|---|---|---|
| \(P_{\text{sz}}, H_{\text{hdr}}\) | \(\mathbb{N}_+\) (Bytes) | Kích thước trang vật lý (8192 B = 8 KiB) và tiêu đề trang (24 B) / tiêu đề tuple (23 B \(\to 24\text{ B}\)) |
Không nhầm \(P_{\text{sz}}\) với số trang kết quả |
| \(x_{\min}, x_{\max}, \mathcal{X}_{\text{ip}}\) | \(\mathbb{Z}/2^{32}\mathbb{Z}\) | XID tạo tuple (t_xmin), XID xóa/cập nhật (t_xmax), danh sách XID đang chạy trong snapshot (xip_list) |
Phân biệt S.xmin/S.xmax của Snapshot với v.xmin/v.xmax của Tuple |
| \(c, B, h\) | \(\mathbb{N}_+\) | Số chỉ mục trên bảng (\(c\)), hệ số rẽ nhánh hiệu dụng B-Tree (\(B\)), chiều cao cây \(h = \lceil \log_B N \rceil\) | Phân biệt \(c\) (số index) với \(c_{\text{seq}}, c_{\text{rand}}\) (hệ số chi phí I/O) |
| \(\text{ff}, \rho_{\text{HOT}}\) | \((0, 100], [0, 1]\) | Hệ số điền đầy trang fillfactor (100 mặc định vs. 70–85) và tỷ lệ cập nhật HOT tại chỗ |
— |
| \(N, m, k\) | \(\mathbb{N}_{\ge 0}\) | Tổng số bản ghi trong bảng (\(N\)), kích thước trang đầu ra LIMIT (\(m\)), độ lệch OFFSET (\(k\)) |
— |
| \(RA, WA, SA\) | \(\mathbb{R}_{\ge 1}\) | Read / Write / Space Amplification theo Giả thuyết RUM | — |
| \(R, W, N_{\text{rep}}\) | \(\mathbb{N}_+\) | Số replica đọc (\(R\)), ghi (\(W\)), và hệ số nhân bản (\(N_{\text{rep}}\)) thỏa \(R + W > N_{\text{rep}}\) cho Quorum | Không nhầm \(W\) (write quorum) với \(W_{\text{row}}\) (độ rộng hàng byte) |
| \(d, m_{\text{hnsw}}, \text{ef}\) | \(\mathbb{N}_+\) | Số chiều vector embedding (\(d\)), bậc kết nối tối đa HNSW (\(m_{\text{hnsw}}\)), bề rộng chùm ef_search |
— |
| \(s, K_{\text{pool}}, C_{\text{app}}\) | \((0, 1], \mathbb{N}_+\) | Độ chọn lọc bộ lọc SQL (\(s\)), số kết nối backend PgBouncer (\(K_{\text{pool}}\)), số kết nối client (\(C_{\text{app}}\)) | — |
Trụ cột 1 — Nguyên lý Gốc: Kỹ nghệ OOP, Hệ sinh thái CSDL, 5 Nhóm lệnh SQL & Nội tại PostgreSQL#
1.1 Kỹ nghệ OOP Cho Tầng Dữ liệu: SOLID, typing.Protocol, Repository & Unit of Work#
Trong hệ thống dữ liệu và AI, OOP không phải nghệ thuật mô hình hóa phân cấp sinh học (Dog(Animal)), mà là kỹ thuật kiểm soát hướng phụ thuộc để logic nghiệp vụ, chấm điểm ML và kiểm thử tự động chạy hoàn toàn tách rời khỏi động cơ lưu trữ (PostgreSQL, SQLite, Redis hay kho vector).
Năm Nguyên lý SOLID Tại Ranh giới Lưu trữ Dữ liệu & AI#
- SRP (Single Responsibility Principle): Mỗi lớp chỉ có một trục thay đổi duy nhất. Sai lầm kinh điển là viết lớp
FeaturePipelinevừa chuẩn hóa z-score, vừa mở con trỏpsycopg, vừa phát sự kiện Kafka: đổi lược đồ SQL làm gãy cả unit test toán học. Giải pháp chuẩn: táchOrderCreateSpec(hợp đồng dữ liệu bất biến),OrderRepository(chuyển dịch đối tượng–quan hệ), vàPlaceOrderService(luồng nghiệp vụ). - OCP (Open/Closed Principle): Đóng với việc sửa mã điều phối hiện có, mở với bộ chuyển đổi lưu trữ mới. Thay vì nhồi
if backend == "pgvector": ... elif backend == "qdrant": ...vàoRAGRetriever, hãy định nghĩa giao diện trừu tượng và bơm (inject) triển khai mới. - LSP (Liskov Substitution Principle): Mọi lớp con hoặc bộ chuyển đổi \(S <: T\) phải giữ nguyên tiền điều kiện không khắt khe hơn và hậu điều kiện không yếu hơn \(T\). Nếu
ReadOnlyFeatureStorekế thừaFeatureStorerồi némNotImplementedErrorở.upsert(), mã gọi tổng quát sẽ sập lúc chạy; hãy tách hợp đồng đọc và ghi riêng. - ISP (Interface Segregation Principle): Tách giao diện lớn thành các hợp đồng hẹp (
OrderRepositoryProtocol,OutboxRepositoryProtocol) thay vì ép một worker chỉ đọc log phải triển khai cả hàng chục phương thức quản trị ghi. - DIP (Dependency Inversion Principle): Cả dịch vụ cấp cao (
PlaceOrderService) lẫn bộ chuyển đổi cấp thấp (SqliteUnitOfWork,SqlAlchemyUnitOfWork) đều phụ thuộc vào trừu tượng (UnitOfWorkProtocol), đảo ngược hoàn toàn hướng phụ thuộc truyền thống.
typing.Protocol (PEP 544) vs. abc.ABC (PEP 3119)#
- Kế thừa Danh nghĩa (
abc.ABC): Ép mọi lớp triển khai phải kế thừa tường minh (class SqliteRepo(AbstractRepo)). Thích hợp khi cần chia sẻ khung thuật toán Template Method có trạng thái chung, nhưng tạo khớp nối cứng và xung đột MRO khi tích hợp thư viện ngoài. - Định kiểu Cấu trúc (
typing.Protocol): Bất kỳ lớp nào có chữ ký phương thức khớp hợp đồng đều thỏa mãn giao diện ở bước kiểm tra tĩnh (mypy --strict/pyright) mà không cần kế thừa (InMemoryUnitOfWorkvàSqliteUnitOfWorktrongdb_internals_labkhông có bất kỳ lớp cha chung nào!).- Bẫy
@runtime_checkable: Dán@runtime_checkablecho phép gọiisinstance(obj, UnitOfWorkProtocol), nhưng Python chỉ kiểm tra sự tồn tại của tên thuộc tính/phương thức quagetattr, không kiểm tra kiểu tham số hay giá trị trả về, và nếu một thuộc tính phiên bản (self.orders) chỉ khai báo chú thích kiểu mà chưa gán giá trị trong__init__(self.orders = None),isinstance()trước khi vào__enter__sẽ trả vềFalse!
- Bẫy
Mẫu Repository & Unit of Work (UoW) + Transactional Outbox#
- Repository: Cung cấp giao diện tựa tập hợp (
add_order,get_order,list_orders_for_tenant) che giấu SQL/JOIN/tải trước ORM khỏi tầng nghiệp vụ. Bất biến sống còn: Repository tuyệt đối không bao giờ tự gọicommit()! -
Unit of Work (
UoW): Quản lý biên giới giao dịch ACID (BEGIN ... COMMIT / ROLLBACK) ôm trọn nhiều repository đồng thời:- Fail-Closed Rollback: Thoát khỏi khối
with uow:/async with uow:mà chưa gọicommit()(do ngoại lệ hayreturnsớm) bắt buộc tự động chạyrollback(), đảm bảo 0 bản ghi rò rỉ một nửa (no torn writes). - Identity Map Coherence: Bảo đảm trong cùng một giao dịch, hai lần truy vấn cùng khóa chính trả về nhất quán một thể hiện thực thể trong bộ nhớ.
- Transactional Outbox: Muốn vừa lưu đơn hàng vào PostgreSQL vừa phát sự kiện sang Kafka mà tránh lỗi ghi kép (dual-write anomaly — DB commit xong thì Kafka chết hoặc ngược lại), hãy ghi sự kiện vào bảng
outbox_eventstrong chính giao dịch UoW đó rồi để tiến trìnhDebeziumCDC đọc WAL phát ra ngoài sau.
- Fail-Closed Rollback: Thoát khỏi khối
1.2 Phân loại Hệ quản trị CSDL, Bố cục Bộ nhớ (NSM vs. PAX) & Giả thuyết RUM#
Bố cục Trang Hàng (NSM) vs. Cột Lai (DSM / PAX)#
- NSM (N-ary Storage Model — PostgreSQL, InnoDB, SQLite): Lưu trọn vẹn \(C\) cột của mỗi tuple liên tiếp nhau trên trang
8 KiB. Khi CPU x86-64/ARM nạp dữ liệu vào L1/L2 theo từng cache line64 B, một truy vấn OLAP chỉ đọc \(k = 2\) cột (12 B) trên bảng rộng \(W = 400\text{ B}\) vẫn phải kéo cả64 Bcache line và cả trang8 KiBvào RAM. Tỷ lệ lãng phí băng thông là:\[\eta_{\text{waste}} = 1 - \frac{\sum_{j \in K} w_j}{W} \quad \Longrightarrow \quad 1 - \frac{12}{400} = \mathbf{97.0\%\text{ byte dư thừa!}}\] -
DSM & PAX (Partition Attributes Across — Parquet, DuckDB, ClickHouse): Chia ngang bảng thành từng Row Group (\(65\text{K–}1\text{M}\) hàng) rồi lưu từng cột liền kề nhau bên trong mỗi nhóm:
- Chỉ đọc đúng \(k\) cột cần thiết (projection pushdown), nhồi đầy
100%giá trị cùng kiểu vào64 Bcache line để chạy lệnh vector hóa SIMD (AVX2/AVX-512). - Header lưu
[min, max, null_count](Zone Maps) giúp bỏ qua toàn bộ khối hàng triệu dòng trong \(O(1)\). - Giá trị đồng nhất liền kề cho phép nén RLE, Dictionary, Delta/Frame-of-Reference đạt tỷ số nén cao hơn NSM
5x–20x, nhưng đổi lại sửa 1 dòng đơn lẻ tốn \(\Theta(C)\) chi phí viết lại các cột.
- Chỉ đọc đúng \(k\) cột cần thiết (projection pushdown), nhồi đầy
Ma trận 6 Mô hình Dữ liệu & Phương trình Quorum#
- Relational OLTP (
PostgreSQL): Chuẩn hóa 3NF/BCNF, toàn vẹn ACID mạnh, khóa ngoại, đa chỉ mục; điểm yếu là quét phân tích hàng tỷ dòng và chia mảnh ghi ngang tự động. - Columnar OLAP (
ClickHouse,DuckDB): Tối ưu tổng hợp tỷ dòng trong mili-giây (MergeTree/ Parquet vector hóa); cập nhật/xóa đơn lẻ rất đắt. - Document (
MongoDB): Cây tài liệu BSON linh hoạt trên WiredTiger B-Tree, ACID đơn tài liệu; nối nhiều bảng chéo ($lookup) và tài liệu phình \(>16\text{ MiB}\) gây nghẽn nặng. - Key-Value RAM (
Redis/Valkey): Độ trễ< 1 mstrên bảng băm RAM đơn luồng; sập khi dữ liệu vượt RAM, chạyKEYS *\(O(N)\), hoặcfork()CoW nhân đôi RAM lúc snapshot RDB/AOF. - Wide-Column / LSM (
Cassandra,ScyllaDB): Kiến trúc vòng không chủ (AP/PA-ELtheoPACELC), ghi tuần tự cực nhanh \(10^5\text{–}10^6\text{ ops/s}\). Ràng buộc giao nhau đọc–ghi mạnh đòi hỏi:\[R + W > N_{\text{rep}}\](Ví dụ \(N_{\text{rep}}=3, R=2, W=2 \implies 4 > 3\)). Rất nhạy cảm với cột không khóa, phân vùng phình \(>100\text{ MiB}\), và bão Tombstone khiDELETEhoặc hết hạnTTLnhiều! - Vector Lai (
pgvector/pgvectorscale): Gắn vectorvector(d)/halfvec(d)trực tiếp vào hàng quan hệ MVCC đểJOINvà lọcRLScùng giao dịch ACID, đánh đổi chi phí bộ nhớ đồ thị HNSW và bẫy lọc hậu kỳ (post-filtering).
Giả thuyết RUM & Toán học Khuếch đại B-Tree vs. LSM-Tree#
Theo Giả thuyết RUM (Athanassoulis et al., 2016), không cấu trúc chỉ mục nào tối ưu đồng thời Read Amplification (\(RA\)), Write Amplification (\(WA\)) và Space Amplification (\(SA\)) (\(\text{Amp} = \text{Byte vật lý} / \text{Byte logic}\)). Xét bản ghi \(r = 128\text{ B}\), trang \(P_{\text{sz}} = 8192\text{ B}\), hệ số tầng LSM \(T = 10\) qua \(L = \lceil \log_T (N r / M_{\text{mem}}) \rceil\) tầng:
- B-Tree cập nhật tại chỗ (PostgreSQL): Sửa \(r\) byte làm bẩn cả trang \(P_{\text{sz}}\) (cộng \(c\) chỉ mục phụ):
\[WA_{\text{B-Tree}} \approx (1 + c)\,\frac{P_{\text{sz}}}{r} \qquad \left(\text{ví dụ } \frac{8192}{128} = \mathbf{64\times}\text{ I/O ngẫu nhiên mỗi trang!}\right)\]Đọc điểm tốt (\(RA = O(\log_B N)\),
1I/O lá nếu tầng trên nằm RAM), không gian dư \(SA \approx \frac{1}{\ln 2} \approx \mathbf{1.44\times}\). - LSM-Tree (
Leveled Compaction— RocksDB): Ghi tiền cảnh chỉ append tuần tự WAL + MemTable \(O(1)\), nén nền tuần tự:\[WA_{\text{leveled}} = \Theta(T \cdot L), \qquad SA_{\text{leveled}} \approx 1 + \frac{1}{T} \approx \mathbf{1.11\times}\]Đọc điểm dùng Bloom filter (\(\approx 10\text{ bit/khóa}\), tỷ lệ dương tính giả \(\approx 1\%\)) giảm \(RA\) về \(O(1)\) I/O đĩa (cònSize-Tieredgiảm \(WA = \Theta(L)\) nhưng tốn \(SA = \Theta(T)\), đòi hỏi chừa50%đĩa trống).
1.3 Năm Nhóm lệnh SQL (DDL, DML, DQL, DCL, TCL) & Biểu cảm SQL Chuyên sâu#
| Nhóm lệnh | Lệnh Cốt lõi | Cơ chế Nội tại & Bẫy Sản xuất trên PostgreSQL |
|---|---|---|
| DDL (Data Definition) | CREATE, ALTER, DROP, TRUNCATE, CREATE INDEX |
Gần như mọi DDL trong PostgreSQL đều có tính giao dịch (có thể ROLLBACK), trừ CREATE INDEX CONCURRENTLY và VACUUM. ALTER TABLE / TRUNCATE lấy khóa ACCESS EXCLUSIVE chặn toàn bộ đọc/ghi. Từ PG 11+, ADD COLUMN ... DEFAULT <hằng số> là thao tác metadata \(O(1)\) (attmissingval), nhưng hàm biến động (gen_random_uuid(), uuidv7(), random()) vẫn viết lại toàn bộ bảng! |
| DML (Data Manipulation) | INSERT, UPDATE, DELETE, MERGE, ON CONFLICT |
INSERT ... ON CONFLICT (sku) DO UPDATE dùng chèn suy đoán (speculative insertion) thay thế mẫu kiểm tra-rồi-chèn vốn dính lỗi tranh chấp TOCTOU. Yêu cầu có UNIQUE index tại cột xung đột và không cập nhật trùng một hàng 2 lần trong cùng lệnh. |
| DQL (Data Query) | SELECT, WITH, OVER, LATERAL, EXPLAIN |
Thực thi logic theo đúng 9 bước chuẩn: 1. FROM/JOIN \(\to\) 2. WHERE \(\to\) 3. GROUP BY \(\to\) 4. HAVING \(\to\) 5. WINDOW \(\to\) 6. SELECT \(\to\) 7. DISTINCT \(\to\) 8. ORDER BY \(\to\) 9. LIMIT/OFFSET. Vì WHERE (bước 2) chạy trước WINDOW (bước 5) và SELECT (bước 6), không thể lọc bí danh cột hay ROW_NUMBER() ngay ở WHERE! |
| DCL (Data Control) | GRANT, REVOKE, CREATE ROLE, CREATE POLICY (RLS) |
Tách vai trò NOINHERIT để leo quyền có kiểm soát; bật ENABLE và FORCE ROW LEVEL SECURITY (vì chủ bảng mặc định vượt qua RLS!), đồng thời bọc current_setting(...) trong (SELECT ...) để planner đánh giá một lần dạng InitPlan. |
| TCL (Transaction Control) | BEGIN, COMMIT, ROLLBACK, SAVEPOINT, SET TRANSACTION |
Mỗi SAVEPOINT (hoặc khối EXCEPTION trong PL/pgSQL) tiêu thụ 1 Subtransaction XID. Mỗi backend chỉ cache 64 subxid trong PGPROC; vượt quá 64 làm tràn sang bộ đệm chia sẻ pg_subtrans, kích hoạt nghẽn khóa SubtransSLRULock toàn CPU! |
Điểm nhấn SOTA về SQL Biểu cảm#
TRUNCATE(DDL) vs.DELETE(DML):TRUNCATEtạo một tệprelfilenoderỗng mới trong \(O(1)\) dưới khóaACCESS EXCLUSIVEvà không kích hoạt row triggerON DELETE(nhưng vẫnROLLBACKđược trong PostgreSQL!); cònDELETEđi từng hàng \(O(N)\) dưới khóaROW EXCLUSIVE, đánh dấut_xmaxvà để lại \(N\) tuple chết cầnVACUUM.- CTE (
MATERIALIZEDvs.NOT MATERIALIZED): Từ PostgreSQL 12+, CTE không đệ quy được tham chiếu 1 lần mặc định làNOT MATERIALIZED(nội tuyến hóa để đẩy vị từWHEREngoài xuống chỉ mục); chỉ dùngAS MATERIALIZEDkhi cần ép tính 1 lần (ví dụ hàm tốn kém/biến động hoặc ngăn quét lặp lại qua join). - Bẫy Khung Cửa sổ
RANGEMặc định vs.ROWS: Khi cóORDER BYtrongOVER (...)mà không viết khung tường minh, SQL mặc định dùngRANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, gom toàn bộ các dòng có khóa bằng nhau (peers) vào một nhóm! Kiểm chứng trực tiếp trên SQLite ở Lab 03 với 2 giao dịch cùng mốcts=10(100và200): tổng tích lũy mặc định trả về300ngay tại dòng đầu tiên thay vì100nhưROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW! LATERALJoin (\(O(G \cdot \log_B N)\) vs. \(O(N \log N)\)): Để lấy Top-3 đơn hàng mới nhất của \(G\) khách hàng trên bảng \(N \gg G\) hàng có chỉ mục(tenant_id, created_at DESC),LEFT JOIN LATERAL (... LIMIT 3)thực hiện \(G\) cú tìm chỉ mục dừng sớm thay vì phải sắp xếp cửa sổ toàn bộ \(N\) dòng.
1.4 Giải phẫu Trang 8 KiB, MVCC, Cô lập SSI & Vòng đời HOT / VACUUM / XID Wraparound#
1. Kiến trúc Trang Slotted 8192 B & Tiêu đề Tuple (HeapTupleHeaderData)#
Mỗi bảng PostgreSQL là dãy trang 8192 B (BLCKSZ): PageHeaderData (24 B: pd_lsn, pd_checksum, pd_flags, pd_lower, pd_upper, pd_special, pd_prune_xid) nằm ở đầu, theo sau bởi mảng con trỏ dòng ItemIdData (4 B/mục) mọc xuôi, vùng trống ở giữa (\(\text{pd\_upper} - \text{pd\_lower}\)), và các Heap Tuple mọc ngược từ cuối trang lên. Chỉ mục chỉ trỏ vào 6 B TID = (BlockNumber 4B, OffsetNumber 2B) trên ItemIdData, giúp dồn nén trang tại chỗ không làm vỡ chỉ mục ngoài.
Mỗi tuple chứa tiêu đề 23 B (căn lề MAXALIGN_8 = 24 B): t_xmin (4 B), t_xmax (4 B), t_cid (4 B, chặn bài toán Halloween tự đọc lại cập nhật của chính mình), t_ctid (6 B, chuỗi phiên bản cập nhật), t_infomask2 (2 B: HEAP_HOT_UPDATED, HEAP_ONLY_TUPLE), t_infomask (2 B: các bit gợi ý HEAP_XMIN_COMMITTED, HEAP_XMIN_FROZEN, HEAP_XMAX_INVALID), và t_hoff (1 B) + bitmap NULL. Lần SELECT đầu tiên đọc tuple mới tự động đóng dấu hint bit vào t_infomask để tránh tra cứu pg_xact (2 bit/XID) lần sau — khiến ngay cả SELECT thuần cũng có thể làm bẩn trang đệm và sinh WAL nếu bật wal_log_hints / checksum.
2. Thuật toán Hiển thị Snapshot MVCC (HeapTupleSatisfiesMVCC)#
Trong PostgreSQL, UPDATE thực chất là DELETE (t_xmax = x_cur) + INSERT phiên bản mới (t_xmin = x_cur, nối t_ctid). Cho snapshot \(S = (x_{\min}, x_{\max}, \mathcal{X}_{\text{ip}})\), định nghĩa vị từ trợ giúp:
Một tuple \(v\) hiển thị với \((x_{\text{cur}}, c_{\text{cur}}, S)\) khi và chỉ khi đồng thời thỏa:
- Người tạo hợp lệ: \(v\) mang cờ
HEAP_XMIN_FROZEN, hoặc \((v.\text{xmin} = x_{\text{cur}} \land v.\text{cid} < c_{\text{cur}})\), hoặc \(\text{XidVisibleInSnap}(v.\text{xmin}, S)\). - Người xóa chưa có hiệu lực: \(v.\text{xmax} = 0\), hoặc
HEAP_XMAX_INVALID, hoặc chỉ khóa dòngHEAP_XMAX_LOCK_ONLY, hoặc \((v.\text{xmax} = x_{\text{cur}} \land v.\text{cid} \ge c_{\text{cur}})\), hoặc \((v.\text{xmax} \neq x_{\text{cur}} \land \neg\text{XidVisibleInSnap}(v.\text{xmax}, S))\).
3. Các Mức Cô lập & Bẫy Write Skew (A5B) Dưới Snapshot Isolation#
READ COMMITTED(Mặc định PG): Chụp snapshot mới cho từng câu lệnh SQL; khóa dòng gặp xung đột chạyEvalPlanQualkiểm tra lạiWHEREtrên phiên bản mới nhất (dễ dính Non-Repeatable Read, Phantom, Write Skew).REPEATABLE READ(Snapshot IsolationSI): Chụp 1 snapshot duy nhất cho toàn giao dịch — loại sạch Phantom Read (mạnh hơn SQL-92!), chặnww-conflict bằng First-Committer-Wins (40001), nhưng vẫn thủng trướcWrite Skew(A5B)! Nếu \(T_1, T_2\) cùng đọcactive_replicas = 2(worker_A=true, worker_B=true), rồi \(T_1\) tắtAvà \(T_2\) tắtB, vì tập ghi{A}và{B}rời nhau nên cả hai cùng commit, đánh sập bất biến xuống0(tái hiện 100% ở Lab 03 Test 04!).SERIALIZABLE(SSI— Serializable Snapshot Isolation): Giữ tốc độ MVCC không khóa đọc bằng cách gắn khóa vị từ phi chặnSIREAD, theo dõi các cạnh phản phụ thuộc đọc–ghi (\(T_1 \xrightarrow{rw} T_2\)). Theo Định lý Fekete, mọi chu trình mất tuần tự hóa đều chứa cấu trúc nguy hiểm \(T_{\text{in}} \xrightarrow{rw} T_{\text{pivot}} \xrightarrow{rw} T_{\text{out}}\); PostgreSQL ngắt một giao dịch vớiSQLSTATE 40001để client thử lại sạch sẽ (active_replicas = 1bảo toàn nguyên vẹn).
4. Tối ưu HOT (Heap-Only Tuple), VACUUM & Giới hạn XID Wraparound#
- Điều kiện Kép của
HOT: MộtUPDATEchỉ trở thànhHOT(0 lần ghi vào \(c\) chỉ mục phụ!) khi đồng thời: (1) Không sửa bất kỳ cột nào nằm trong mọi chỉ mục (kể cảINCLUDE, biểu thức, điều kiệnWHEREcủa partial index), VÀ (2) Còn đủ chỗ trống trên chính trang8 KiBcũ. Giảmfillfactortừ100xuống75chừa25%(~2 KiB) không gian trên mỗi trang cho chuỗiHOTvà cắt tỉa tại chỗ (LP_REDIRECT, không cầnVACUUMhay khóa chỉ mục). - Kích hoạt
Autovacuum& Bản đồ Hiển thị (_vm): Kích hoạt khi \(N_{\text{dead}} > \text{threshold} + \text{scale\_factor} \times N_{\text{live}}\). Với bảng \(10^8\) dòng, mức mặc định0.20chờ tận20,000,000tuple chết; cần hạautovacuum_vacuum_scale_factor = 0.01. Tệp_vmlưu2 bit/trang (ALL_VISIBLEcho phép Index-Only Scan bỏ qua đọc heap;ALL_FROZENcho phépVACUUMchống wraparound bỏ qua trang). - Số học Modulo \(2^{32}\) &
XID Wraparound: Khoảng cách \(x_1 \prec x_2 \iff (x_2 - x_1) \bmod 2^{32} < 2^{31}\) (~2.147 tỷ). Quá ngưỡng này, dữ liệu cũ biến thành "tương lai" và biến mất! Các chốt chặn leo thang:autovacuum_freeze_max_age = 200M(ép vacuum cưỡng bức),vacuum_failsafe_age = 1.6B(tắt tiết lưu độ trễ và bỏ qua dọn chỉ mục để đóng băng nhanh), cảnh báo ở~40MXID cuối, và khóa cứng toàn bộ quyền ghi ởxidStopLimit(~3MXID trước wrap).
1.5 Toán học Chỉ mục, Mô hình Chi phí EXPLAIN, Keyset Pagination & Pooling#
1. B-Tree Lehman–Yao: Tính Hệ số Rẽ nhánh \(B\) & Chiều cao \(h\)#
Không gian khả dụng mỗi trang B-Tree 8192 B là \(8192 - 24\text{ (PageHeaderData)} - 16\text{ (BTPageOpaqueData)} = \mathbf{8152\text{ B}}\). Mỗi mục chỉ mục tốn \(S_{\text{entry}} = 4\text{ B (ItemIdData)} + 8\text{ B (IndexTupleData)} + \text{MAXALIGN}_8(\text{key\_bytes})\). Với \(N = 10^7\) dòng tại fillfactor = 90%:
- Khóa
BIGINT(8 B): \(S_{\text{entry}} = 20\text{ B} \implies B = \lfloor 0.90 \times \lfloor 8152/20 \rfloor \rfloor = \mathbf{366} \implies \mathbf{h = 3}\) (27,323trang lá, chỉ76trang tầng trên =~608 KiBluôn ghim gọn trong RAM \(\implies\) mọi truy vấn chỉ tốn tối đa1I/O lá!). - Khóa ghép
32 B: \(S_{\text{entry}} = 44\text{ B} \implies B = \mathbf{166} \implies \mathbf{h = 4}\) (473.50 MB). - Quy tắc Tiền tố Trái nhất (
ESR: Equality – Sort – Range): Chỉ mục(a, b, c)sắp xếp từ điển theo \(a \to b \to c\). Luôn đặt cột bằng (=) trước, rồi cột sắp xếp (ORDER BY), cuối cùng mới đến cột khoảng (>,BETWEEN). Truy vấn bỏ quaahoặc đặt khoảng trênbtrướcc = 5đều không thu hẹp được khung tìm kiếm trênc(\(\le\) PG 17). - Covering (
INCLUDE) & Partial Indexes:INCLUDE (status, total_cents)chỉ nhúng cột tải vào trang lá (không làm phình tầng phân cách nội bộ, giữ \(B\) cao!), cho phép Index-Only Scan nếu_vmđã đượcVACUUMđánh dấuALL_VISIBLE(bảng không vacuum làmHeap Fetches > 0, sụp hiệu năng!). Partial indexWHERE status = 'pending'thu nhỏ chỉ mục \(20\text{–}100\times\) và giúp các bản cập nhật trạng thái hoàn tất luôn chạyHOT. - GIN vs. BRIN:
GINđảo ngược choJSONB/ARRAYgặp bẫyfastupdate = on(gin_pending_list_limit = 4 MiB): mọi truy vấn đọc phải quét tuần tự danh sách chờ chưa sắp, và phiên ghi làm tràn4 MiBphải trả giá hợp nhất hàng trăm mili-giây.BRINlưu[min, max]mỗipages_per_range = 128khối (1 MiB), nhỏ hơn B-Tree hàng nghìn lần cho nhật ký append-only tương quan vật lý cao, nhưng sập hoàn toàn vềSeq Scannếu bảng bị cập nhật xáo trộn vị trí vật lý.
2. Mô hình Chi phí Planner, SARGability & 3 Thuật toán Join#
Mặc định seq_page_cost = 1.0, random_page_cost = 4.0 (phản ánh đĩa quay HDD; trên NVMe SSD cần hạ về 1.1–1.5 để planner không bỏ qua Index Scan). Vị từ SARGable (created_at >= '2026-01-01' AND created_at < '2027-01-01') mở khóa tìm kiếm cây \(O(\log_B N)\) trong khi hàm bọc cột (EXTRACT(YEAR FROM created_at) = 2026, substr(...), LIKE '%foo%') phá hủy tìm kiếm khoảng (27.0x chậm hơn trong Lab 03!). Ba phép Join chính: Nested Loop (\(O(|R| \log_B |S|)\), cực nhanh khi \(|R|\) nhỏ và \(|S|\) có index), Hash Join (\(O(|R|+|S|)\) trong work_mem, tràn ra Grace Hash trên đĩa nếu thiếu work_mem), và Merge Join (\(O(|R|+|S|)\) khi hai đầu đã sắp sẵn).
3. Toán học Phân trang (OFFSET \(\Theta(N^2/m)\) vs. Keyset \(O(\log_B N)\)) & PgBouncer#
OFFSET k LIMIT m: Quét và vứt bỏ \(k\) bản ghi đầu tiên mất \(\Theta(k + m)\) mỗi trang; quét hết \(N\) dòng tốn \(\sum_{j=0}^{N/m-1} c(jm+m) = \Theta(N^2/m)\) và dễ lệch/trùng dòng khi có thêm ghi mới! Keyset Seek dùng so sánh tupleWHERE (created_at, id) < ($1, $2)(tránhORvốn làm gãy seek đơn!) giữ chi phí \(O(\log_B N + m)\) bất biến dù ở trang 1 hay trang 1.000.000 (23.5xnhanh hơn ởOFFSET 15,000trong Lab 03).PgBouncer: Mỗi kết nối trực tiếp sinh một tiến trình OS ngốn~5–10 MiB(7.6 MiBPSS khônghuge_pages) và làm phình kiểm traProcArray. Công suất tối ưu cho OLTP chỉ là \(\approx 2 \cdot N_{\text{cores}} + N_{\text{disks}}\) (16–40backend hoạt động). Chế độ Transaction Pooling ghép500–2,000+client vào32backend, giảm93.6%số tiến trình DB.
Trụ cột 2 — Kiến trúc Hệ thống Sản xuất & Đổi mới SOTA 2024–2026#
2.1 Kiến trúc Tách lớp OOP & 5 Nhóm lệnh SQL (DDL, DML, DQL, DCL, TCL)#
Sơ đồ kiến trúc dưới đây kết nối tầng nghiệp vụ Python thuần túy (typing.Protocol + Unit of Work) với 5 nhóm lệnh SQL chạy trên động cơ giao dịch ACID và hàng đợi Transactional Outbox:
2.2 Chu trình Trang 8 KiB, MVCC/HOT & Đột phá PostgreSQL 16–18 (TidStore, Native AIO, Skip Scan)#
Giai đoạn 2023–2025 đánh dấu cuộc đại tu tầng lưu trữ lớn nhất của PostgreSQL trong một thập kỷ qua ba phiên bản PG 16, PG 17 (09/2024), và PG 18 (09/2025):
- PG 17
TidStore(Adaptive Radix Tree thay Mảng TID Phẳng1 GB): Trước PG 17,VACUUMlưu TID chết trong mảng phẳng6 B/phần tử bị khóa cứng trần1 GB(MaxAllocSize) bất kểmaintenance_work_memlớn đến đâu — hễ tràn1 GB(~178Mtuple chết) là phải dừng quét heap, chạy lặp toàn bộ cây chỉ mục nhiều lượt (multi-pass index vacuum storm). PG 17 thay bằng cấu trúc Adaptive Radix Tree chia sẻ (TidStore) dùng ít RAM hơn tới20x(1,029.97 MB -> 51.50 MBtrên180Mdead tuples trong Lab 03!) và xóa bỏ hoàn toàn trần1 GB. Bổ sung ở PG 18, tham sốautovacuum_vacuum_max_threshold(mặc định100,000,000tuple) ngăn bảng tỷ dòng phải chờ tích tụ hàng trăm triệu tuple chết mới kích hoạt vacuum. - PG 17 Streaming I/O & PG 18 Native Async I/O (
AIO): Đọc đồng bộpread()(\(QD = 1\)) trên AWS EBS (\(\tau \approx 500\,\mu\text{s}\)) bóp nghẽn băng thông chỉ còn~15.6 MiB/s. PG 17 thêmread_streamgom đọc vectơio_combine_limit(128kBmặc định); PG 18 mở khóaio_method = worker(mặc định) hoặcio_uringcùngeffective_io_concurrency = 16, tăng thông lượng quét tuần tự / Bitmap Heap /VACUUMlên2x–3x. - PG 17
ScalarArrayOpExpr& PG 18 B-Tree Skip Scan: PG 17 duyệtWHERE id IN (...)trong 1 lần xuống cây theo thứ tự lá thay vì \(k\) lần xuống cây rời rạc; PG 18 thêm B-Tree Skip Scan tự động nhảy qua các giá trị rời rạc của cột dẫn đầu có lực lượng thấp trên chỉ mục ghép(tenant_id, created_at)ngay cả khi truy vấn thiếutenant_id. - Quan sát Hệ thống (
PG 16–18):pg_stat_io(PG 16),pg_stat_checkpointer+EXPLAIN (MEMORY, SERIALIZE)(PG 17), vàEXPLAIN ANALYZEtự động bậtBUFFERSmặc định từ PG 18!
2.3 UUIDv7 (RFC 9562, PG 18 uuidv7()) vs. UUIDv4 & Tìm kiếm Vector Lai pgvector#
1. Vì sao UUIDv7 Giải phóng Khoảng trống B-Tree & Bão WAL FPI#
Chuẩn RFC 9562 (05/2024) — tích hợp gốc trong PostgreSQL 18 qua uuidv7() (đảm bảo đơn điệu dưới mili-giây qua rand_a 12-bit) và uuid_extract_timestamp() — đặt dấu thời gian Unix 48-bit ở đầu khóa UUID. Khác với UUIDv4 ngẫu nhiên ép B-Tree tách đôi mọi trang lá ở mức lấp đầy ~69–71% (71.4% trong Lab 03), văng khỏi shared_buffers (64.7% hit), và buộc mỗi trang lá chạm tới sau checkpoint phải chép trọn 8192 B FPI vào WAL (17.17 MiB trên 6,000 insert), UUIDv7 luôn ghi nối vào trang lá cực phải: mật độ đạt 89.6%, tỷ lệ trúng cache đạt 98.9%, và tổng lượng WAL FPI giảm xuống 0.91 MiB (-94.7%, thấp hơn 30.7x số FPI!).
2. Tìm kiếm Vector Lai pgvector HNSW, halfvec, Binary Quantization & iterative_scan#
Bộ nhớ chỉ mục đồ thị HNSW (Malkov & Yashunin, IEEE TPAMI 2020) với \(N\) vector \(d\) chiều, bậc \(m\) (16 mặc định) xấp xỉ \(M_{\text{HNSW}} \approx N \cdot (d \cdot b_{\text{elem}} + 8m)\) (+ ~10–15% tiêu đề trang). Với fp32 (d=1536, m=16), 1M vector ngốn ~6.5 GB RAM. Hai kỹ thuật nén SOTA trong pgvector 0.7+:
halfvec(d)(fp16): Cắt đôi dung lượng (2d + 8 B, hỗ trợ tới4,000chiều), giảm50%RAM đồ thị gần như không mất recall.- Lượng tử hóa Nhị phân (
bit(d)+ Rescore): Nén~32x(200 Bở1536chiều) quabinary_quantize(embedding)::bit(1536)vàbit_hamming_ops(<~>), truy xuất dư \(K_{\text{cand}} = 100\) ứng viên rồi chấm lại khoảng cáchhalfvecchính xác ở truy vấn ngoài! - Khắc phục Sụp đổ Lọc Hậu kỳ (
pgvector 0.8.0+hnsw.iterative_scan): Với độ chọn lọc khách hàng \(s = 2\%\) vàef_search = 40, kỳ vọng số dòng khớp chỉ là \(0.02 \times 40 = 0.8\) (Lab 03 ghi nhận chỉ trả2/10dòng,Recall@10 = 0.20!). BậtSET LOCAL hnsw.iterative_scan = 'relaxed_order'tự động mở rộng quét biên đồ thị (bảo vệ bởihnsw.max_scan_tuples = 20000vàwork_mem * hnsw.scan_mem_multiplier), phục hồi trọn vẹn10/10kết quả (Recall@10 = 1.00sau411tuple quét); ở quy mô50M+vector vượt RAM,pgvectorscale(StreamingDiskANN+ nhãn lọc trong đồ thị&&) đặt đồ thị lên SSD với chi phí thấp hơn dịch vụ vector chuyên biệt tới~75%.
2.4 SQLAlchemy 2.0 Async, PgBouncer & Di trú Zero-Downtime Alembic Expand–Contract#
Kiến trúc ứng dụng FastAPI + SQLAlchemy 2.0 chuẩn 2026 khóa chặt bốn chốt chặn an toàn:
- Định kiểu
Mapped[T]& Chống N+1 Cưỡng bức (lazy="raise"): ThaySession.query()1.x bằngDeclarativeBase+Mapped[]+select(). Gắnlazy="raise"lên mọirelationship()để mọi lần đọc thuộc tính chưa nạp trước đều nổ lỗi ngay lúc test thay vì rò rỉ101câu SQL (hoặcMissingGreenletlúc runtime), sau đó chủ động chọnselectinload()(2truy vấnWHERE fk IN (...), không nhân bản dòng cha) cho quan hệ1-to-manyvàjoinedload()(1truy vấnLEFT OUTER JOIN) cho quan hệmany-to-1. AsyncSessionAn toàn Sau Commit (expire_on_commit=False): Với mặc địnhexpire_on_commit=True, đọcorder.idsauawait session.commit()sẽ kích hoạt đồng bộ lại thuộc tính ngoài ngữ cảnh greenlet và némMissingGreenlet. Luôn cấu hìnhasync_sessionmaker(engine, expire_on_commit=False).PgBouncerTransaction Pooling & Bẫy Prepared Statements: Ở chế độtransaction, hai giao dịch liên tiếp của cùng một client có thể rơi vào hai backend PostgreSQL khác nhau, làmasyncpgnémDuplicatePreparedStatementError/InvalidSQLStatementNameError. Giải pháp: dùngpoolclass=NullPool(tránh double-pooling) kết hợpstatement_cache_size=0(chỉ thêm~0.5 msparse) trên proxy cũ, hoặc bậtmax_prepared_statements = 100trênPgBouncer 1.21+.- Di trú
AlembicExpand–Contract Không Dừng Hệ thống: Luôn đặtSET LOCAL lock_timeout = '2s'để lệnhALTER TABLEtự hủy thay vì đứng xếp hàng FIFO chặn toàn bộ API; chạyCREATE INDEX CONCURRENTLYbên trongwith op.get_context().autocommit_block():; thêm ràng buộc kiểm tra hai phaNOT VALID(< 1 ms) rồi mớiVALIDATE CONSTRAINT(SHARE UPDATE EXCLUSIVEcho phép đọc/ghi chạy song song — hỗ trợ cảNOT NULL NOT VALIDtừ PostgreSQL 18!).
2.5 Kiến trúc Lai OLTP / OLAP Hiện đại (DuckDB, ClickHouse CDC, Neon)#
Chạy truy vấn tổng hợp OLAP nặng trực tiếp trên nút chính OLTP gây ra hai hiểm họa: (1) đầu độc shared_buffers (đẩy các trang nóng B-Tree ra khỏi RAM) và (2) ghim xmin horizon làm VACUUM tê liệt suốt thời gian báo cáo chạy. Kiến trúc SOTA 2026 tách tải qua ba mô hình:
DuckDB(postgresextension /pg_duckdb/pg_mooncake): Quét bảng đọc replica qua giao thứcCOPYnhị phân hoặc ghi trực tiếp bảng Parquet/Iceberg để vector hóa SIMD không đụng trang heap OLTP.ClickHouse+PeerDB/DebeziumCDC: Đồng bộ WAL logical (pgoutput) song song sangReplacingMergeTreetrên cụm ClickHouse tách biệt hoàn toàn CPU, RAM và đĩa.NeonServerless Postgres (Safekeepers+Pageservers): Tách compute không trạng thái khỏi nhật ký WAL (Paxos/Raft trên Safekeepers) và vật chất hóa trang8 KiBtheo yêu cầu trên Pageservers, cho phép copy-on-write branching phục vụ chạy thử migration Alembic trên bản sao dữ liệu thật trong vài giây.
Trụ cột 3 — Năm Sự cố Sản xuất Kinh điển, Mã Chuẩn SQLAlchemy 2.0 & Bảng Ra quyết định#
Case 1 — Uber Engineering (PostgreSQL -> MySQL): Khuếch đại Ghi Non-HOT & Bão WAL FPI#
- Thực tế Sản xuất (Evan Klitzke, Uber Engineering Blog, 07/2016): Ở giai đoạn tăng trưởng nóng, cụm PostgreSQL
9.2của Uber gánh hàng loạtUPDATEvào tọa độ tài xế và trạng thái chuyến đi (những cột có đánh chỉ mục phụ) trên các bảng có nhiều chỉ mục vàfillfactor = 100. Vì mỗi chỉ mục phụ trong PostgreSQL trỏ thẳng tới địa chỉ vật lýctid(khácInnoDBtrỏ vào khóa chính logic), thất bại điều kiệnHOTbuộc mỗi cập nhật1cột phải viết thêm mục mới vào toàn bộ \(c\) chỉ mục phụ và phát hàng loạt8 KiBFull-Page Images vào WAL sau mỗi checkpoint, bóp nghẹt SSD và nhân bản vật lý. - Cách Phòng tránh Trên PostgreSQL Hiện đại (
14–18): (1) Tách dọc phần tĩnh (có nhiều chỉ mục) khỏi bảng trạng thái nóng (fillfactor = 70–75, tối giản chỉ mục); (2) xóa chỉ mục thừa cóidx_scan = 0; (3) giám sátROUND(100.0 * n_tup_hot_upd / NULLIF(n_tup_upd, 0), 2)trênpg_stat_user_tablesgiữ ngưỡng> 80%–95%. (Lab 03 chứng minh đặtfillfactor = 75và tách cột cập nhật khỏi chỉ mục đẩy tỷ lệHOTtừ0.0%lên100.0%, xóa sạch4,000lần ghi chỉ mục cập nhật dư thừa!)
Case 2 — Sentry (07/2015) & Mailchimp/Mandrill (02/2019, 40h 34m): Khóa Ghi Toàn cụm Vì XID Wraparound#
- Thực tế Sản xuất: Ngày
20/07/2015, Sentry bị ngắt quyền ghi gần trọn ngày làm việc do autovacuum tụt hậu trên bảng lớnevents-to-rollups(phảiTRUNCATEbảng rollup để thoát kẹt chỉ sau 5 phút). Ngày04–05/02/2019, cụmshard4của Mailchimp/Mandrill chạm ngưỡng cứngxidStopLimit, làm gián đoạn ghi suốt40 giờ 34 phútvà sụt thông lượng gửi email xuống~80%cho tới khi kỹ sư truncate bảngSearch/Urlvà chạyVACUUM FREEZE(~1 giờ). - Phòng thủ Bắt buộc: Đặt
idle_in_transaction_session_timeout = '120s'(chặt đứt phiên treo ghimGlobalXmin), tăngautovacuum_vacuum_cost_limit = 1000+autovacuum_max_workers = 6cho SSD, nâng cấp PostgreSQL 17+ (TidStore) tránh lặp đa pha1 GB, và đặt cảnh báo pager khiage(datfrozenxid) > 250M(Warning) /500M(Critical) — tuyệt đối không để trôi tới2.1B(xidStopLimit).
Case 3 — GoCardless, Braintree (pg_ha_migrations) & GitLab: Sập Dịch vụ Do Hàng đợi Khóa FIFO ACCESS EXCLUSIVE#
- Thực tế Sản xuất (Chris Sinjakli, GoCardless): Một bản di trú chỉ đổi tên vài bảng hoàn toàn rỗng và cập nhật khóa ngoại đã đánh sập toàn bộ API trong
~15 giây. Nguyên nhân: thêm/xóa khóa ngoại xin khóaACCESS EXCLUSIVEtrên cả bảng cha; nó đứng chờ sau một câuSELECTđọc báo cáo và tạo thành nút cổ chai FIFO chặn đứng 100% lệnhSELECT/INSERTđến sau. - Quy trình Chuẩn Sản xuất: Bọc mọi DDL bằng
SET LOCAL lock_timeout = '2s';kèm vòng lặp thử lại có jitter (with_lock_retriescủa GitLab), luôn dùngCREATE INDEX CONCURRENTLY, và áp dụng khóa ngoại /CHECK/NOT NULL(PG 18) theo hai bướcNOT VALID\(\to\)VALIDATE CONSTRAINT.
Case 4 — Cạn max_connections (ProcArray), PGKeeper (Figma) & Mẫu Code Chuẩn SQLAlchemy 2.0#
- Thực tế Sản xuất & Số đo (
Andres Freund/Figma): Mỗi kết nối PostgreSQL tiêu tốn~7.6–15+ MiBRSS (chỉ~1.3–2 MiBvớihuge_pages = on). Trước PG 14,10,000kết nối nhàn rỗi làmGetSnapshotData()quétProcArraykéo tụt thông lượng đọc đơn luồng từ~33,700 TPSxuống~6,000 TPS; ngay cả sau cải tiến PG 14, hàng trăm backend chạy đồng thời vẫn vấp tràn chuyển ngữ cảnh OS. Figma phải xây bộ điều phốiPGKeeper(CoDel + LIFO thích nghi) phía trước cụm shard để giữ99.99%+SLO. - Mẫu Code Sản xuất (
SQLAlchemy 2.0+PgBouncerTransaction Mode +Unit of Work):
from __future__ import annotations
from sqlalchemy import BigInteger, ForeignKey, String, create_engine, event, select
from sqlalchemy.exc import InvalidRequestError
from sqlalchemy.orm import (
DeclarativeBase,
Mapped,
Session,
mapped_column,
relationship,
selectinload,
sessionmaker,
)
class Base(DeclarativeBase):
pass
class Order(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
tenant_id: Mapped[int] = mapped_column(BigInteger, index=True)
status: Mapped[str] = mapped_column(String(32), default="pending")
items: Mapped[list[OrderItem]] = relationship(back_populates="order", lazy="raise")
class OrderItem(Base):
__tablename__ = "order_items"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
order_id: Mapped[int] = mapped_column(ForeignKey("orders.id", ondelete="CASCADE"), index=True)
sku: Mapped[str] = mapped_column(String(64))
order: Mapped[Order] = relationship(back_populates="items", lazy="raise")
# Ở sản xuất với PgBouncer Transaction Pooling, truyền DSN qua biến môi trường DATABASE_URL
# cùng poolclass=NullPool và statement_cache_size=0 (hoặc khớp max_prepared_statements >= 1.21).
engine = create_engine("sqlite:///:memory:")
SessionFactory = sessionmaker(engine, expire_on_commit=False, autoflush=False)
def list_orders_without_n_plus_1(session: Session, tenant_id: int, limit: int = 100) -> list[Order]:
"""Nạp đơn hàng + chi tiết trong ĐÚNG 2 câu SQL (cấm N+1 qua lazy='raise')."""
stmt = (
select(Order)
.where(Order.tenant_id == tenant_id)
.options(selectinload(Order.items))
.order_by(Order.id.desc())
.limit(limit)
)
return list(session.scalars(stmt).all())
if __name__ == "__main__":
Base.metadata.create_all(engine)
sql_selects: list[str] = []
@event.listens_for(engine, "before_cursor_execute")
def _count_selects(_conn: object, _cur: object, stmt: str, *_args: object) -> None:
if stmt.lstrip().upper().startswith("SELECT"):
sql_selects.append(stmt)
with SessionFactory() as session:
for oid in range(1, 6):
session.add(
Order(
id=oid,
tenant_id=101,
items=[
OrderItem(id=oid * 10 + 1, sku=f"GPU-{oid}-A"),
OrderItem(id=oid * 10 + 2, sku=f"GPU-{oid}-B"),
],
)
)
session.commit()
with SessionFactory() as session:
raw_orders = list(session.scalars(select(Order).where(Order.tenant_id == 101)).all())
try:
_ = raw_orders[0].items
raise AssertionError("lazy='raise' phải chặn truy cập ngầm!")
except InvalidRequestError:
pass
sql_selects.clear()
orders = list_orders_without_n_plus_1(session, tenant_id=101)
skus = [item.sku for order in orders for item in order.items]
assert len(orders) == 5 and len(skus) == 10 and len(sql_selects) == 2
print(f"SQLAlchemy 2.0 OK: {len(orders)} orders, {len(skus)} items in {len(sql_selects)} SELECTs")
Case 5 — UUIDv4 FPI Bloat, OFFSET 100k & Sụp đổ Recall pgvector HNSW Khi Lọc Tenant#
- Thực tế Thực nghiệm: Benchmark của Tomas Vondra & PostgresAI ghi nhận khi B-Tree vượt RAM,
UUIDv4đẩy lượng WAL phình1.5x–1.9xtới hơn10xkhi giao cắt checkpoint FPI so với khóa tuần tự; chuyển sangUUIDv7(RFC 9562/ PG 18uuidv7()) kéo mật độ lá về~90%và chặn bão cache miss. Kết hợp phân trang Keyset(created_at, id) < ($1, $2)giữ độ trễ< 1 msở mọi độ sâu trang (so vớiOFFSET\(\Theta(k+m)\)), và bậthnsw.iterative_scan = 'relaxed_order'(pgvector 0.8.0+) hoặc partial HNSW index cho các RAG truy vấn có lọctenant_idđể tránh trả về0–2đoạn văn bản thay vìLIMIT 10.
Ba Bảng Ra quyết định Sản xuất 2026 (Production Decision Playbooks)#
Playbook A — Chọn Động cơ Lưu trữ Dữ liệu (SQL vs. NoSQL vs. OLAP vs. Vector)#
| Động cơ | Kiến trúc & Bố cục | Nhất quán & Giao dịch | p99 Kỳ vọng |
Bẫy Sập Lớn Nhất | Dùng Khi / Tránh Khi |
|---|---|---|---|---|---|
PostgreSQL 17/18 |
NSM trang 8 KiB, MVCC, đa chỉ mục |
ACID toàn diện (SSI), khóa ngoại, RLS |
1–25 ms (OLTP) |
Ghi Non-HOT, XID Wraparound, quá tải max_connections |
Dùng: Hệ thống ghi chuẩn OLTP, giao dịch phức tạp, SQL + JSONB + pgvector.Tránh: Quét phân tích hàng tỷ dòng trực tiếp trên primary. |
MongoDB |
Tài liệu BSON, WiredTiger B-Tree |
ACID 1 tài liệu (đa mảnh đắt) | 5–30 ms (RAM) |
Chỉ mục tràn RAM, join $lookup chậm, tài liệu >16 MiB |
Dùng: Dữ liệu bán cấu trúc cây lồng nhau truy cập theo khóa. Tránh: Quan hệ nhiều–nhiều chuẩn hóa hoặc nhật ký tăng vô hạn. |
Redis / Valkey |
Bảng băm RAM đơn luồng | Tối hậu (bất đồng bộ), nguyên tử 1 lệnh | < 1–2 ms |
Lệnh \(O(N)\) (KEYS *) đóng băng loop, hết RAM / fork() CoW |
Dùng: Cache, rate limiter, khóa phân tán, feature online. Tránh: Kho lưu trữ bền vững chính hay truy vấn SQL phức tạp. |
Cassandra / ScyllaDB |
Vòng phân tán, LSM-Tree | Quorum điều chỉnh (\(R + W > N_{\text{rep}}\)) | Scylla 5–15 ms |
Phân vùng nóng >100 MiB, bão Tombstone, GC JVM (Cassandra) |
Dùng: Ghi append tốc độ cực cao đa vùng (IoT, tin nhắn).Tránh: Truy vấn tự do không khóa phân vùng hoặc nhiều DELETE. |
ClickHouse / DuckDB |
Cột hóa PAX/MergeTree + SIMD |
Bất đồng bộ theo lô / đơn ghi cục bộ | 10–200 ms (tỷ dòng) |
INSERT từng dòng lẻ (Too many parts), UPDATE/DELETE đơn |
Dùng: Bảng điều khiển OLAP, log/telemetry, Parquet ETL (DuckDB).Tránh: Giao dịch OLTP cập nhật hàng đơn đồng thời cao. |
pgvector (PG) |
Đồ thị HNSW / DiskANN gắn MVCC | ACID đồng bộ hoàn toàn với bảng quan hệ | 5–30 ms (<50M vec) |
Sụp recall khi post-filter thiếu iterative_scan, đồ thị tràn RAM |
Dùng: RAG/AI cần đồng bộ ACID giữa embedding, ACL/RLS và SQL. Tránh: Kho tỷ vector phân tán đa nút không sharding. |
Playbook B — Chọn Loại Chỉ mục PostgreSQL#
| Loại Chỉ mục | Cơ chế Vật lý | Phí Ghi & Tác động HOT |
Tỷ lệ Dung lượng | Dùng Khi / Bẫy Thường Gặp |
|---|---|---|---|---|
| B-Tree (Mặc định) | B-Link Lehman–Yao (8 KiB) |
Chặn HOT nếu sửa cột index; UUIDv4 rỗng ~69% |
15%–35% bảng |
=, <, >, BETWEEN, LIKE 'abc%', ORDER BY / Keyset. Ưu tiên UUIDv7 hoặc BIGINT; sắp cột theo ESR. |
Covering (INCLUDE) |
B-Tree chứa cột tải chỉ ở trang lá | Phình trang lá hơn B-Tree thường; chặn HOT cột tải |
20%–45% bảng |
Truy vấn đọc tần suất cao cần Index-Only Scan. Phải giữ VACUUM chạy đều để _vm bật ALL_VISIBLE. |
Partial (WHERE) |
Chỉ đánh mục các hàng thỏa WHERE |
0 phí ghi & giữ HOT cho mọi hàng ngoài điều kiện |
1%–10% chỉ mục đầy đủ |
Cột lệch phân phối (WHERE status = 'pending'). Câu SQL bắt buộc lặp lại vị từ khớp ngữ nghĩa WHERE của index. |
| GIN | Cây đảo ngược + posting lists | Đắt khi cập nhật; fastupdate=on gây gai đọc/xả 4 MiB |
30%–100%+ bảng |
Truy vấn chứa @> trên JSONB (ưu tiên jsonb_path_ops), mảng TEXT[], Full-Text tsvector. |
| BRIN | [min, max] mỗi pages_per_range (1 MiB) |
Gần như 0 phí ghi & HOT |
< 0.1%–1% B-Tree |
Bảng append-only cực lớn có tương quan vật lý cao (created_at). Vô dụng nếu UPDATE/VACUUM xáo trộn thứ tự! |
HNSW (pgvector) |
Đồ thị gần kề đa tầng + halfvec |
Nặng khi chèn & dựng (cần maintenance_work_mem) |
~1x–2x vector thô |
Tìm kiếm ngữ nghĩa <=>. Bắt buộc bật hnsw.iterative_scan khi kết hợp bộ lọc SQL WHERE. |
Playbook C — Ma trận SQLAlchemy 2.0, Pooling & Ngân sách Vận hành#
| Hạng mục | Cấu hình Khuyến nghị Sản xuất | Ngưỡng SLA / Ngân sách Mục tiêu | Cách Đo & Chống Sập |
|---|---|---|---|
| Tải Quan hệ ORM | Gắn lazy="raise" toàn cục; selectinload() cho 1:N, joinedload() cho N:1 |
1–2 lượt SQL (3.55 ms vs 152.19 ms N+1) |
Đếm SQL trong test bằng SQLAlchemy before_cursor_execute hoặc SQLite set_trace_callback |
| Phiên & Bể kết nối | expire_on_commit=False; NullPool + statement_cache_size=0 (hoặc PgBouncer 1.21+ max_prepared_statements=100) |
default_pool_size ≈ 2 * cores (16–40); cl_waiting == 0 |
SHOW POOLS; trên PgBouncer; không để pods * pool_size vượt max_connections |
| Khóa DDL & Di trú | SET LOCAL lock_timeout = '2s'; CREATE INDEX CONCURRENTLY; NOT VALID \(\to\) VALIDATE CONSTRAINT |
Thời gian giữ ACCESS EXCLUSIVE < 1–2s |
Kiểm tra pg_locks WHERE NOT granted; audit pg_index WHERE NOT indisvalid |
| Bộ nhớ & Sức khỏe Bảng | fillfactor = 70–85 bảng nóng; idle_in_transaction_session_timeout = '120s'; random_page_cost = 1.1 (NVMe) |
Buffer hit > 99%; HOT > 80–95%; age(datfrozenxid) < 250M |
pg_statio_user_tables, pg_stat_user_tables, pg_database |
Trụ cột 4 — Phòng thí nghiệm Công nghiệp: db_internals_lab & Kiểm định 16/16 pytest#
4.1 Kiến trúc Gói & Hợp đồng An toàn Môi trường#
labs/lab-03-postgres-sqlalchemy-optimization/
├── pyproject.toml # PEP 621 src/ layout + sqlalchemy>=2.0 + ruff (ASYNC, S, RUF) + mypy strict
├── uv.lock # Tệp khóa phụ thuộc tái lập qua uv lock / uv sync --locked
├── README.md # Hướng dẫn thực hành 100% tiếng Việt
├── sql/
│ ├── 001_schema_and_indexes.sql # DDL, UUIDv7, fillfactor=75, CONCURRENTLY/INCLUDE/GIN/BRIN/HNSW, DCL/RLS
│ └── 002_explain_queries_and_tuning.sql # DML ON CONFLICT, DQL CTE/Window ROWS/LATERAL, Keyset, EXPLAIN, TCL SERIALIZABLE
├── sqlalchemy2_reference/
│ └── models_and_uow.py # SQLAlchemy 2.0 + PgBouncer + Alembic Expand-Contract (kiểm định AST & runtime import)
├── src/
│ └── db_internals_lab/
│ ├── __init__.py
│ ├── repository_and_uow.py # Pydantic v2, Protocol, UoW, Outbox, N+1 vs Eager, SIGTERM, check_db_readiness
│ └── mvcc_and_query_engine.py # MVCC 8 KiB, Write Skew SSI, HOT, TidStore/XID, B-Tree/UUIDv7, SQLite 20k, PgBouncer, --healthcheck
├── scripts/
│ └── run_lab_demo.py # CLI xuất artifacts/t2_ch03_workbench_results.json
├── tests/
│ └── test_db_internals_lab.py # 16 ca kiểm thử pytest + test SQLAlchemy 2.x sqlite:///:memory: + AST security scan
└── artifacts/
└── t2_ch03_workbench_results.json
Hợp đồng An toàn Môi trường: Trình quét AST trong Test 14 kiểm toán toàn bộ mã chạy trong src/, scripts/, và tests/ chỉ cấm các mô-đun giải tuần tự không an toàn (pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal). Test 12 kiểm định tĩnh sql/*.sql; Test 13 kiểm tra cả AST lẫn nạp thực thi sqlalchemy2_reference/models_and_uow.py; Test 15 chạy thực tế SQLAlchemy 2.x trên sqlite:///:memory: đo đếm truy vấn selectinload/joinedload/lazy="raise" vs. N+1; và Test 16 kiểm định SIGTERM + check_db_readiness (--healthcheck).
4.2 Thực thi CLI Workbench & Bảng 6 Chỉ số Thực nghiệm (artifacts/t2_ch03_workbench_results.json)#
python scripts/run_lab_demo.py --output artifacts/t2_ch03_workbench_results.json
Chỉ số KPI (artifacts/t2_ch03_workbench_results.json) |
Giá trị Đo kiểm Thực tế | Trạng thái |
|---|---|---|
kpi_hot_vs_non_hot_updates (HOT Updates ff=75 vs 100) |
100.0% vs 0.0% (-100.0% idx writes; 1,000 updates x 4 index: Non-HOT 4000 vs HOT 0 upd idx writes; pruned=970; total 4480 vs 480) |
ok (Đã xác minh) |
kpi_isolation_write_skew_ssi (Write Skew: Repeatable Read vs SSI) |
0 vs 1 active (SQLSTATE 40001; SI cho phép 2 cập nhật rời rạc kéo 2 -> 0; SSI bắt chu trình rw, hủy T2 và retry giữ >= 1) |
ok (Đã xác minh) |
kpi_sargable_and_keyset_sqlite (SQLite Query & Keyset 20k rows) |
0.45 -> 0.019 ms (23.5x seek; SARGable Covering 0.019 vs 0.518 ms, 27.0x; Keyset quét 20 dòng vs OFFSET 15020) |
ok (Đã xác minh) |
kpi_uuidv7_vs_uuidv4_wal (UUIDv7 vs UUIDv4 B-Tree WAL FPI) |
17.17 -> 0.91 MiB (-94.7% WAL; fill 71.4% -> 89.6%; cache hit 64.7% -> 98.9%; tỷ số FPI 30.7x) |
ok (Đã xác minh) |
kpi_n_plus_1_vs_selectinload (ORM N+1 vs selectinload 100 Orders) |
101 -> 2 SQL (-98.0%; VPC RTT 1.5 ms: 152.19 ms -> 3.55 ms; wire rows 600 vs joinedload 500) |
ok (Đã xác minh) |
kpi_pgbouncer_and_pgvector_rag (PgBouncer Pool & pgvector Recall@10) |
500 -> 32 conns (Recall 20%->100%; tiết kiệm 1404.0 MiB, 0 từ chối vs 300, p99 37.7 -> 6.3 ms; iterative_scan khôi phục 10/10 dòng ở s=2%) |
ok (Đã xác minh) |
4.3 Hợp đồng 16 Ca Kiểm thử pytest (tests/test_db_internals_lab.py)#
Toàn bộ 16/16 ca kiểm thử vượt qua trên máy chủ Windows (.venv Python 3.12.16, SQLAlchemy 2.1.x, uv.lock, 16 passed):
| # | Tên Hàm Kiểm thử (test_db_internals_lab.py) |
Khẳng định & Bất biến Bắt buộc |
|---|---|---|
| 1 | test_01_solid_protocol_pydantic_v2_and_fail_closed_uow_atomicity |
Kiểm tra ValidationError cho khóa lạ/ép kiểu/PgBouncer thiếu an toàn; xác minh InMemoryUnitOfWork & SqliteUnitOfWork cùng thỏa UnitOfWorkProtocol không kế thừa; và PlaceOrderService tự rollback() sạch đơn hàng + outbox khi lỗi. |
| 2 | test_02_dml_on_conflict_upsert_and_tcl_savepoint_rollback |
Xác nhận INSERT ... ON CONFLICT DO UPDATE cộng dồn số lượng an toàn trên SQLite, và chuỗi SAVEPOINT -> ROLLBACK TO SAVEPOINT -> RELEASE -> COMMIT + DELETE trong ROLLBACK. |
| 3 | test_03_mvcc_8kib_slotted_page_and_snapshot_visibility_rules |
Kiểm thử MVCCPageEngine trên trang 8192 B: tuple HEAP_XMIN_FROZEN luôn hiện, phiên bản đang cập nhật chưa commit ẩn với xip_list, và hiện ra sau commit kèm liên kết t_ctid. |
| 4 | test_04_isolation_write_skew_under_si_vs_ssi_40001_prevention |
Tái hiện REPEATABLE READ (SI) cho phép 2 giao dịch rời rạc đẩy active_replicas về 0 (Write Skew), trong khi SERIALIZABLE (SSI) phát hiện chu trình rw, ném 40001, và retry giữ active_replicas = 1. |
| 5 | test_05_hot_updates_fillfactor_75_vs_non_hot_index_amplification |
Xác nhận fillfactor=100 + sửa cột chỉ mục đạt 0.0% HOT (4,000 ghi chỉ mục cập nhật), trong khi fillfactor=75 + không sửa cột chỉ mục đạt >= 85% HOT và cắt giảm >= 80% ghi chỉ mục. |
| 6 | test_06_vacuum_tidstore_20x_memory_and_xid_wraparound_thresholds |
Kiểm định ngưỡng autovacuum (20,000,050 mặc định vs. 1,005,000 tinh chỉnh), PG 17 TidStore giảm 20.0x RAM (51.5 MB vs. 1,029.97 MB), ghim idle_tx, và phân loại đúng 4 mốc XID tới XID_STOP_LIMIT_SHUTDOWN. |
| 7 | test_07_btree_8kib_fanout_height_and_real_sqlite_sargable_covering_plan |
Xác nhận công thức trang 8152 B cho BIGINT (fanout=366, h=3) và khóa 32 B (h=4), cùng sqlite3 EXPLAIN QUERY PLAN đạt COVERING INDEX và nhanh hơn substr() >= 2.0x. |
| 8 | test_08_uuidv4_vs_uuidv7_leaf_fill_cache_and_fpi_wal_amplification |
Xác nhận trên 6,000 insert: UUIDv7 đạt mật độ lá >= 85% (vs <= 75% UUIDv4), cache hit cao hơn, và giảm >= 70% tổng WAL FPI (17.17 -> 0.91 MiB). |
| 9 | test_09_keyset_vs_offset_pagination_parity_and_window_rows_vs_range |
Kiểm chứng Keyset (created_at, id) < (?, ?) trả đúng hệt 20 dòng như OFFSET 15000, nhanh hơn >= 2.5x, và chứng minh RANGE mặc định trả 300 vs ROWS trả 100 trên khóa trùng. |
| 10 | test_10_pgbouncer_transaction_pooling_and_pgvector_filtered_recall |
Khẳng định PgBouncer giảm >= 90% backend (500 -> 32), 0 từ chối, giảm RAM & p99; và hnsw.iterative_scan cứu Recall@10 từ <= 0.4 lên 1.0 ở s=0.02. |
| 11 | test_11_real_sqlite_n_plus_1_vs_selectinload_and_joinedload |
Dùng sqlite3.set_trace_callback xác minh chính xác 101 câu SQL (N+1) vs 2 câu (selectinload, 600 dòng không nhân bản cha) vs 1 câu (joinedload, 500 dòng nhân bản cha 5x). |
| 12 | test_12_static_validation_of_sql_reference_scripts |
Kiểm tra cân bằng ngoặc và sự hiện diện đầy đủ 5 nhóm lệnh + từ khóa SOTA trong sql/001_schema_and_indexes.sql và sql/002_explain_queries_and_tuning.sql. |
| 13 | test_13_ast_and_runtime_validation_of_sqlalchemy2_reference |
Phân tích ast.parse lẫn nạp thực thi trực tiếp sqlalchemy2_reference/models_and_uow.py: xác nhận bảng orders/order_items/outbox_events và các mẫu DeclarativeBase, Mapped, lazy="raise", selectinload, NullPool, autocommit_block. |
| 14 | test_14_cli_demo_workbench_json_and_zero_forbidden_runtime_imports |
Chạy CLI run_lab_demo.py --quick kiểm định đủ 6 KPI, 4 bars, 4 tables và quét AST toàn bộ src/, scripts/, tests/ xác nhận 0 import giải tuần tự không an toàn (pickle, joblib, cloudpickle, dill, shelve, marshal). |
| 15 | test_15_real_sqlalchemy_sqlite_selectinload_vs_n_plus_1_and_lazy_raise |
Chạy SQLAlchemy 2.x thật trên sqlite:///:memory: với listener before_cursor_execute: chứng minh lazy="select" nổ 1 + N truy vấn, lazy="raise" ném InvalidRequestError, selectinload còn 2 SQL và joinedload còn 1 SQL. |
| 16 | test_16_sigterm_graceful_shutdown_and_db_readiness |
Kiểm định check_db_readiness (ready vs draining + PRAGMA integrity_check(1)), lắp/khôi phục SIGTERM/SIGINT (install_signal_handlers) và đầu dò CLI --healthcheck. |
Trụ cột 5 — Tài liệu Đọc SOTA 2024–2026 & Bài tập Đánh giá Năng lực#
5.1 Danh mục Tài liệu Kinh điển & SOTA 2024–2026 (Curated SOTA Reading List)#
- Berenson, H., Bernstein, P., Gray, J., Melton, J., O'Neil, E., & O'Neil, P. (ACM SIGMOD 1995) + Cahill, M. J., Röhm, U., & Fekete, A. D. (ACM TODS 2009). A Critique of ANSI SQL Isolation Levels & Serializable Isolation for Snapshot Databases (SSI).
Vì sao quan trọng: Chỉ ra lỗ hổng của chuẩn SQL-92 với Snapshot Isolation (Write Skew) và đặt nền tảng lý thuyếtSIREAD+ chu trìnhrw-antidependency mà PostgreSQLSERIALIZABLEhiện thực. - PostgreSQL Global Development Group (2023–2025) & Davis, K., Peabody, B., Leach, P. (IETF
RFC 9562, 05/2024). PostgreSQL 16, 17 & 18 Release Notes (pg_stat_io,TidStoreART,read_stream/ Nativeio_method, B-Tree Skip Scan,uuidv7(),NOT NULL NOT VALID) & Universally Unique IDentifiers (UUIDs).
Vì sao quan trọng: Ghi nhận bước nhảy vọt hiện đại hóa bộ nhớVACUUM, I/O bất đồng bộ và khóa chính tuần tự có dấu thời gian trong PostgreSQL 2024–2026. - Malkov, Y. A., & Yashunin, D. A. (
IEEE TPAMI, 2020) & Kane, A. (pgvectorv0.7–v0.8, 2024–2025) + Timescale (pgvectorscale/ DiskANN). Efficient and Robust Approximate Nearest Neighbor Search Using HNSW & Iterative Index Scans (hnsw.iterative_scan),halfvec, Binary Quantization.
Vì sao quan trọng: Giải mã toán học đồ thị tìm kiếm gần nhất và khắc phục triệt để thảm họa mất recall khi lọc đa khách hàng trên cơ sở dữ liệu vector lai. - Klitzke, E. (Uber Engineering, 2016), Cramer, D. (Sentry, 2015), Sinjakli, C. (GoCardless), & Freund, A. (
ProcArrayScalability, 2020). Postmortems & Architecture Deep-Dives on Non-HOT Write Amplification, XID Wraparound, FIFO Lock Queues, andmax_connectionsSnapshots.
Vì sao quan trọng: Nối liền từng byte cấu trúc nội tại của PostgreSQL với các sự cố sập sản xuất thực tế trị giá hàng triệu đô-la. - Bayer, M. et al. (
SQLAlchemy 2.0Documentation, 2023–2026) &PgBouncer 1.21+Contributors. AsyncIO ORM (DeclarativeBase,Mapped[],lazy="raise",selectinload), Alembicautocommit_block& Protocol-Levelmax_prepared_statements.
Vì sao quan trọng: Thiết lập chuẩn viết mã Python bất đồng bộ định kiểu tĩnh hoàn toàn, miễn nhiễm bão truy vấnN+1và nghẽnPgBouncer.
5.2 Tám Điểm Kiểm tra Tư duy (Q1–Q8) & Sáu Bài tập Trọng số#
- Q1 (SOLID,
Protocol& Fail-ClosedUnit of Work): Chứng minh vì sao Repository không được tự gọicommit(), cơ chếtyping.Protocoltách rời domain khỏi SQLAlchemy/SQLite, và tại sao mẫu Transactional Outbox xóa bỏ lỗi ghi kép (dual-write). - Q2 (5 Nhóm lệnh SQL & Bẫy Ngữ nghĩa): So sánh
TRUNCATEvs.DELETEtrên PostgreSQL, giải thích vì saoWHERE row_num = 1báo lỗi cú pháp theo thứ tự 9 bước DQL, bẫy cửa sổRANGEvs.ROWS, và giới hạn64subtransactionSAVEPOINTtrongPGPROC. - Q3 (8 KiB Page, MVCC Snapshot &
Write Skew): Phân tích cấu trúc24 Bheader +4 BItemIdData+24 Btuple header, quy tắc hiển thị(xmin, xmax, xip_list), và lý giải vì saoREPEATABLE READ(SI) để lọtWrite Skewtrong khiSERIALIZABLE(SSI) bắt qua chu trìnhrw(SQLSTATE 40001). - Q4 (
HOTUpdates,VACUUM TidStore&XID Wraparound): Nêu đủ 2 điều kiện củaHOT(cơ sở vụ Uber), vai trò củafillfactor = 75, cơ chếidle in transactionghimGlobalXmingây khóa ghi ởxidStopLimit, và cải tiến20xRAM củaTidStore(PG 17). - Q5 (B-Tree
8 KiB,INCLUDE,GINvs.BRIN): Tính toán chiều cao \(h = 3\) cho10MkhóaBIGINT, giải thích vì sao bảng chưaVACUUMbiến Index-Only Scan thành đọc heap hàng loạt, và so sánh bẫyGIN fastupdatevới điều kiện tương quan vật lý củaBRIN. - Q6 (
UUIDv7vs.UUIDv4& Phân trang Keyset): Lý giải cơ chếUUIDv4làm mật độ lá tụt xuống71.4%và thổi bùng17.17 MiBWAL FPI (+1,787%so vớiUUIDv70.91 MiB), đồng thời chứng minh độ phức tạp \(\Theta(N^2/m)\) củaOFFSETso với Seek(created_at, id) < (...). - Q7 (
EXPLAIN,PgBouncer&pgvectorHNSW): Chuyển vị từ phi-SARGable thành SARGable (27.0xnhanh hơn trong Lab 03), tính bộ nhớ và ngưỡng quá tảimax_connectionsvs.PgBouncer(500 -> 32), và giải thích cơ chếhnsw.iterative_scancứuRecall@10từ0.20lên1.00. - Q8 (
SQLAlchemy 2.0Async &AlembicExpand–Contract): Lý giải lỗiMissingGreenletkhi thiếuexpire_on_commit=False, đối chiếulazy="raise"+selectinloadvs.joinedload, xử lýDuplicatePreparedStatementErrorquaPgBouncer, và phác thảo quy trìnhlock_timeout+CONCURRENTLY+NOT VALID.
Sáu Bài tập Thực hành (Gợi ý Từng bước Tích hợp Tại Mục Quiz Cuối Trang)#
- Bài tập 1 (15 điểm) — Kiến trúc OOP
Protocol, Fail-ClosedUnit of Work& Transactional Outbox:- Bước thực hành: Định nghĩa
OrderCreateSpec(ConfigDict(extra="forbid", strict=True)), khởi tạoPlaceOrderServicelần lượt vớiInMemoryUnitOfWorkvàSqliteUnitOfWork(thỏa mãnUnitOfWorkProtocoltheo kiểu cấu trúc), chạy cả nhánhfail_after_order_insert=TruelẫnFalse, sau đó kiểm tra bảngordersvàoutbox_events. - Tiêu chí đạt: Chắc chắn
aborted_order_is_none == True(0bản ghi nửa vời), sự kiệnOrderPlacedchỉ xuất hiện khi giao dịchcommit(), và vượt trọn vẹntest_01.
- Bước thực hành: Định nghĩa
- Bài tập 2 (15 điểm) — Thực hành 5 Nhóm lệnh SQL (
ON CONFLICT,SAVEPOINT,ROWSvs.RANGE,RLS):- Bước thực hành: Thực thi
upsert_inventory_itemcộng dồn tồn kho nguyên tử; chạydemonstrate_tcl_savepoint_and_ddl_truncatequan sátSAVEPOINT -> ROLLBACK TO -> RELEASEcùngDELETEtrongROLLBACK; đối chiếu kết quả cửa sổ mặc địnhRANGEvsROWStrên cột khóa trùngts = 10(amt = 100, 200); và kiểm tra cân bằng ngoặc / đủ 5 nhóm lệnh trongsql/*.sql. - Tiêu chí đạt: Tổng tích lũy hàng đầu trả
300(RANGE) vs.100(ROWS),qty_after_commit == 8, và quatest_02+test_12.
- Bước thực hành: Thực thi
- Bài tập 3 (20 điểm) — Mô phỏng Trang
8 KiB,MVCC,Write Skew(SIvs.SSI) &HOT(fillfactor = 75):- Bước thực hành: Kiểm thử
MVCCPageEnginetrên trang8192 B(t_xmin,t_xmax,xip_list), chạysimulate_isolation_anomalies()tái hiệnREPEATABLE READ(SI) vs.SERIALIZABLE(SSISQLSTATE 40001), và chạysimulate_hot_vs_non_hot_updates()chofillfactor = 100(sửa cột index) vs.fillfactor = 75(cột ngoài index). - Tiêu chí đạt: Dưới
SIactive_replicastụt về0cònSSIgiữ1;fillfactor=75đạt100.0%HOT (0ghi chỉ mục cập nhật vs.4,000,pruned = 970) tạitest_03–test_05.
- Bước thực hành: Kiểm thử
- Bài tập 4 (15 điểm) — Tuổi
XID Wraparound,VACUUM TidStore(PG 17) & Hình học B-Tree /UUIDv7:- Bước thực hành: Gọi
compute_btree_geometry()tính fanout hiệu dụng ởfillfactor = 90%từ trang8152 Bkhả dụng choBIGINT(8 B) vs. composite32 Bở \(10^7\) dòng; chạysimulate_uuid_v4_vs_v7()(6,000inserts) vàsimulate_vacuum_and_xid_wraparound(). - Tiêu chí đạt: Đạt
fanout=366, h=3(BIGINT),UUIDv7tăng mật độ lá71.4% -> 89.6%và giảm-94.7%WAL FPI (17.17 -> 0.91 MiB),TidStoregiảm20.0xRAM (51.5 vs 1,029.97 MB), vượttest_06–test_08.
- Bước thực hành: Gọi
- Bài tập 5 (15 điểm) — Tối ưu Truy vấn Thực tế (
EXPLAIN QUERY PLAN, SARGable Covering Index & Keyset Seek):- Bước thực hành: Chạy
benchmark_sqlite_indexes_and_pagination(18_000, 2_000, 15_000)so sánh kế hoạchsubstr()vs. khoảng SARGable, đối chiếuOFFSET 15000vớiKeyset Seek (created_at, id) < (?, ?)trên bảng20,000dòng SQLite. - Tiêu chí đạt: Khớp kết quả trang 100% (
pagination_parity_exact == True), SARGable Covering đạt27.0x(0.518 -> 0.019 ms), Keyset Seek chỉ quét20dòng (0.019 ms, nhanh hơn23.5x), vượttest_07,test_09.
- Bước thực hành: Chạy
- Bài tập 6 (20 điểm) —
SQLAlchemy 2.0Thực chiến (sqlite:///:memory:), ChốngN+1,PgBouncer/pgvector,SIGTERM&16/16 pytest:- Bước thực hành: Thực thi
Test 13(AST + nạp thực thisqlalchemy2_reference/models_and_uow.py), chạyTest 15(SQLAlchemy 2.xin-memory với listenerbefore_cursor_executeđếm1 + Nvs2SQLselectinloadvs1SQLjoinedload+lazy="raise"), kiểm tracheck_db_readiness+SIGTERM(--healthcheck), chạyscripts/run_lab_demo.py,ruff check src tests scriptsvàpytest -p no:cacheprovider -v. - Tiêu chí đạt:
PgBouncergiảm500 -> 32backend (-93.6%),hnsw.iterative_scankéoRecall@10từ0.2lên1.0,ruff0 lỗi, AST 0 import giải tuần tự bị cấm (pickle,joblib,cloudpickle,dill,shelve,marshal), và16/16 pytestPASS.
- Bước thực hành: Thực thi
5.3 Thang Điểm & Tiêu chuẩn Nghiệm thu (Grading Rubric — 100 Điểm)#
| Hạng mục Đánh giá | Trọng số | Tiêu chí Đạt Chuẩn Nghiệm thu (>= 80/100) |
Lệnh / Ca Kiểm thử Đối chứng |
|---|---|---|---|
1. OOP (Protocol, UoW, Outbox) & 5 Nhóm lệnh SQL (ON CONFLICT, SAVEPOINT, Window) |
20 | Rollback nguyên tử fail-closed (0 ghi dở), ON CONFLICT & SAVEPOINT chuẩn xác, phân biệt ROWS vs RANGE, sql/*.sql đầy đủ từ khóa SOTA. |
Tests 1, 2, 12 |
2. MVCC 8 KiB, Write Skew (SI vs SSI) & HOT (fillfactor=75) |
20 | Xác định đúng snapshot (xmin, xmax, xip_list), chặn Write Skew bằng SSI (40001), đạt 100.0% HOT (0 ghi chỉ mục cập nhật). |
Tests 3, 4, 5 |
3. VACUUM TidStore, XID Wraparound, B-Tree 8152 B & UUIDv7 WAL |
20 | Tính đúng fanout h=3, TidStore giảm 20x RAM, ngưỡng XID chính xác, và UUIDv7 giảm -94.7% WAL FPI. |
Tests 6, 7, 8 |
4. SARGable EXPLAIN, Keyset Seek, PgBouncer & pgvector iterative_scan |
15 | Keyset khớp dữ liệu 100% (23.5x), COVERING INDEX (27.0x), PgBouncer 500 -> 32 (-1,404 MiB), và RAG Recall@10 = 1.0. |
Tests 7, 9, 10 |
5. SQLAlchemy 2.0 (sqlite:///:memory: selectinload/lazy="raise"), --healthcheck & 16/16 pytest |
25 | Nạp sạch models_and_uow.py; SQLAlchemy selectinload (2 SQL) / lazy="raise" đạt; SIGTERM + --healthcheck ready/draining; uv.lock + ruff 0 lỗi + 16/16 pytest. |
Tests 11, 13–16 + ruff check |
| Tổng cộng | 100 | Đạt tối thiểu 80/100 tổng điểm và không có mục nào 0 điểm (toàn bộ 16/16 test phải PASS). |
pytest -p no:cacheprovider -v |
Real SQLite Query Plan & Pagination Latency at 20,000 Rows (ms)
PostgreSQL 8 KiB Page Workload (120 Inserts + 1,000 Updates x 4 Indexes): Total Index Writes
SQLAlchemy Loading Modes (100 Orders x 5 Items, 1.5ms VPC RTT): Total Latency (ms)
B-Tree 6,000-Insert Checkpoint WAL Full-Page Image (FPI) Amplification (MiB)
PostgreSQL MVCC, Write Skew (SI vs SSI), HOT Pruning & PG 17 TidStore Vacuum
| subsystem_experiment | baseline_or_risk | optimized_or_guard | measured_invariant | status |
|---|---|---|---|---|
| write_skew_isolation | REPEATABLE READ (SI): 0 active | SERIALIZABLE (SSI): 1 active | SQLSTATE 40001 retry preserved invariant | SSI_VERIFIED |
| hot_updates_4_indexes | ff=100 idx_mut: 4000 writes | ff=75 non-idx: 0 writes | HOT=100.0%, pruned=970 | HOT_OPTIMAL |
| pg17_tidstore_180m_dead | Legacy array: 1029.97 MB (2 passes) | PG 17 TidStore: 51.5 MB | 20.0x less RAM (0 multi-pass) | ART_VERIFIED |
| xid_wraparound_horizon | idle_tx pins xmin: blocked=True | autovac_freeze=200M / failsafe=1.6B | 2.145B -> XID_STOP_LIMIT_SHUTDOWN | GUARD_ACTIVE |
B-Tree Geometry (8 KiB), UUIDv4 vs UUIDv7 & Real SQLite EXPLAIN QUERY PLAN
| benchmark_case | baseline_metric | optimized_metric | query_plan_or_ratio | verdict |
|---|---|---|---|---|
| btree_10m_bigint_8b | fanout=366 | height h=3 | 214.05 MB (76 upper pgs) | 3_HOP_SEEK |
| btree_10m_composite_32b | fanout=166 | height h=4 | 473.5 MB (367 upper pgs) | 4_HOP_SEEK |
| uuid_v4_vs_v7_6k_inserts | v4=17.17 MiB (hit 64.7%) | v7=0.91 MiB (hit 98.9%) | -94.7% WAL FPI | UUIDV7_WIN |
| sqlite_sargable_covering | substr()=0.543 ms | range=0.02 ms | SEARCH events USING COVERING INDEX ix_events_cov (tena | 27.8x_FASTER |
| sqlite_offset_vs_keyset | OFFSET 15000=0.481 ms | Keyset=0.02 ms | parity=True (23.8x) | O_LOG_N_SEEK |
SOLID UoW Fail-Closed Atomicity, TCL Savepoints & SQLAlchemy Eager Loading
| pattern_or_mode | sql_queries | latency_1_5ms_rtt | invariant_or_wire_rows | status |
|---|---|---|---|---|
| uow_crash_rollback_outbox | BEGIN IMMEDIATE -> ROLLBACK | 0 ms leaked | aborted_is_none=True, outbox=1 | ACID_ATOMIC |
| tcl_savepoint_and_upsert | SAVEPOINT -> ROLLBACK TO -> COMMIT | < 1 ms | final_sku_qty=8 | TCL_VERIFIED |
| orm_lazy_n_plus_1_storm | 101 queries | 152.25 ms | 100 extra child round-trips | ANTI_PATTERN |
| orm_selectinload_batched | 2 queries | 3.57 ms | 600 rows (0 parent dup) | SOTA_DEFAULT |
| orm_joinedload_left_join | 1 query | 2.29 ms | 500 wire rows (parent x5) | BEST_FOR_M_TO_1 |
PgBouncer Transaction Pooling (500 Clients) & pgvector HNSW Filtered RAG
| subsystem | naive_baseline | sota_configuration | delta_or_sla | status |
|---|---|---|---|---|
| pgbouncer_500_clients | Direct max=200: 300 rejected, 1700.0 MB | Tx pool=32: 0 rejected, 296.0 MB | -93.6% backends, p99 37.7->6.3 ms | POOL_SCALED |
| pgvector_filtered_s_2pct | Post-filter ef=40: 2/10 rows | iterative_scan: 10/10 rows | Recall@10 0.2 -> 1.0 (411 scanned) | RECALL_SAVED |
| window_rows_vs_range_trap | Default RANGE peer sum=300 | Explicit ROWS sum=100 | Prevents silent peer-grouping bug | SQL_VERIFIED |
03-track-2-data-and-ai-engineering/part-01-software-systems-foundations/labs/lab-03-postgres-sqlalchemy-optimization
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "db-internals-lab"
version = "0.1.0"
description = "FSDS-SOTA-2026 Track 2 Lab 03: Engineering OOP (SOLID/Protocol/Repository/UoW), SQL Command Groups, PostgreSQL MVCC/HOT/VACUUM, B-Tree/GIN/BRIN/HNSW, Keyset Pagination & SQLAlchemy 2.0"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"pydantic>=2.0",
"numpy>=1.24",
"pandas>=2.0",
"sqlalchemy>=2.0",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0",
]
[project.scripts]
fsds-db-lab = "db_internals_lab.mvcc_and_query_engine:main"
[tool.setuptools.packages.find]
where = ["src"]
[tool.ruff]
target-version = "py312"
line-length = 100
[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP", "ASYNC", "S", "RUF"]
ignore = ["S101", "S105", "S608", "E501"]
[tool.ruff.lint.per-file-ignores]
"tests/*.py" = ["S603"]
[tool.mypy]
python_version = "3.12"
strict = true
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-v"
-- ============================================================================
-- FSDS-SOTA-2026 Track 2 Lab 03 — Authentic PostgreSQL 17/18 + pgvector Schema
-- Covers: DDL, DCL (RLS), HOT-friendly fillfactor, UUIDv7, Composite/INCLUDE,
-- Partial, GIN, BRIN, HNSW halfvec indexes & Expand-Contract Constraints
-- ============================================================================
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE EXTENSION IF NOT EXISTS vector;
-- ----------------------------------------------------------------------------
-- 1. DDL: Core OLTP Tables (UUIDv7 temporal locality + HOT-friendly fillfactor)
-- ----------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS tenants (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
slug TEXT NOT NULL UNIQUE,
tier TEXT NOT NULL DEFAULT 'standard',
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS orders (
-- PostgreSQL 18 native monotonic uuidv7() eliminates UUIDv4 B-Tree FPI WAL bloat
id UUID PRIMARY KEY DEFAULT uuidv7(),
tenant_id BIGINT NOT NULL REFERENCES tenants(id),
status TEXT NOT NULL DEFAULT 'pending',
total_cents BIGINT NOT NULL CHECK (total_cents >= 0),
payload JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
) WITH (
-- Reserve 25% of every 8 KiB heap page for intra-page HOT tuple chains
fillfactor = 75,
autovacuum_vacuum_scale_factor = 0.01,
autovacuum_vacuum_threshold = 5000
);
CREATE TABLE IF NOT EXISTS order_items (
id UUID PRIMARY KEY DEFAULT uuidv7(),
order_id UUID NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
sku TEXT NOT NULL,
quantity INT NOT NULL CHECK (quantity > 0),
unit_price_cents BIGINT NOT NULL CHECK (unit_price_cents >= 0)
);
CREATE TABLE IF NOT EXISTS inventory_stock (
sku TEXT PRIMARY KEY,
available_qty INT NOT NULL CHECK (available_qty >= 0),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
) WITH (fillfactor = 70);
-- Transactional Outbox staged in the SAME Unit of Work ACID transaction
CREATE TABLE IF NOT EXISTS outbox_events (
id UUID PRIMARY KEY DEFAULT uuidv7(),
aggregate_type TEXT NOT NULL,
aggregate_id UUID NOT NULL,
event_type TEXT NOT NULL,
payload JSONB NOT NULL,
published_at TIMESTAMPTZ NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Append-only telemetry table ideal for BRIN index (high physical correlation)
CREATE TABLE IF NOT EXISTS audit_logs (
log_id BIGINT GENERATED ALWAYS AS IDENTITY,
tenant_id BIGINT NOT NULL,
action TEXT NOT NULL,
meta JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Hybrid Relational + Vector RAG storage using fp16 halfvec (50% RAM savings)
CREATE TABLE IF NOT EXISTS document_chunks (
id UUID PRIMARY KEY DEFAULT uuidv7(),
tenant_id BIGINT NOT NULL REFERENCES tenants(id),
doc_status TEXT NOT NULL DEFAULT 'published',
chunk_text TEXT NOT NULL,
embedding halfvec(1536) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- ----------------------------------------------------------------------------
-- 2. Zero-Downtime Indexes (CREATE INDEX CONCURRENTLY outside tx block)
-- ----------------------------------------------------------------------------
-- Composite ESR (Equality-Sort-Range) + Covering INCLUDE for Index-Only Scans
CREATE INDEX CONCURRENTLY IF NOT EXISTS ix_orders_tenant_created_cov
ON orders (tenant_id, created_at DESC, id DESC)
INCLUDE (status, total_cents);
-- Partial Index: Only 1-5% pending rows indexed -> keeps completed updates HOT!
CREATE INDEX CONCURRENTLY IF NOT EXISTS ix_orders_pending_only
ON orders (tenant_id, created_at)
WHERE status = 'pending';
-- Foreign key index preventing parent-delete Seq Scans & lock amplification
CREATE INDEX CONCURRENTLY IF NOT EXISTS ix_order_items_order_id
ON order_items (order_id);
-- GIN inverted index with compact jsonb_path_ops for @> containment queries
CREATE INDEX CONCURRENTLY IF NOT EXISTS ix_orders_payload_gin
ON orders USING gin (payload jsonb_path_ops)
WITH (fastupdate = on, gin_pending_list_limit = 4096);
-- BRIN index: stores (min, max) per 64 x 8 KiB = 512 KiB block range
CREATE INDEX CONCURRENTLY IF NOT EXISTS ix_audit_logs_created_brin
ON audit_logs USING brin (created_at)
WITH (pages_per_range = 64);
-- pgvector HNSW graph on fp16 halfvec embeddings
CREATE INDEX CONCURRENTLY IF NOT EXISTS ix_document_chunks_hnsw_cos
ON document_chunks USING hnsw (embedding halfvec_cosine_ops)
WITH (m = 16, ef_construction = 64);
-- ----------------------------------------------------------------------------
-- 3. Zero-Downtime Expand-Contract DDL Guardrails
-- ----------------------------------------------------------------------------
SET LOCAL lock_timeout = '2s';
SET LOCAL statement_timeout = '5s';
-- Instant metadata-only constant default (PG 11+)
ALTER TABLE orders
ADD COLUMN IF NOT EXISTS schema_version INT NOT NULL DEFAULT 2;
-- Two-phase constraint validation: NOT VALID (<1ms) -> VALIDATE (online scan)
ALTER TABLE orders
ADD CONSTRAINT chk_orders_schema_ver CHECK (schema_version >= 1) NOT VALID;
ALTER TABLE orders
VALIDATE CONSTRAINT chk_orders_schema_ver;
-- PostgreSQL 18 native non-blocking NOT NULL constraint validation
-- ALTER TABLE orders ADD CONSTRAINT nn_orders_status NOT NULL (status) NOT VALID;
-- ALTER TABLE orders VALIDATE CONSTRAINT nn_orders_status;
-- ----------------------------------------------------------------------------
-- 4. DCL: Least-Privilege Roles & Row-Level Security (RLS) w/ InitPlan Caching
-- ----------------------------------------------------------------------------
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'app_rw') THEN
CREATE ROLE app_rw NOINHERIT LOGIN;
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'analyst_ro') THEN
CREATE ROLE analyst_ro NOINHERIT;
END IF;
END $$;
GRANT USAGE ON SCHEMA public TO app_rw, analyst_ro;
GRANT SELECT, INSERT, UPDATE ON orders, order_items, outbox_events, document_chunks TO app_rw;
GRANT SELECT ON orders, audit_logs TO analyst_ro;
REVOKE DELETE, TRUNCATE ON audit_logs FROM PUBLIC, app_rw;
ALTER TABLE document_chunks ENABLE ROW LEVEL SECURITY;
ALTER TABLE document_chunks FORCE ROW LEVEL SECURITY;
-- Wrap current_setting() in scalar subselect so planner evaluates once (InitPlan)
DROP POLICY IF EXISTS p_chunks_tenant_iso ON document_chunks;
CREATE POLICY p_chunks_tenant_iso ON document_chunks
USING (tenant_id = (SELECT NULLIF(current_setting('app.tenant_id', true), '')::bigint))
WITH CHECK (tenant_id = (SELECT NULLIF(current_setting('app.tenant_id', true), '')::bigint));
-- ============================================================================
-- FSDS-SOTA-2026 Track 2 Lab 03 — DML, DQL, TCL, EXPLAIN & Diagnostics Playbook
-- ============================================================================
-- ----------------------------------------------------------------------------
-- 1. DML: Speculative Atomic UPSERT (ON CONFLICT) vs. TOCTOU Check-Then-Insert
-- ----------------------------------------------------------------------------
INSERT INTO inventory_stock (sku, available_qty, updated_at)
VALUES ('GPU-H100-NODE', 12, now())
ON CONFLICT (sku) DO UPDATE
SET
available_qty = inventory_stock.available_qty + EXCLUDED.available_qty,
updated_at = now();
-- ----------------------------------------------------------------------------
-- 2. DQL: CTEs (MATERIALIZED vs NOT MATERIALIZED), Window ROWS vs RANGE & LATERAL
-- ----------------------------------------------------------------------------
WITH recent_orders AS NOT MATERIALIZED (
-- Inlined in PG 12+: outer tenant_id predicate pushes down into covering index
SELECT id, tenant_id, total_cents, created_at
FROM orders
WHERE created_at >= now() - interval '30 days'
),
scored_orders AS (
SELECT
id,
tenant_id,
total_cents,
created_at,
ROW_NUMBER() OVER (PARTITION BY tenant_id ORDER BY total_cents DESC, id ASC) AS rn,
DENSE_RANK() OVER (PARTITION BY tenant_id ORDER BY total_cents DESC) AS drk,
LAG(total_cents, 1, 0) OVER (PARTITION BY tenant_id ORDER BY created_at ASC, id ASC) AS prev_cents,
-- Explicit ROWS frame avoids default RANGE peer-grouping pitfall on equal timestamps
SUM(total_cents) OVER (
PARTITION BY tenant_id
ORDER BY created_at ASC, id ASC
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_revenue_cents
FROM recent_orders
WHERE tenant_id = 42
)
SELECT id, total_cents, rn, drk, prev_cents, running_revenue_cents
FROM scored_orders
WHERE rn <= 10;
-- Correlated Top-N per tenant via LATERAL index seek: O(G * (log N + 3))
SELECT t.id AS tenant_id, t.slug, top_o.id AS order_id, top_o.total_cents, top_o.created_at
FROM tenants t
LEFT JOIN LATERAL (
SELECT o.id, o.total_cents, o.created_at
FROM orders o
WHERE o.tenant_id = t.id
ORDER BY o.created_at DESC, o.id DESC
LIMIT 3
) AS top_o ON TRUE;
-- ----------------------------------------------------------------------------
-- 3. Query Tuning: SARGable Range vs Non-SARGable + Keyset vs OFFSET + EXPLAIN
-- ----------------------------------------------------------------------------
-- ANTI-PATTERN (Non-SARGable -> forces Seq Scan):
-- EXPLAIN (ANALYZE, BUFFERS)
-- SELECT id, total_cents FROM orders WHERE EXTRACT(YEAR FROM created_at) = 2026;
-- SARGable + Covering Index-Only Scan:
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, status, total_cents, created_at
FROM orders
WHERE tenant_id = 42
AND created_at >= TIMESTAMPTZ '2026-01-01 00:00:00Z'
AND created_at < TIMESTAMPTZ '2027-01-01 00:00:00Z'
ORDER BY created_at DESC, id DESC
LIMIT 20;
-- ANTI-PATTERN (O(k + m) linear page scan & skip):
-- SELECT id, created_at, total_cents FROM orders
-- WHERE tenant_id = 42 ORDER BY created_at DESC, id DESC OFFSET 100000 LIMIT 20;
-- Keyset / Seek Pagination using Row-Value Comparison: O(log_B N + m) constant time
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, status, total_cents, created_at
FROM orders
WHERE tenant_id = 42
AND (created_at, id) < (TIMESTAMPTZ '2026-11-21 12:00:00Z', '01934f21-0000-7000-8000-000000000001'::uuid)
ORDER BY created_at DESC, id DESC
LIMIT 20;
-- Filtered pgvector HNSW recovery (prevents ef_search=40 post-filtering collapse)
BEGIN;
SET LOCAL hnsw.iterative_scan = 'relaxed_order';
SET LOCAL hnsw.ef_search = 80;
SET LOCAL hnsw.max_scan_tuples = 20000;
SELECT id, chunk_text
FROM document_chunks
WHERE tenant_id = 42
AND doc_status = 'published'
ORDER BY embedding <=> (SELECT embedding FROM document_chunks LIMIT 1)
LIMIT 10;
COMMIT;
-- ----------------------------------------------------------------------------
-- 4. TCL: Explicit Isolation (SSI), Savepoints (Watch 64 SubXID Limit) & Commit
-- ----------------------------------------------------------------------------
BEGIN;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SET LOCAL lock_timeout = '2s';
SAVEPOINT sp_reserve_sku;
UPDATE inventory_stock
SET available_qty = available_qty - 1, updated_at = now()
WHERE sku = 'GPU-H100-NODE' AND available_qty >= 1;
RELEASE SAVEPOINT sp_reserve_sku;
-- On SQLSTATE 40001 (serialization_failure), client MUST abort & retry with jitter!
COMMIT;
-- ----------------------------------------------------------------------------
-- 5. Production Observability: HOT Efficiency & XID Wraparound Horizon Audits
-- ----------------------------------------------------------------------------
SELECT
relname,
n_live_tup,
n_dead_tup,
n_tup_upd,
n_tup_hot_upd,
ROUND(100.0 * n_tup_hot_upd / NULLIF(n_tup_upd, 0), 2) AS hot_update_pct
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC;
SELECT
datname,
age(datfrozenxid) AS xid_age,
2147483647 - age(datfrozenxid) AS xids_remaining_before_wrap
FROM pg_database
ORDER BY age(datfrozenxid) DESC;
"""Authentic SQLAlchemy 2.0 + AsyncPG + PgBouncer + Alembic Expand-Contract Reference.
Validated both statically via AST inspection (Test 13) and at runtime import
using SQLAlchemy 2.x (with optional greenlet async extension guarded gracefully).
"""
from __future__ import annotations
from collections.abc import Sequence
from datetime import datetime
from typing import Any, Protocol
from uuid import UUID
import sqlalchemy as sa
from alembic import op
from sqlalchemy import BigInteger, ForeignKey, Index, Integer, String, func, select
from sqlalchemy.dialects.postgresql import JSONB
try:
from sqlalchemy.ext.asyncio import (
AsyncAttrs,
AsyncSession,
async_sessionmaker,
create_async_engine,
)
_HAS_ASYNC_SA = True
except ImportError: # pragma: no cover - greenlet is optional in sync test environments
_HAS_ASYNC_SA = False
class AsyncAttrs: # type: ignore[no-redef]
"""Fallback mixin when optional greenlet async extension is unavailable."""
AsyncSession = Any # type: ignore[assignment,misc]
async_sessionmaker = Any # type: ignore[assignment,misc]
create_async_engine = None # type: ignore[assignment]
from sqlalchemy.orm import (
DeclarativeBase,
Mapped,
joinedload,
mapped_column,
relationship,
selectinload,
)
from sqlalchemy.pool import NullPool
# ----------------------------------------------------------------------------
# 1. Strictly Typed SQLAlchemy 2.0 Declarative Models (lazy="raise" Guardrail)
# ----------------------------------------------------------------------------
class Base(AsyncAttrs, DeclarativeBase):
"""Typed declarative base enabling AsyncAttrs if explicit awaitable loads are used."""
class OrderModel(Base):
__tablename__ = "orders"
__table_args__ = (
Index("ix_orders_tenant_created_id", "tenant_id", "created_at", "id"),
)
id: Mapped[UUID] = mapped_column(primary_key=True, server_default=func.uuidv7())
tenant_id: Mapped[int] = mapped_column(BigInteger, nullable=False, index=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default="pending")
total_cents: Mapped[int] = mapped_column(BigInteger, nullable=False)
payload: Mapped[dict[str, object]] = mapped_column(JSONB, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(nullable=False, server_default=func.now())
# lazy="raise" turns silent N+1 regressions into immediate test-time errors
items: Mapped[list[OrderItemModel]] = relationship(
back_populates="order",
cascade="all, delete-orphan",
lazy="raise",
)
class OrderItemModel(Base):
__tablename__ = "order_items"
id: Mapped[UUID] = mapped_column(primary_key=True, server_default=func.uuidv7())
order_id: Mapped[UUID] = mapped_column(
ForeignKey("orders.id", ondelete="CASCADE"),
nullable=False,
index=True,
)
sku: Mapped[str] = mapped_column(String(64), nullable=False)
quantity: Mapped[int] = mapped_column(Integer, nullable=False)
unit_price_cents: Mapped[int] = mapped_column(BigInteger, nullable=False)
order: Mapped[OrderModel] = relationship(back_populates="items", lazy="raise")
class OutboxEventModel(Base):
__tablename__ = "outbox_events"
id: Mapped[UUID] = mapped_column(primary_key=True, server_default=func.uuidv7())
aggregate_id: Mapped[UUID] = mapped_column(nullable=False, index=True)
event_type: Mapped[str] = mapped_column(String(128), nullable=False)
payload: Mapped[dict[str, object]] = mapped_column(JSONB, nullable=False)
created_at: Mapped[datetime] = mapped_column(nullable=False, server_default=func.now())
# ----------------------------------------------------------------------------
# 2. PgBouncer Transaction-Mode Safe Async Engine + Session Factory
# ----------------------------------------------------------------------------
def build_pgbouncer_async_engine(dsn: str, pgbouncer_supports_prepared: bool = False):
"""Create an AsyncEngine safe under PgBouncer pool_mode=transaction.
- NullPool avoids double-pooling across FastAPI pods and PgBouncer.
- statement_cache_size=0 avoids DuplicatePreparedStatementError on PgBouncer <1.21.
- expire_on_commit=False prevents MissingGreenlet errors when reading attrs post-commit.
"""
cache_sz = 100 if pgbouncer_supports_prepared else 0
engine = create_async_engine(
dsn,
poolclass=NullPool,
connect_args={
"statement_cache_size": cache_sz,
"prepared_statement_cache_size": cache_sz,
"command_timeout": 10.0,
},
)
session_factory = async_sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False,
autoflush=False,
)
return engine, session_factory
# ----------------------------------------------------------------------------
# 3. Structural Repository Protocol + Async Unit of Work (Fail-Closed Rollback)
# ----------------------------------------------------------------------------
class AsyncOrderRepoProtocol(Protocol):
async def list_with_items_selectin(
self, tenant_id: int, limit: int = 50
) -> Sequence[OrderModel]: ...
async def get_item_with_parent_joined(self, item_id: UUID) -> OrderItemModel | None: ...
class SqlAlchemyOrderRepository:
def __init__(self, session: AsyncSession) -> None:
self._session = session
async def list_with_items_selectin(
self, tenant_id: int, limit: int = 50
) -> Sequence[OrderModel]:
"""Load 1-to-many collections in exactly 2 queries (SELECT orders + WHERE IN)."""
stmt = (
select(OrderModel)
.where(OrderModel.tenant_id == tenant_id)
.options(selectinload(OrderModel.items))
.order_by(OrderModel.created_at.desc(), OrderModel.id.desc())
.limit(limit)
)
return (await self._session.scalars(stmt)).all()
async def get_item_with_parent_joined(self, item_id: UUID) -> OrderItemModel | None:
"""Load many-to-1 scalar parent in 1 LEFT OUTER JOIN round-trip."""
stmt = (
select(OrderItemModel)
.where(OrderItemModel.id == item_id)
.options(joinedload(OrderItemModel.order))
)
return await self._session.scalar(stmt)
def add_order_and_outbox(self, order: OrderModel, event: OutboxEventModel) -> None:
self._session.add(order)
self._session.add(event)
class SqlAlchemyUnitOfWork:
def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
self._factory = session_factory
self._session: AsyncSession | None = None
self.orders: SqlAlchemyOrderRepository
async def __aenter__(self) -> SqlAlchemyUnitOfWork:
self._session = self._factory()
self.orders = SqlAlchemyOrderRepository(self._session)
return self
async def commit(self) -> None:
assert self._session is not None
await self._session.commit()
async def rollback(self) -> None:
assert self._session is not None
await self._session.rollback()
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
assert self._session is not None
try:
# Fail-closed: rollback on unhandled exception OR uncommitted exit
if exc_type is not None or self._session.in_transaction():
await self._session.rollback()
finally:
await self._session.close()
# ----------------------------------------------------------------------------
# 4. Zero-Downtime Alembic Expand-Contract Migration Recipe
# ----------------------------------------------------------------------------
def alembic_zero_downtime_upgrade() -> None:
"""Reference Alembic migration avoiding ACCESS EXCLUSIVE FIFO lock-queue pileups."""
# Phase A: Short lock_timeout + metadata-only constant default + NOT VALID check
op.execute("SET LOCAL lock_timeout = '2s';")
op.add_column(
"orders",
sa.Column("priority_tier", sa.Integer(), server_default="1", nullable=False),
)
op.create_check_constraint(
"chk_orders_priority_tier",
"orders",
"priority_tier BETWEEN 1 AND 5",
postgresql_not_valid=True,
)
op.execute("ALTER TABLE orders VALIDATE CONSTRAINT chk_orders_priority_tier;")
# Phase B: Concurrent index creation MUST run outside transaction block
with op.get_context().autocommit_block():
op.execute("SET LOCAL lock_timeout = '5s';")
op.create_index(
"ix_orders_priority_created",
"orders",
["priority_tier", "created_at"],
unique=False,
postgresql_concurrently=True,
)
"""FSDS-SOTA-2026 Track 2 Lab 03: Engineering OOP, SQL Command Groups, PostgreSQL Internals & SQLAlchemy 2.0 Patterns."""
from db_internals_lab.mvcc_and_query_engine import (
HeapTuple,
MVCCPageEngine,
SerializationError,
SlottedHeapPage,
Snapshot,
benchmark_sqlite_indexes_and_pagination,
compute_btree_geometry,
simulate_hot_vs_non_hot_updates,
simulate_isolation_anomalies,
simulate_pgbouncer_pool_collapse,
simulate_pgvector_filtered_recall,
simulate_uuid_v4_vs_v7,
simulate_vacuum_and_xid_wraparound,
)
from db_internals_lab.repository_and_uow import (
DatabaseConfigSpec,
InMemoryOrderRepository,
InMemoryOutboxRepository,
InMemoryUnitOfWork,
OrderCreateSpec,
OrderDTO,
OrderItemSpec,
OrderRepositoryProtocol,
OutboxEventDTO,
OutboxRepositoryProtocol,
PaginationQuerySpec,
PlaceOrderService,
PoolRoutingSpec,
SqliteOrderRepository,
SqliteOutboxRepository,
SqliteUnitOfWork,
UnitOfWorkProtocol,
benchmark_n_plus_1_vs_eager_loading,
check_db_readiness,
demonstrate_tcl_savepoint_and_ddl_truncate,
install_signal_handlers,
restore_signal_handlers,
upsert_inventory_item,
)
__all__ = [
"DatabaseConfigSpec",
"HeapTuple",
"InMemoryOrderRepository",
"InMemoryOutboxRepository",
"InMemoryUnitOfWork",
"MVCCPageEngine",
"OrderCreateSpec",
"OrderDTO",
"OrderItemSpec",
"OrderRepositoryProtocol",
"OutboxEventDTO",
"OutboxRepositoryProtocol",
"PaginationQuerySpec",
"PlaceOrderService",
"PoolRoutingSpec",
"SerializationError",
"SlottedHeapPage",
"Snapshot",
"SqliteOrderRepository",
"SqliteOutboxRepository",
"SqliteUnitOfWork",
"UnitOfWorkProtocol",
"benchmark_n_plus_1_vs_eager_loading",
"benchmark_sqlite_indexes_and_pagination",
"check_db_readiness",
"compute_btree_geometry",
"demonstrate_tcl_savepoint_and_ddl_truncate",
"install_signal_handlers",
"restore_signal_handlers",
"simulate_hot_vs_non_hot_updates",
"simulate_isolation_anomalies",
"simulate_pgbouncer_pool_collapse",
"simulate_pgvector_filtered_recall",
"simulate_uuid_v4_vs_v7",
"simulate_vacuum_and_xid_wraparound",
"upsert_inventory_item",
]
"""Engineering OOP (SOLID, typing.Protocol, Repository, Unit of Work) & SQLite ACID/SQL Groups."""
from __future__ import annotations
import json
import signal
import sqlite3
import threading
import time
from copy import deepcopy
from datetime import UTC, datetime
from pathlib import Path
from typing import Any, Literal, Protocol, runtime_checkable
from pydantic import BaseModel, ConfigDict, Field, model_validator
# ----------------------------------------------------------------------------
# 1. Pydantic v2 Strict Boundary Contracts (Zero Implicit Coercion / Extra Keys)
# ----------------------------------------------------------------------------
class DatabaseConfigSpec(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True, frozen=True)
db_path: str = Field(min_length=1)
journal_mode: Literal["WAL", "DELETE"] = "WAL"
fillfactor: int = Field(default=75, ge=50, le=100)
lock_timeout_ms: int = Field(default=2000, ge=100, le=60000)
class PaginationQuerySpec(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True, frozen=True)
tenant_id: int = Field(ge=1)
limit: int = Field(default=20, ge=1, le=500)
offset: int = Field(default=0, ge=0)
cursor_ts: str | None = None
cursor_id: int | None = None
@model_validator(mode="after")
def _validate_cursor_pair(self) -> PaginationQuerySpec:
if (self.cursor_ts is None) != (self.cursor_id is None):
raise ValueError("cursor_ts and cursor_id must be provided together for Keyset seek")
return self
class PoolRoutingSpec(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True, frozen=True)
app_clients: int = Field(ge=1, le=20000)
pgbouncer_pool_size: int = Field(ge=1, le=512)
pgbouncer_mode: Literal["transaction", "session"] = "transaction"
statement_cache_size: int = Field(ge=0, le=4096)
pgbouncer_supports_prepared: bool = False
@model_validator(mode="after")
def _check_prepared_statement_safety(self) -> PoolRoutingSpec:
if (
self.pgbouncer_mode == "transaction"
and not self.pgbouncer_supports_prepared
and self.statement_cache_size > 0
):
raise ValueError(
"PgBouncer <1.21 transaction pooling requires statement_cache_size=0 "
"to prevent DuplicatePreparedStatementError"
)
return self
class OrderItemSpec(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True, frozen=True)
sku: str = Field(min_length=2, max_length=64)
quantity: int = Field(ge=1, le=10000)
unit_price_cents: int = Field(ge=0)
class OrderCreateSpec(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True, frozen=True)
order_id: int = Field(ge=1)
tenant_id: int = Field(ge=1)
status: Literal["pending", "paid", "shipped", "cancelled"] = "pending"
created_at: str = Field(min_length=10)
items: tuple[OrderItemSpec, ...] = Field(min_length=1)
class OrderDTO(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True, frozen=True)
order_id: int
tenant_id: int
status: str
total_cents: int
created_at: str
items: tuple[OrderItemSpec, ...] = ()
class OutboxEventDTO(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True, frozen=True)
event_id: int
aggregate_id: int
event_type: str
payload_json: str
# ----------------------------------------------------------------------------
# 2. Structural Subtyping Contracts (typing.Protocol — Zero Inheritance Coupling)
# ----------------------------------------------------------------------------
@runtime_checkable
class OrderRepositoryProtocol(Protocol):
def add_order(self, spec: OrderCreateSpec) -> OrderDTO: ...
def get_order(self, order_id: int) -> OrderDTO | None: ...
def list_orders_for_tenant(self, tenant_id: int) -> list[OrderDTO]: ...
@runtime_checkable
class OutboxRepositoryProtocol(Protocol):
def append_event(self, aggregate_id: int, event_type: str, payload: dict[str, Any]) -> None: ...
def list_events(self) -> list[OutboxEventDTO]: ...
@runtime_checkable
class UnitOfWorkProtocol(Protocol):
orders: OrderRepositoryProtocol
outbox: OutboxRepositoryProtocol
def __enter__(self) -> UnitOfWorkProtocol: ...
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: ...
def commit(self) -> None: ...
def rollback(self) -> None: ...
# ----------------------------------------------------------------------------
# 3. Pure In-Memory Test Adapter (Satisfies Protocols Without Inheriting Anything)
# ----------------------------------------------------------------------------
class InMemoryOrderRepository:
def __init__(self, store: dict[int, OrderDTO]) -> None:
self._store = store
def add_order(self, spec: OrderCreateSpec) -> OrderDTO:
if spec.order_id in self._store:
raise ValueError(f"Duplicate order_id={spec.order_id}")
total = sum(it.quantity * it.unit_price_cents for it in spec.items)
dto = OrderDTO(
order_id=spec.order_id,
tenant_id=spec.tenant_id,
status=spec.status,
total_cents=total,
created_at=spec.created_at,
items=spec.items,
)
self._store[spec.order_id] = dto
return dto
def get_order(self, order_id: int) -> OrderDTO | None:
return self._store.get(order_id)
def list_orders_for_tenant(self, tenant_id: int) -> list[OrderDTO]:
return [o for o in self._store.values() if o.tenant_id == tenant_id]
class InMemoryOutboxRepository:
def __init__(self, events: list[OutboxEventDTO]) -> None:
self._events = events
def append_event(self, aggregate_id: int, event_type: str, payload: dict[str, Any]) -> None:
self._events.append(
OutboxEventDTO(
event_id=len(self._events) + 1,
aggregate_id=aggregate_id,
event_type=event_type,
payload_json=json.dumps(payload, sort_keys=True),
)
)
def list_events(self) -> list[OutboxEventDTO]:
return list(self._events)
class InMemoryUnitOfWork:
"""Transactional in-memory UoW using snapshot isolation and fail-closed rollback."""
def __init__(self) -> None:
self._committed_orders: dict[int, OrderDTO] = {}
self._committed_outbox: list[OutboxEventDTO] = []
self._staged_orders: dict[int, OrderDTO] = {}
self._staged_outbox: list[OutboxEventDTO] = []
self._committed = False
self.orders = InMemoryOrderRepository(self._staged_orders)
self.outbox = InMemoryOutboxRepository(self._staged_outbox)
def __enter__(self) -> InMemoryUnitOfWork:
self._staged_orders = deepcopy(self._committed_orders)
self._staged_outbox = deepcopy(self._committed_outbox)
self._committed = False
self.orders = InMemoryOrderRepository(self._staged_orders)
self.outbox = InMemoryOutboxRepository(self._staged_outbox)
return self
def commit(self) -> None:
self._committed_orders = deepcopy(self._staged_orders)
self._committed_outbox = deepcopy(self._staged_outbox)
self._committed = True
def rollback(self) -> None:
self._staged_orders = deepcopy(self._committed_orders)
self._staged_outbox = deepcopy(self._committed_outbox)
self.orders = InMemoryOrderRepository(self._staged_orders)
self.outbox = InMemoryOutboxRepository(self._staged_outbox)
self._committed = False
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
if exc_type is not None or not self._committed:
self.rollback()
# ----------------------------------------------------------------------------
# 4. SQLite Production Adapter (Explicit TCL BEGIN IMMEDIATE / COMMIT / ROLLBACK)
# ----------------------------------------------------------------------------
def initialize_lab_sqlite_schema(conn: sqlite3.Connection) -> None:
"""Create normalized OLTP tables, Transactional Outbox, inventory & composite indexes."""
conn.executescript(
"""
PRAGMA foreign_keys = ON;
CREATE TABLE IF NOT EXISTS orders (
id INTEGER PRIMARY KEY,
tenant_id INTEGER NOT NULL,
status TEXT NOT NULL,
total_cents INTEGER NOT NULL CHECK (total_cents >= 0),
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS order_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
order_id INTEGER NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
sku TEXT NOT NULL,
quantity INTEGER NOT NULL CHECK (quantity > 0),
unit_price_cents INTEGER NOT NULL CHECK (unit_price_cents >= 0)
);
CREATE TABLE IF NOT EXISTS outbox_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
aggregate_id INTEGER NOT NULL,
event_type TEXT NOT NULL,
payload_json TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS inventory_stock (
sku TEXT PRIMARY KEY,
available_qty INTEGER NOT NULL CHECK (available_qty >= 0),
updated_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS ix_orders_tenant_created_cov
ON orders (tenant_id, created_at DESC, id DESC, status, total_cents);
CREATE INDEX IF NOT EXISTS ix_order_items_order_id
ON order_items (order_id);
"""
)
class SqliteOrderRepository:
def __init__(self, conn: sqlite3.Connection) -> None:
self._conn = conn
def add_order(self, spec: OrderCreateSpec) -> OrderDTO:
total = sum(it.quantity * it.unit_price_cents for it in spec.items)
self._conn.execute(
"INSERT INTO orders (id, tenant_id, status, total_cents, created_at) VALUES (?, ?, ?, ?, ?)",
(spec.order_id, spec.tenant_id, spec.status, total, spec.created_at),
)
self._conn.executemany(
"INSERT INTO order_items (order_id, sku, quantity, unit_price_cents) VALUES (?, ?, ?, ?)",
[(spec.order_id, it.sku, it.quantity, it.unit_price_cents) for it in spec.items],
)
return OrderDTO(
order_id=spec.order_id,
tenant_id=spec.tenant_id,
status=spec.status,
total_cents=total,
created_at=spec.created_at,
items=spec.items,
)
def get_order(self, order_id: int) -> OrderDTO | None:
row = self._conn.execute(
"SELECT id, tenant_id, status, total_cents, created_at FROM orders WHERE id = ?",
(order_id,),
).fetchone()
if row is None:
return None
item_rows = self._conn.execute(
"SELECT sku, quantity, unit_price_cents FROM order_items WHERE order_id = ? ORDER BY id ASC",
(order_id,),
).fetchall()
items = tuple(
OrderItemSpec(sku=str(r[0]), quantity=int(r[1]), unit_price_cents=int(r[2]))
for r in item_rows
)
return OrderDTO(
order_id=int(row[0]),
tenant_id=int(row[1]),
status=str(row[2]),
total_cents=int(row[3]),
created_at=str(row[4]),
items=items,
)
def list_orders_for_tenant(self, tenant_id: int) -> list[OrderDTO]:
order_rows = self._conn.execute(
"SELECT id, tenant_id, status, total_cents, created_at FROM orders "
"WHERE tenant_id = ? ORDER BY created_at DESC, id DESC",
(tenant_id,),
).fetchall()
if not order_rows:
return []
order_ids = [int(r[0]) for r in order_rows]
placeholders = ",".join("?" for _ in order_ids)
item_rows = self._conn.execute(
f"SELECT order_id, sku, quantity, unit_price_cents FROM order_items "
f"WHERE order_id IN ({placeholders}) ORDER BY id ASC",
order_ids,
).fetchall()
by_order: dict[int, list[OrderItemSpec]] = {oid: [] for oid in order_ids}
for r in item_rows:
by_order[int(r[0])].append(
OrderItemSpec(sku=str(r[1]), quantity=int(r[2]), unit_price_cents=int(r[3]))
)
return [
OrderDTO(
order_id=int(r[0]),
tenant_id=int(r[1]),
status=str(r[2]),
total_cents=int(r[3]),
created_at=str(r[4]),
items=tuple(by_order[int(r[0])]),
)
for r in order_rows
]
class SqliteOutboxRepository:
def __init__(self, conn: sqlite3.Connection) -> None:
self._conn = conn
def append_event(self, aggregate_id: int, event_type: str, payload: dict[str, Any]) -> None:
now_iso = datetime.now(UTC).isoformat()
self._conn.execute(
"INSERT INTO outbox_events (aggregate_id, event_type, payload_json, created_at) "
"VALUES (?, ?, ?, ?)",
(aggregate_id, event_type, json.dumps(payload, sort_keys=True), now_iso),
)
def list_events(self) -> list[OutboxEventDTO]:
rows = self._conn.execute(
"SELECT id, aggregate_id, event_type, payload_json FROM outbox_events ORDER BY id ASC"
).fetchall()
return [
OutboxEventDTO(
event_id=int(r[0]),
aggregate_id=int(r[1]),
event_type=str(r[2]),
payload_json=str(r[3]),
)
for r in rows
]
class SqliteUnitOfWork:
"""Explicit TCL-managed SQLite Unit of Work guaranteeing fail-closed rollback."""
def __init__(self, db_path: str | Path) -> None:
self._db_path = str(db_path)
self._conn: sqlite3.Connection | None = None
self._committed = False
self.orders: SqliteOrderRepository | None = None
self.outbox: SqliteOutboxRepository | None = None
def __enter__(self) -> SqliteUnitOfWork:
self._conn = sqlite3.connect(self._db_path, isolation_level=None)
self._conn.execute("PRAGMA foreign_keys = ON;")
if self._db_path != ":memory:":
self._conn.execute("PRAGMA journal_mode = WAL;")
initialize_lab_sqlite_schema(self._conn)
self._conn.execute("BEGIN IMMEDIATE;")
self._committed = False
self.orders = SqliteOrderRepository(self._conn)
self.outbox = SqliteOutboxRepository(self._conn)
return self
def commit(self) -> None:
assert self._conn is not None
self._conn.execute("COMMIT;")
self._committed = True
def rollback(self) -> None:
if self._conn is not None and self._conn.in_transaction:
self._conn.execute("ROLLBACK;")
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
try:
if exc_type is not None or not self._committed:
self.rollback()
finally:
if self._conn is not None:
self._conn.close()
self._conn = None
# ----------------------------------------------------------------------------
# 5. Domain Service (Depends ONLY on UnitOfWorkProtocol — DIP / OCP / SRP)
# ----------------------------------------------------------------------------
class PlaceOrderService:
"""Orchestrates atomic order creation + Transactional Outbox staging."""
def __init__(self, uow_factory: Any) -> None:
self._uow_factory = uow_factory
def place_order(self, spec: OrderCreateSpec, fail_after_order_insert: bool = False) -> OrderDTO:
with self._uow_factory() as raw_uow:
uow: UnitOfWorkProtocol = raw_uow
order = uow.orders.add_order(spec)
if fail_after_order_insert:
raise RuntimeError("Simulated downstream validation crash before outbox/commit")
uow.outbox.append_event(
aggregate_id=order.order_id,
event_type="OrderPlaced",
payload={"tenant_id": order.tenant_id, "total_cents": order.total_cents},
)
uow.commit()
return order
# ----------------------------------------------------------------------------
# 6. DML Speculative UPSERT & TCL Savepoint Demonstrations
# ----------------------------------------------------------------------------
def upsert_inventory_item(
conn: sqlite3.Connection, sku: str, delta_qty: int, updated_at: str
) -> int:
"""Idempotent DML INSERT ... ON CONFLICT DO UPDATE (eliminates check-then-insert TOCTOU)."""
conn.execute(
"""
INSERT INTO inventory_stock (sku, available_qty, updated_at)
VALUES (?, ?, ?)
ON CONFLICT(sku) DO UPDATE SET
available_qty = inventory_stock.available_qty + excluded.available_qty,
updated_at = excluded.updated_at;
""",
(sku, delta_qty, updated_at),
)
row = conn.execute(
"SELECT available_qty FROM inventory_stock WHERE sku = ?",
(sku,),
).fetchone()
return int(row[0]) if row else 0
def demonstrate_tcl_savepoint_and_ddl_truncate(db_path: str | Path) -> dict[str, Any]:
"""Verify TCL BEGIN/SAVEPOINT/ROLLBACK TO/RELEASE/COMMIT + DML vs DDL row counts."""
conn = sqlite3.connect(str(db_path), isolation_level=None)
try:
initialize_lab_sqlite_schema(conn)
conn.execute("BEGIN;")
upsert_inventory_item(conn, "GPU-H100", 8, "2026-11-21T10:00:00Z")
conn.execute("SAVEPOINT sp_bad_adjust;")
upsert_inventory_item(conn, "GPU-H100", 99, "2026-11-21T10:00:05Z")
qty_before_sp_rollback = int(
conn.execute("SELECT available_qty FROM inventory_stock WHERE sku = 'GPU-H100'").fetchone()[0]
)
conn.execute("ROLLBACK TO SAVEPOINT sp_bad_adjust;")
conn.execute("RELEASE SAVEPOINT sp_bad_adjust;")
conn.execute("COMMIT;")
qty_after_commit = int(
conn.execute("SELECT available_qty FROM inventory_stock WHERE sku = 'GPU-H100'").fetchone()[0]
)
# DML DELETE inside ROLLBACK restores deleted rows (transactional!)
conn.execute("BEGIN;")
conn.execute("DELETE FROM inventory_stock;")
count_mid_delete = int(conn.execute("SELECT COUNT(*) FROM inventory_stock").fetchone()[0])
conn.execute("ROLLBACK;")
count_after_rollback = int(conn.execute("SELECT COUNT(*) FROM inventory_stock").fetchone()[0])
return {
"qty_before_sp_rollback": qty_before_sp_rollback,
"qty_after_commit": qty_after_commit,
"count_mid_delete": count_mid_delete,
"count_after_rollback": count_after_rollback,
}
finally:
conn.close()
# ----------------------------------------------------------------------------
# 7. Real SQLite N+1 Query Storm vs. selectinload (IN) vs. joinedload (LEFT JOIN)
# ----------------------------------------------------------------------------
def benchmark_n_plus_1_vs_eager_loading(
n_orders: int = 100, items_per_order: int = 5, repeats: int = 10
) -> dict[str, Any]:
"""Measure exact SQL round-trip counts and latency on real sqlite3 tables."""
conn = sqlite3.connect(":memory:")
initialize_lab_sqlite_schema(conn)
# Seed target tenant=42 (n_orders) + noise tenants (400 orders)
order_rows: list[tuple[int, int, str, int, str]] = []
item_rows: list[tuple[int, str, int, int]] = []
oid = 1
for t_id, count in ((42, n_orders), (99, 400)):
for i in range(count):
ts = f"2026-11-{(i % 28) + 1:02d}T{(i % 24):02d}:00:00Z"
order_rows.append((oid, t_id, "paid", 5000 + i, ts))
for k in range(items_per_order):
item_rows.append((oid, f"SKU-{k:02d}", 1 + (k % 3), 1000))
oid += 1
conn.executemany(
"INSERT INTO orders (id, tenant_id, status, total_cents, created_at) VALUES (?, ?, ?, ?, ?)",
order_rows,
)
conn.executemany(
"INSERT INTO order_items (order_id, sku, quantity, unit_price_cents) VALUES (?, ?, ?, ?)",
item_rows,
)
conn.commit()
sql_counter = 0
def _trace(_sql: str) -> None:
nonlocal sql_counter
sql_counter += 1
conn.set_trace_callback(_trace)
# Mode 1: N+1 Anti-pattern (1 parent SELECT + N child SELECTs)
sql_counter = 0
t0 = time.perf_counter()
n1_items_total = 0
for _ in range(repeats):
parents = conn.execute(
"SELECT id, status, total_cents, created_at FROM orders WHERE tenant_id = ? "
"ORDER BY created_at DESC, id DESC LIMIT ?",
(42, n_orders),
).fetchall()
for p in parents:
children = conn.execute(
"SELECT sku, quantity, unit_price_cents FROM order_items WHERE order_id = ?",
(p[0],),
).fetchall()
n1_items_total = len(children)
n1_ms = ((time.perf_counter() - t0) * 1000.0) / repeats
n1_queries = sql_counter // repeats
# Mode 2: selectinload Pattern (1 parent SELECT + 1 batched WHERE order_id IN (...))
sql_counter = 0
t0 = time.perf_counter()
sel_wire_rows = 0
for _ in range(repeats):
parents = conn.execute(
"SELECT id, status, total_cents, created_at FROM orders WHERE tenant_id = ? "
"ORDER BY created_at DESC, id DESC LIMIT ?",
(42, n_orders),
).fetchall()
ids = [p[0] for p in parents]
placeholders = ",".join("?" for _ in ids)
children = conn.execute(
f"SELECT order_id, sku, quantity, unit_price_cents FROM order_items "
f"WHERE order_id IN ({placeholders})",
ids,
).fetchall()
sel_wire_rows = len(parents) + len(children)
selectin_ms = ((time.perf_counter() - t0) * 1000.0) / repeats
selectin_queries = sql_counter // repeats
# Mode 3: joinedload Pattern (1 LEFT OUTER JOIN query -> duplicates parent columns!)
sql_counter = 0
t0 = time.perf_counter()
joined_wire_rows = 0
for _ in range(repeats):
joined = conn.execute(
"SELECT o.id, o.status, o.total_cents, o.created_at, i.sku, i.quantity, i.unit_price_cents "
"FROM (SELECT id, status, total_cents, created_at FROM orders WHERE tenant_id = ? "
"ORDER BY created_at DESC, id DESC LIMIT ?) AS o "
"LEFT JOIN order_items i ON i.order_id = o.id",
(42, n_orders),
).fetchall()
joined_wire_rows = len(joined)
joined_ms = ((time.perf_counter() - t0) * 1000.0) / repeats
joined_queries = sql_counter // repeats
conn.set_trace_callback(None)
conn.close()
# Simulated network RTT impact at 1.5 ms per DB round-trip (typical VPC/AZ RTT)
vpc_rtt_ms = 1.5
n1_with_rtt_ms = round(n1_ms + n1_queries * vpc_rtt_ms, 2)
selectin_with_rtt_ms = round(selectin_ms + selectin_queries * vpc_rtt_ms, 2)
joined_with_rtt_ms = round(joined_ms + joined_queries * vpc_rtt_ms, 2)
query_reduction_pct = round(100.0 * (1.0 - selectin_queries / max(1, n1_queries)), 1)
return {
"n_orders": n_orders,
"items_per_order": items_per_order,
"n_plus_1_queries": n1_queries,
"selectinload_queries": selectin_queries,
"joinedload_queries": joined_queries,
"query_reduction_pct": query_reduction_pct,
"n_plus_1_local_ms": round(n1_ms, 3),
"selectinload_local_ms": round(selectin_ms, 3),
"joinedload_local_ms": round(joined_ms, 3),
"local_speedup": round(n1_ms / max(1e-6, selectin_ms), 2),
"n_plus_1_vpc_rtt_ms": n1_with_rtt_ms,
"selectinload_vpc_rtt_ms": selectin_with_rtt_ms,
"joinedload_vpc_rtt_ms": joined_with_rtt_ms,
"selectinload_wire_rows": sel_wire_rows,
"joinedload_wire_rows": joined_wire_rows,
"last_order_items": n1_items_total,
}
def install_signal_handlers(stop_event: threading.Event) -> dict[int, Any]:
"""Register SIGTERM/SIGINT handlers setting stop_event for graceful shutdown."""
previous: dict[int, Any] = {}
def _handle_signal(_signum: int, _frame: Any) -> None:
stop_event.set()
for sig in (signal.SIGTERM, signal.SIGINT):
try:
previous[sig] = signal.getsignal(sig)
signal.signal(sig, _handle_signal)
except (ValueError, OSError, AttributeError):
continue
return previous
def restore_signal_handlers(previous_handlers: dict[int, Any]) -> None:
"""Restore previously registered signal handlers after CLI shutdown."""
for sig, handler in previous_handlers.items():
try:
signal.signal(sig, handler)
except (ValueError, OSError, AttributeError):
continue
def check_db_readiness(
db_path: str | Path = ":memory:",
*,
stop_event: threading.Event | None = None,
timeout_sec: float = 2.0,
) -> dict[str, Any]:
"""Run lightweight readiness probe against SQLite store and shutdown signal state."""
shutting_down = bool(stop_event is not None and stop_event.is_set())
started = time.perf_counter()
db_ok = False
integrity_status = "unknown"
error_message: str | None = None
target = str(db_path)
conn: sqlite3.Connection | None = None
try:
conn = sqlite3.connect(target, timeout=max(0.1, float(timeout_sec)))
ping_row = conn.execute("SELECT 1;").fetchone()
integrity_row = conn.execute("PRAGMA integrity_check(1);").fetchone()
integrity_status = str(integrity_row[0]) if integrity_row else "unknown"
db_ok = bool(ping_row == (1,) and integrity_status.lower() == "ok")
except sqlite3.Error as exc:
error_message = str(exc)
db_ok = False
finally:
if conn is not None:
conn.close()
latency_ms = round((time.perf_counter() - started) * 1000.0, 3)
ready = bool(db_ok and not shutting_down)
status = "draining" if shutting_down else ("ready" if ready else "unhealthy")
payload: dict[str, Any] = {
"status": status,
"ready": ready,
"shutting_down": shutting_down,
"db_ok": db_ok,
"integrity_check": integrity_status,
"db_path": target,
"latency_ms": latency_ms,
}
if error_message is not None:
payload["error"] = error_message
return payload
"""PostgreSQL MVCC, 8 KiB Slotted Pages, Isolation/SSI, HOT, VACUUM/XID, B-Tree, Pagination & Pool Engine."""
from __future__ import annotations
import math
import sqlite3
import time
from collections import OrderedDict
from dataclasses import dataclass, field
from typing import Any
import numpy as np
# ----------------------------------------------------------------------------
# 1. PostgreSQL 8 KiB Slotted Heap Page & MVCC Snapshot Visibility Engine
# ----------------------------------------------------------------------------
PAGE_SIZE_BYTES = 8192
PAGE_HEADER_BYTES = 24
ITEM_ID_BYTES = 4
TUPLE_HEADER_BYTES = 24 # MAXALIGN_8(23 B HeapTupleHeaderData)
HEAP_XMIN_COMMITTED = 0x0100
HEAP_XMIN_INVALID = 0x0200
HEAP_XMIN_FROZEN = 0x0300
HEAP_XMAX_COMMITTED = 0x0400
HEAP_XMAX_INVALID = 0x0800
HEAP_HOT_UPDATED = 0x4000
HEAP_ONLY_TUPLE = 0x8000
class SerializationError(RuntimeError):
"""Emulates PostgreSQL SQLSTATE 40001 (serialization_failure)."""
def __init__(self, message: str, sqlstate: str = "40001") -> None:
super().__init__(f"[{sqlstate}] {message}")
self.sqlstate = sqlstate
@dataclass(frozen=True, slots=True)
class Snapshot:
xmin: int
xmax: int
xip_list: frozenset[int]
current_xid: int
current_cid: int = 0
@dataclass(slots=True)
class HeapTuple:
tuple_id: int
tid: tuple[int, int] # (block_number, offset_index)
t_xmin: int
t_xmax: int
t_cid: int
t_ctid: tuple[int, int]
t_infomask: int
payload_bytes: int
data: dict[str, Any]
@dataclass(slots=True)
class SlottedHeapPage:
page_id: int
fillfactor: int = 100
pd_lower: int = PAGE_HEADER_BYTES
pd_upper: int = PAGE_SIZE_BYTES
line_pointers: list[tuple[str, int]] = field(default_factory=list) # (LP_NORMAL|LP_REDIRECT|LP_DEAD, idx_or_len)
tuples: dict[int, HeapTuple] = field(default_factory=dict)
@property
def raw_free_bytes(self) -> int:
return max(0, self.pd_upper - self.pd_lower)
@property
def usable_insert_ceiling(self) -> int:
# Leave (100 - fillfactor)% reserved for HOT updates when inserting fresh rows
reserved = int((PAGE_SIZE_BYTES - PAGE_HEADER_BYTES) * ((100 - self.fillfactor) / 100.0))
return max(0, self.raw_free_bytes - reserved)
def can_fit_insert(self, payload_bytes: int) -> bool:
needed = ITEM_ID_BYTES + TUPLE_HEADER_BYTES + payload_bytes
return self.usable_insert_ceiling >= needed
def can_fit_hot_update(self, payload_bytes: int) -> bool:
# HOT updates MAY consume the fillfactor reserve on the same 8 KiB page!
needed = ITEM_ID_BYTES + TUPLE_HEADER_BYTES + payload_bytes
return self.raw_free_bytes >= needed
class MVCCPageEngine:
"""Simulates PostgreSQL 8 KiB page storage, MVCC snapshot visibility, HOT & pruning."""
def __init__(self, fillfactor: int = 100, n_indexes: int = 4) -> None:
self.fillfactor = fillfactor
self.n_indexes = n_indexes
self.pages: list[SlottedHeapPage] = [SlottedHeapPage(page_id=0, fillfactor=fillfactor)]
self.committed_xids: set[int] = {1, 2}
self.aborted_xids: set[int] = set()
self.next_xid: int = 100
self.next_tuple_id: int = 1
self.index_writes: int = 0
self.hot_updates: int = 0
self.non_hot_updates: int = 0
self.pruned_dead_tuples: int = 0
def allocate_xid(self) -> int:
xid = self.next_xid
self.next_xid += 1
return xid
def commit_xid(self, xid: int) -> None:
self.committed_xids.add(xid)
def abort_xid(self, xid: int) -> None:
self.aborted_xids.add(xid)
def xid_visible_in_snap(self, xid: int, snap: Snapshot) -> bool:
if xid == 0:
return False
if xid >= snap.xmax:
return False
if xid in snap.xip_list:
return False
return xid in self.committed_xids
def is_tuple_visible(self, tup: HeapTuple, snap: Snapshot) -> bool:
"""Exact PostgreSQL HeapTupleSatisfiesMVCC visibility semantics."""
xmin_frozen = (tup.t_infomask & HEAP_XMIN_FROZEN) == HEAP_XMIN_FROZEN
xmin_ok = False
if xmin_frozen or (tup.t_infomask & HEAP_XMIN_COMMITTED):
xmin_ok = True
elif tup.t_xmin == snap.current_xid and tup.t_cid < snap.current_cid:
xmin_ok = True
elif self.xid_visible_in_snap(tup.t_xmin, snap):
xmin_ok = True
if not xmin_ok:
return False
# Creator is visible; now check whether deleter (t_xmax) is visible
if tup.t_xmax == 0 or (tup.t_infomask & HEAP_XMAX_INVALID):
return True
if tup.t_xmax == snap.current_xid:
return tup.t_cid >= snap.current_cid
return not self.xid_visible_in_snap(tup.t_xmax, snap)
def _append_tuple_to_page(
self, page: SlottedHeapPage, xid: int, cid: int, payload_bytes: int, data: dict[str, Any], infomask: int
) -> HeapTuple:
off = len(page.line_pointers) + 1
tid = (page.page_id, off)
tup = HeapTuple(
tuple_id=self.next_tuple_id,
tid=tid,
t_xmin=xid,
t_xmax=0,
t_cid=cid,
t_ctid=tid,
t_infomask=infomask,
payload_bytes=payload_bytes,
data=dict(data),
)
self.next_tuple_id += 1
page.line_pointers.append(("LP_NORMAL", off))
page.pd_lower += ITEM_ID_BYTES
page.pd_upper -= TUPLE_HEADER_BYTES + payload_bytes
page.tuples[off] = tup
return tup
def insert_tuple(
self, xid: int, data: dict[str, Any], payload_bytes: int = 104, cid: int = 0
) -> HeapTuple:
target = self.pages[-1]
if not target.can_fit_insert(payload_bytes):
target = SlottedHeapPage(page_id=len(self.pages), fillfactor=self.fillfactor)
self.pages.append(target)
tup = self._append_tuple_to_page(target, xid, cid, payload_bytes, data, infomask=0)
self.index_writes += self.n_indexes
return tup
def prune_page_hot(self, page: SlottedHeapPage, oldest_active_xmin: int) -> int:
"""Opportunistic single-page HOT pruning: reclaims dead versions without touching indexes."""
reclaimed = 0
for off, (lp_state, _val) in enumerate(page.line_pointers, start=1):
if lp_state != "LP_NORMAL":
continue
tup = page.tuples.get(off)
if tup is None or tup.t_xmax == 0:
continue
if tup.t_xmax in self.committed_xids and tup.t_xmax < oldest_active_xmin:
# Reclaim old version bytes & turn slot into 0-byte LP_REDIRECT if HOT
reclaimed_bytes = TUPLE_HEADER_BYTES + tup.payload_bytes
if (tup.t_infomask & HEAP_HOT_UPDATED) and tup.t_ctid[0] == page.page_id:
page.line_pointers[off - 1] = ("LP_REDIRECT", tup.t_ctid[1])
else:
page.line_pointers[off - 1] = ("LP_DEAD", 0)
page.pd_upper = min(PAGE_SIZE_BYTES, page.pd_upper + reclaimed_bytes)
del page.tuples[off]
reclaimed += 1
self.pruned_dead_tuples += 1
return reclaimed
def update_tuple(
self,
old_tup: HeapTuple,
xid: int,
new_data: dict[str, Any],
indexed_column_changed: bool,
oldest_active_xmin: int,
cid: int = 0,
) -> tuple[HeapTuple, bool]:
"""Execute PostgreSQL DELETE+INSERT update with HOT check + page pruning."""
page = self.pages[old_tup.tid[0]]
if not page.can_fit_hot_update(old_tup.payload_bytes):
self.prune_page_hot(page, oldest_active_xmin)
is_hot = (not indexed_column_changed) and page.can_fit_hot_update(old_tup.payload_bytes)
old_tup.t_xmax = xid
if is_hot:
old_tup.t_infomask |= HEAP_HOT_UPDATED
new_tup = self._append_tuple_to_page(
page,
xid=xid,
cid=cid,
payload_bytes=old_tup.payload_bytes,
data=new_data,
infomask=HEAP_ONLY_TUPLE,
)
old_tup.t_ctid = new_tup.tid
self.hot_updates += 1
return new_tup, True
# Non-HOT: place on target page with space & rewrite ALL c secondary indexes!
target = self.pages[-1]
if not target.can_fit_hot_update(old_tup.payload_bytes):
target = SlottedHeapPage(page_id=len(self.pages), fillfactor=self.fillfactor)
self.pages.append(target)
new_tup = self._append_tuple_to_page(
target,
xid=xid,
cid=cid,
payload_bytes=old_tup.payload_bytes,
data=new_data,
infomask=0,
)
old_tup.t_ctid = new_tup.tid
self.non_hot_updates += 1
self.index_writes += self.n_indexes
return new_tup, False
# ----------------------------------------------------------------------------
# 2. Isolation Levels & Write Skew (A5B) vs. SSI (SQLSTATE 40001)
# ----------------------------------------------------------------------------
def simulate_isolation_anomalies() -> dict[str, Any]:
"""Reproduce Write Skew under Snapshot Isolation (REPEATABLE READ) vs SSI (SERIALIZABLE)."""
# Invariant: active inference replicas across {worker_A, worker_B} must remain >= 1
initial_state = {"worker_A": True, "worker_B": True}
# --- A. REPEATABLE READ (Snapshot Isolation) ---
# T1 & T2 take concurrent snapshots, read active_count=2 >= 2, modify disjoint keys!
si_state = dict(initial_state)
t1_snap = dict(si_state)
t2_snap = dict(si_state)
t1_writes: dict[str, bool] = {}
t2_writes: dict[str, bool] = {}
if sum(t1_snap.values()) >= 2:
t1_writes["worker_A"] = False
if sum(t2_snap.values()) >= 2:
t2_writes["worker_B"] = False
# First-Committer-Wins checks ONLY write-write (ww) overlap -> disjoint sets commit cleanly!
ww_overlap_si = set(t1_writes).intersection(t2_writes)
si_state.update(t1_writes)
si_state.update(t2_writes)
si_active_after = sum(si_state.values())
# --- B. SERIALIZABLE (SSI: SIREAD Predicate Locks & rw-antidependency detection) ---
ssi_state = dict(initial_state)
t1_reads = {"worker_A", "worker_B"}
t2_reads = {"worker_A", "worker_B"}
t1_write_keys = {"worker_A"}
t2_write_keys = {"worker_B"}
# T1 commits first -> updates worker_A
ssi_state["worker_A"] = False
# Check dangerous rw-antidependency cycle: T1 read T2's write AND T2 read T1's write
rw_t1_to_t2 = bool(t1_reads & t2_write_keys)
rw_t2_to_t1 = bool(t2_reads & t1_write_keys)
t2_aborted_40001 = False
t2_sqlstate = "00000"
try:
if rw_t1_to_t2 and rw_t2_to_t1:
raise SerializationError("could not serialize access due to read/write dependencies among transactions")
ssi_state["worker_B"] = False
except SerializationError as exc:
t2_aborted_40001 = True
t2_sqlstate = exc.sqlstate
# Client retries T2 after 40001 abort -> sees updated state {A: False, B: True} (active=1) -> refuses disable!
t2_retry_snap = dict(ssi_state)
t2_retry_denied_disable = sum(t2_retry_snap.values()) < 2
ssi_active_after = sum(ssi_state.values())
return {
"si_ww_overlap": len(ww_overlap_si),
"si_active_replicas_after": si_active_after,
"si_write_skew_breached": si_active_after == 0,
"ssi_rw_cycle_detected": rw_t1_to_t2 and rw_t2_to_t1,
"ssi_t2_aborted_40001": t2_aborted_40001,
"ssi_sqlstate": t2_sqlstate,
"ssi_retry_preserved_invariant": ssi_active_after >= 1 and t2_retry_denied_disable,
"ssi_active_replicas_after": ssi_active_after,
}
# ----------------------------------------------------------------------------
# 3. HOT vs. Non-HOT Updates & VACUUM / XID Wraparound Experiments
# ----------------------------------------------------------------------------
def simulate_hot_vs_non_hot_updates(
n_rows: int = 120, n_updates: int = 1000, n_indexes: int = 4
) -> dict[str, Any]:
"""Compare fillfactor=100 (indexed col changed) vs fillfactor=75 (HOT-friendly)."""
# Baseline: fillfactor=100 + updating an indexed column -> Non-HOT on every update
eng_bad = MVCCPageEngine(fillfactor=100, n_indexes=n_indexes)
x0 = eng_bad.allocate_xid()
rows_bad = [eng_bad.insert_tuple(x0, {"id": i, "status": "active", "counter": 0}, payload_bytes=104) for i in range(n_rows)]
eng_bad.commit_xid(x0)
for step in range(n_updates):
idx = step % n_rows
ux = eng_bad.allocate_xid()
new_t, _ = eng_bad.update_tuple(
rows_bad[idx],
ux,
{"id": idx, "status": f"s_{step % 3}", "counter": step + 1},
indexed_column_changed=True,
oldest_active_xmin=ux - 2,
)
eng_bad.commit_xid(ux)
rows_bad[idx] = new_t
# Optimized: fillfactor=75 + updating non-indexed counter -> opportunistic HOT pruning!
eng_hot = MVCCPageEngine(fillfactor=75, n_indexes=n_indexes)
x1 = eng_hot.allocate_xid()
rows_hot = [eng_hot.insert_tuple(x1, {"id": i, "status": "active", "counter": 0}, payload_bytes=104) for i in range(n_rows)]
eng_hot.commit_xid(x1)
for step in range(n_updates):
idx = step % n_rows
ux = eng_hot.allocate_xid()
new_t, _ = eng_hot.update_tuple(
rows_hot[idx],
ux,
{"id": idx, "status": "active", "counter": step + 1},
indexed_column_changed=False,
oldest_active_xmin=ux - 2,
)
eng_hot.commit_xid(ux)
rows_hot[idx] = new_t
bad_total_idx_writes = eng_bad.index_writes
hot_total_idx_writes = eng_hot.index_writes
bad_update_idx_writes = eng_bad.non_hot_updates * n_indexes
hot_update_idx_writes = eng_hot.non_hot_updates * n_indexes
hot_ratio_pct = round(100.0 * eng_hot.hot_updates / n_updates, 1)
bad_ratio_pct = round(100.0 * eng_bad.hot_updates / n_updates, 1)
return {
"n_rows": n_rows,
"n_updates": n_updates,
"n_indexes": n_indexes,
"non_hot_ratio_pct": bad_ratio_pct,
"hot_ratio_pct": hot_ratio_pct,
"non_hot_update_index_writes": bad_update_idx_writes,
"hot_update_index_writes": hot_update_idx_writes,
"non_hot_total_index_writes": bad_total_idx_writes,
"hot_total_index_writes": hot_total_idx_writes,
"index_write_reduction_pct": round(
100.0 * (1.0 - hot_update_idx_writes / max(1, bad_update_idx_writes)), 1
),
"non_hot_heap_pages": len(eng_bad.pages),
"hot_heap_pages": len(eng_hot.pages),
"hot_pruned_tuples": eng_hot.pruned_dead_tuples,
}
def simulate_vacuum_and_xid_wraparound(
n_live_tuples: int = 100_000_000,
n_dead_tuples: int = 180_000_000,
) -> dict[str, Any]:
"""Model autovacuum triggers, TidStore (PG 17) memory savings, and XID wraparound states."""
default_trigger = 50 + 0.20 * n_live_tuples
tuned_trigger = 5000 + 0.01 * n_live_tuples
pg18_max_threshold = 100_000_000
# Legacy PG <=16 flat 6-byte TID array (capped at 1 GB!) vs PG 17 TidStore ART (~20x smaller)
legacy_raw_mb = (n_dead_tuples * 6) / (1024 * 1024)
legacy_passes_needed = max(1, math.ceil(legacy_raw_mb / 1024.0))
tidstore_mb = round(legacy_raw_mb / 20.0, 2)
def _classify_xid_age(age: int) -> str:
if age >= 2_144_483_647:
return "XID_STOP_LIMIT_SHUTDOWN"
if age >= 2_107_483_647:
return "XID_WARN_LIMIT"
if age >= 1_600_000_000:
return "VACUUM_FAILSAFE_MODE"
if age >= 200_000_000:
return "ANTI_WRAPAROUND_FORCED"
return "HEALTHY"
# Idle-in-transaction pinning GlobalXmin blocks dead tuple reclamation
idle_session_xmin = 500_000_000
newest_dead_xmax = 500_050_000
blocked_by_idle_tx = newest_dead_xmax >= idle_session_xmin
return {
"n_live_tuples": n_live_tuples,
"n_dead_tuples": n_dead_tuples,
"default_autovacuum_trigger": int(default_trigger),
"tuned_autovacuum_trigger": int(tuned_trigger),
"pg18_autovacuum_max_threshold": pg18_max_threshold,
"legacy_tid_array_mb": round(legacy_raw_mb, 2),
"legacy_index_vacuum_passes": legacy_passes_needed,
"pg17_tidstore_mb": tidstore_mb,
"tidstore_memory_reduction_x": round(legacy_raw_mb / tidstore_mb, 1),
"blocked_by_idle_tx": blocked_by_idle_tx,
"xid_states": {
"150M": _classify_xid_age(150_000_000),
"250M": _classify_xid_age(250_000_000),
"1.65B": _classify_xid_age(1_650_000_000),
"2.145B": _classify_xid_age(2_145_000_000),
},
}
# ----------------------------------------------------------------------------
# 4. Lehman-Yao B-Tree Geometry & UUIDv4 vs. UUIDv7 FPI WAL Amplification
# ----------------------------------------------------------------------------
def compute_btree_geometry(
n_rows: int, key_bytes: int = 8, fillfactor_pct: int = 90
) -> dict[str, Any]:
"""Compute exact 8 KiB PostgreSQL B-Tree fanout B and tree height h = ceil(log_B(N))."""
usable_bytes = 8192 - 24 - 16 # 8152 B (PageHeaderData 24 B + BTPageOpaqueData 16 B)
aligned_key = ((key_bytes + 7) // 8) * 8
entry_bytes = 4 + 8 + aligned_key # ItemIdData(4) + IndexTupleData(8) + MAXALIGN_8(key)
max_entries_per_page = usable_bytes // entry_bytes
fanout = max(2, int(max_entries_per_page * (fillfactor_pct / 100.0)))
levels: list[int] = []
cur = max(1, math.ceil(n_rows / fanout))
levels.append(cur)
while cur > 1:
cur = math.ceil(cur / fanout)
levels.append(cur)
total_pages = sum(levels)
return {
"n_rows": n_rows,
"key_bytes": key_bytes,
"entry_bytes": entry_bytes,
"fanout_effective": fanout,
"tree_height": len(levels),
"leaf_pages": levels[0],
"upper_pages": total_pages - levels[0],
"total_size_mb": round((total_pages * 8192) / (1024 * 1024), 2),
}
def simulate_uuid_v4_vs_v7(
n_inserts: int = 6000,
page_capacity: int = 100,
shared_buffers_pages: int = 24,
checkpoint_interval: int = 1500,
seed: int = 2026,
) -> dict[str, Any]:
"""Simulate B-Tree leaf splits, shared_buffers LRU misses & 8 KiB FPI WAL amplification."""
rng = np.random.default_rng(seed)
def _run_pattern(random_keys: bool) -> dict[str, Any]:
# Maintain list of leaf page fill counts; split at 50/50 for random insertions!
leaf_counts: list[int] = [0]
lru: OrderedDict[int, int] = OrderedDict() # page_id -> last_checkpoint_epoch_fpi
misses = 0
fpi_count = 0
delta_wal_bytes = 0
for i in range(n_inserts):
epoch = i // checkpoint_interval
if random_keys:
target_page = int(rng.integers(0, len(leaf_counts)))
else:
target_page = len(leaf_counts) - 1
# Check shared_buffers LRU
if target_page not in lru:
misses += 1
if len(lru) >= shared_buffers_pages:
lru.popitem(last=False)
lru[target_page] = -1
else:
lru.move_to_end(target_page)
# First modification to page in checkpoint epoch emits 8192 B Full-Page Image (FPI)
if lru[target_page] != epoch:
fpi_count += 1
lru[target_page] = epoch
delta_wal_bytes += 64
# Insert + split logic
max_cap = page_capacity if random_keys else int(page_capacity * 0.90)
leaf_counts[target_page] += 1
if leaf_counts[target_page] > max_cap:
if random_keys:
half = leaf_counts[target_page] // 2
leaf_counts[target_page] = half
leaf_counts.append(max_cap + 1 - half)
else:
leaf_counts[target_page] = max_cap
leaf_counts.append(1)
avg_fill_pct = round(100.0 * (sum(leaf_counts) / (len(leaf_counts) * page_capacity)), 1)
wal_mb = round((fpi_count * 8192 + delta_wal_bytes) / (1024 * 1024), 2)
cache_hit_pct = round(100.0 * (1.0 - misses / n_inserts), 1)
return {
"leaf_pages": len(leaf_counts),
"avg_fill_pct": avg_fill_pct,
"buffer_misses": misses,
"cache_hit_pct": cache_hit_pct,
"fpi_count": fpi_count,
"total_wal_mb": wal_mb,
}
v4 = _run_pattern(random_keys=True)
v7 = _run_pattern(random_keys=False)
wal_reduction_pct = round(100.0 * (1.0 - v7["total_wal_mb"] / max(1e-6, v4["total_wal_mb"])), 1)
return {
"n_inserts": n_inserts,
"uuid_v4": v4,
"uuid_v7": v7,
"wal_reduction_pct": wal_reduction_pct,
"fpi_ratio_v4_to_v7": round(v4["fpi_count"] / max(1, v7["fpi_count"]), 1),
}
# ----------------------------------------------------------------------------
# 5. Real SQLite Query Plan, SARGability, OFFSET vs. Keyset & Window Frame Test
# ----------------------------------------------------------------------------
def benchmark_sqlite_indexes_and_pagination(
n_hot_tenant_rows: int = 18_000, n_noise_rows: int = 2_000, offset_depth: int = 15_000
) -> dict[str, Any]:
"""Run real sqlite3 EXPLAIN QUERY PLAN & latency benchmarks (no mocks)."""
conn = sqlite3.connect(":memory:")
conn.execute(
"""
CREATE TABLE events (
id INTEGER PRIMARY KEY,
tenant_id INTEGER NOT NULL,
status TEXT NOT NULL,
created_at TEXT NOT NULL,
amount_cents INTEGER NOT NULL,
payload TEXT NOT NULL
);
"""
)
rows: list[tuple[int, int, str, str, int, str]] = []
# Tenant 1 has n_hot_tenant_rows monotonic timestamps across 2025-2026
for i in range(1, n_hot_tenant_rows + 1):
year = 2025 if i <= (n_hot_tenant_rows // 2) else 2026
day_idx = i % 360
month = (day_idx // 30) + 1
day = (day_idx % 28) + 1
ts = f"{year}-{month:02d}-{day:02d}T{(i % 24):02d}:{(i % 60):02d}:{(i % 60):02d}Z"
status = "pending" if (i % 50 == 0) else "done"
rows.append((i, 1, status, ts, 100 + (i % 900), "x" * 96))
for j in range(1, n_noise_rows + 1):
eid = n_hot_tenant_rows + j
rows.append((eid, 2 + (j % 20), "done", "2026-06-15T12:00:00Z", 500, "y" * 96))
conn.executemany("INSERT INTO events VALUES (?, ?, ?, ?, ?, ?)", rows)
conn.execute(
"CREATE INDEX ix_events_cov ON events (tenant_id, created_at DESC, id DESC, status, amount_cents);"
)
conn.execute("ANALYZE;")
# 1. Non-SARGable vs SARGable Covering Index-Only Scan
q_non_sarg = (
"SELECT id, status, amount_cents FROM events "
"WHERE tenant_id = 1 AND substr(created_at, 1, 7) = '2026-06' "
"ORDER BY created_at DESC, id DESC LIMIT 20"
)
q_sarg = (
"SELECT id, status, amount_cents FROM events "
"WHERE tenant_id = 1 AND created_at >= '2026-06-01T00:00:00Z' "
"AND created_at < '2026-07-01T00:00:00Z' "
"ORDER BY created_at DESC, id DESC LIMIT 20"
)
plan_non_sarg = " | ".join(str(r[3]) for r in conn.execute(f"EXPLAIN QUERY PLAN {q_non_sarg}").fetchall())
plan_sarg = " | ".join(str(r[3]) for r in conn.execute(f"EXPLAIN QUERY PLAN {q_sarg}").fetchall())
repeats = 12
t0 = time.perf_counter()
for _ in range(repeats):
conn.execute(q_non_sarg).fetchall()
non_sarg_ms = ((time.perf_counter() - t0) * 1000.0) / repeats
t0 = time.perf_counter()
for _ in range(repeats):
conn.execute(q_sarg).fetchall()
sarg_ms = ((time.perf_counter() - t0) * 1000.0) / repeats
# 2. OFFSET vs Keyset Seek Pagination at offset_depth
q_offset = (
f"SELECT id, created_at, amount_cents FROM events "
f"WHERE tenant_id = 1 ORDER BY created_at DESC, id DESC LIMIT 20 OFFSET {offset_depth}"
)
# Grab exact cursor just BEFORE page at offset_depth so Keyset returns IDENTICAL 20 rows!
cursor_row = conn.execute(
f"SELECT created_at, id FROM events WHERE tenant_id = 1 "
f"ORDER BY created_at DESC, id DESC LIMIT 1 OFFSET {offset_depth - 1}"
).fetchone()
cursor_ts, cursor_id = str(cursor_row[0]), int(cursor_row[1])
q_keyset = (
"SELECT id, created_at, amount_cents FROM events "
"WHERE tenant_id = 1 AND (created_at, id) < (?, ?) "
"ORDER BY created_at DESC, id DESC LIMIT 20"
)
plan_keyset = " | ".join(
str(r[3]) for r in conn.execute(f"EXPLAIN QUERY PLAN {q_keyset}", (cursor_ts, cursor_id)).fetchall()
)
offset_rows = conn.execute(q_offset).fetchall()
keyset_rows = conn.execute(q_keyset, (cursor_ts, cursor_id)).fetchall()
parity_ok = offset_rows == keyset_rows and len(keyset_rows) == 20
t0 = time.perf_counter()
for _ in range(repeats):
conn.execute(q_offset).fetchall()
offset_ms = ((time.perf_counter() - t0) * 1000.0) / repeats
t0 = time.perf_counter()
for _ in range(repeats):
conn.execute(q_keyset, (cursor_ts, cursor_id)).fetchall()
keyset_ms = ((time.perf_counter() - t0) * 1000.0) / repeats
# 3. Verify Window Function Frame Trap: default RANGE peers vs explicit ROWS
conn.execute("CREATE TABLE t_win (id INT, ts INT, amt INT);")
conn.executemany(
"INSERT INTO t_win VALUES (?, ?, ?)",
[(1, 10, 100), (2, 10, 200), (3, 20, 50)],
)
win_res = conn.execute(
"""
SELECT id,
SUM(amt) OVER (ORDER BY ts) AS default_range_sum,
SUM(amt) OVER (ORDER BY ts, id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS rows_sum
FROM t_win ORDER BY id;
"""
).fetchall()
conn.close()
return {
"total_rows": n_hot_tenant_rows + n_noise_rows,
"offset_depth": offset_depth,
"plan_non_sargable": plan_non_sarg,
"plan_sargable_covering": plan_sarg,
"plan_keyset": plan_keyset,
"non_sargable_ms": round(non_sarg_ms, 3),
"sargable_covering_ms": round(sarg_ms, 3),
"sargable_speedup": round(non_sarg_ms / max(1e-6, sarg_ms), 1),
"offset_ms": round(offset_ms, 3),
"keyset_ms": round(keyset_ms, 3),
"keyset_speedup": round(offset_ms / max(1e-6, keyset_ms), 1),
"offset_rows_scanned": offset_depth + 20,
"keyset_rows_scanned": 20,
"pagination_parity_exact": parity_ok,
"window_range_first_row_sum": int(win_res[0][1]), # 300 (includes tied ts=10 peer!)
"window_rows_first_row_sum": int(win_res[0][2]), # 100 (strict per-row running sum)
}
# ----------------------------------------------------------------------------
# 6. PgBouncer Pool Collapse & pgvector Filtered Recall Models
# ----------------------------------------------------------------------------
def simulate_pgbouncer_pool_collapse(
app_clients: int = 500,
pg_max_connections: int = 200,
pgbouncer_pool_size: int = 32,
db_cores: int = 8,
) -> dict[str, Any]:
"""Quantify direct max_connections saturation vs PgBouncer transaction multiplexing."""
mem_per_backend_mb = 8.5 # RSS/PSS with warmed catalog + work_mem baseline
direct_accepted = min(app_clients, pg_max_connections)
direct_rejected = max(0, app_clients - pg_max_connections)
direct_ram_mb = round(direct_accepted * mem_per_backend_mb, 1)
# USL-inspired active backend contention penalty beyond 2 * db_cores active processes
optimal_active = 2 * db_cores
overload = max(0, direct_accepted - optimal_active)
direct_ctx_penalty = 1.0 + 0.018 * overload + 0.00012 * (overload**2)
direct_p99_ms = round(4.5 * direct_ctx_penalty, 1)
direct_tps = round((optimal_active * 850) / max(1.0, direct_ctx_penalty * 0.45))
# PgBouncer transaction mode: 500 app clients share 32 physical DB backends!
pb_ram_mb = round(pgbouncer_pool_size * mem_per_backend_mb + 24.0, 1)
pb_overload = max(0, pgbouncer_pool_size - optimal_active)
pb_ctx_penalty = 1.0 + 0.018 * pb_overload + 0.00012 * (pb_overload**2)
pb_p99_ms = round(4.5 * pb_ctx_penalty + 0.4, 1)
pb_tps = round((optimal_active * 850) / max(1.0, pb_ctx_penalty * 0.35))
return {
"app_clients": app_clients,
"pg_max_connections": pg_max_connections,
"pgbouncer_pool_size": pgbouncer_pool_size,
"direct_accepted_conns": direct_accepted,
"direct_rejected_conns": direct_rejected,
"direct_backend_ram_mb": direct_ram_mb,
"direct_p99_ms": direct_p99_ms,
"direct_effective_tps": direct_tps,
"pgbouncer_rejected_conns": 0,
"pgbouncer_backend_ram_mb": pb_ram_mb,
"pgbouncer_p99_ms": pb_p99_ms,
"pgbouncer_effective_tps": pb_tps,
"backend_reduction_pct": round(100.0 * (1.0 - pgbouncer_pool_size / app_clients), 1),
"ram_saved_mb": round(direct_ram_mb - pb_ram_mb, 1),
}
def simulate_pgvector_filtered_recall(
n_vectors: int = 20_000,
tenant_selectivity: float = 0.02,
ef_search: int = 40,
top_k: int = 10,
max_scan_tuples: int = 20_000,
seed: int = 42,
) -> dict[str, Any]:
"""Simulate pgvector HNSW post-filtering recall collapse vs hnsw.iterative_scan recovery."""
rng = np.random.default_rng(seed)
# Generate normalized 16-d unit vectors ordered by cosine similarity to a query vector
raw = rng.normal(size=(n_vectors, 16))
norms = np.linalg.norm(raw, axis=1, keepdims=True)
vecs = raw / np.maximum(norms, 1e-12)
query = vecs[0]
sims = vecs @ query
order = np.argsort(-sims)
tenant_mask = rng.random(n_vectors) < tenant_selectivity
# Ground truth top_k matching tenant
gt_indices = [int(idx) for idx in order if tenant_mask[idx]][:top_k]
# 1. Naive Post-Filtering (HNSW halts after ef_search=40 global candidates)
post_candidates = order[:ef_search]
post_returned = [int(idx) for idx in post_candidates if tenant_mask[idx]][:top_k]
post_recall = round(len(set(post_returned) & set(gt_indices)) / max(1, len(gt_indices)), 3)
# 2. pgvector 0.8+ hnsw.iterative_scan='relaxed_order' (resumes scan until top_k or max_scan_tuples)
iter_returned: list[int] = []
scanned = 0
for idx in order:
scanned += 1
if tenant_mask[idx]:
iter_returned.append(int(idx))
if len(iter_returned) >= top_k:
break
if scanned >= max_scan_tuples:
break
iter_recall = round(len(set(iter_returned) & set(gt_indices)) / max(1, len(gt_indices)), 3)
return {
"n_vectors": n_vectors,
"tenant_selectivity": tenant_selectivity,
"ef_search": ef_search,
"top_k": top_k,
"post_filter_returned_rows": len(post_returned),
"post_filter_recall": post_recall,
"iterative_scan_returned_rows": len(iter_returned),
"iterative_scan_tuples_scanned": scanned,
"iterative_scan_recall": iter_recall,
}
def main(argv: list[str] | None = None) -> int:
import argparse
import json
import threading
from db_internals_lab.repository_and_uow import (
check_db_readiness,
install_signal_handlers,
restore_signal_handlers,
)
parser = argparse.ArgumentParser(
description="PostgreSQL MVCC/Query Engine & DB Readiness Diagnostics"
)
parser.add_argument(
"--healthcheck",
action="store_true",
help="Run lightweight SQLite readiness probe and exit.",
)
parser.add_argument(
"--db-path",
default=":memory:",
help="Target SQLite path for --healthcheck.",
)
args = parser.parse_args(argv)
stop_event = threading.Event()
previous_handlers = install_signal_handlers(stop_event)
try:
if args.healthcheck:
probe = check_db_readiness(args.db_path, stop_event=stop_event)
print(json.dumps(probe, indent=2))
return 0 if probe["ready"] else 1
summary = {
"isolation": simulate_isolation_anomalies(),
"hot_vs_non_hot": simulate_hot_vs_non_hot_updates(),
"sqlite_query_bench": benchmark_sqlite_indexes_and_pagination(),
"readiness": check_db_readiness(args.db_path, stop_event=stop_event),
}
print(json.dumps(summary, indent=2))
return 0
finally:
restore_signal_handlers(previous_handlers)
if __name__ == "__main__":
raise SystemExit(main())
"""CLI workbench runner exporting deterministic empirical benchmarks for FSDS-SOTA-2026 Track 2 Lab 03."""
from __future__ import annotations
import argparse
import json
import sys
import tempfile
from pathlib import Path
LAB_ROOT = Path(__file__).resolve().parents[1]
SRC_DIR = LAB_ROOT / "src"
if str(SRC_DIR) not in sys.path:
sys.path.insert(0, str(SRC_DIR))
from db_internals_lab.mvcc_and_query_engine import ( # noqa: E402
benchmark_sqlite_indexes_and_pagination,
compute_btree_geometry,
simulate_hot_vs_non_hot_updates,
simulate_isolation_anomalies,
simulate_pgbouncer_pool_collapse,
simulate_pgvector_filtered_recall,
simulate_uuid_v4_vs_v7,
simulate_vacuum_and_xid_wraparound,
)
from db_internals_lab.repository_and_uow import ( # noqa: E402
OrderCreateSpec,
OrderItemSpec,
PlaceOrderService,
SqliteUnitOfWork,
benchmark_n_plus_1_vs_eager_loading,
demonstrate_tcl_savepoint_and_ddl_truncate,
)
def run_all_benchmarks(quick: bool = False) -> dict[str, object]:
n_rows_sqlite = 12_000 if quick else 20_000
offset_depth = 9_000 if quick else 15_000
n_hot_rows = 10_000 if quick else 18_000
# 1. OOP Repository & Unit of Work (fail-closed rollback + Transactional Outbox) + TCL Savepoint
with tempfile.TemporaryDirectory() as tmp_dir:
db_file = Path(tmp_dir) / "uow_demo.sqlite3"
svc = PlaceOrderService(lambda: SqliteUnitOfWork(db_file))
# Fail-closed test: crash mid-tx -> 0 orders, 0 outbox rows persisted
rollback_caught = False
try:
svc.place_order(
OrderCreateSpec(
order_id=101,
tenant_id=42,
status="pending",
created_at="2026-11-21T10:00:00Z",
items=(OrderItemSpec(sku="GPU-H100", quantity=1, unit_price_cents=250000),),
),
fail_after_order_insert=True,
)
except RuntimeError:
rollback_caught = True
# Atomic commit: 1 order + 1 outbox event
committed_order = svc.place_order(
OrderCreateSpec(
order_id=102,
tenant_id=42,
status="paid",
created_at="2026-11-21T10:05:00Z",
items=(OrderItemSpec(sku="NVME-4TB", quantity=2, unit_price_cents=45000),),
),
fail_after_order_insert=False,
)
with SqliteUnitOfWork(db_file) as check_uow:
aborted_order = check_uow.orders.get_order(101)
if check_uow.orders.get_order(102) is None:
raise RuntimeError("Expected committed order 102 to persist in SQLite UoW")
outbox_events = check_uow.outbox.list_events()
tcl_res = demonstrate_tcl_savepoint_and_ddl_truncate(Path(tmp_dir) / "tcl_demo.sqlite3")
uow_summary = {
"rollback_caught": rollback_caught,
"aborted_order_is_none": aborted_order is None,
"committed_order_total_cents": committed_order.total_cents,
"persisted_outbox_events": len(outbox_events),
"tcl_savepoint_qty_after_commit": tcl_res["qty_after_commit"],
}
# 2. PostgreSQL Internals: Isolation/Write Skew, HOT vs Non-HOT, VACUUM/TidStore/XID
iso = simulate_isolation_anomalies()
hot = simulate_hot_vs_non_hot_updates(n_rows=120, n_updates=1000, n_indexes=4)
vac = simulate_vacuum_and_xid_wraparound()
# 3. B-Tree Geometry, UUIDv4 vs UUIDv7, Real SQLite Index & Pagination Benchmarks
btree_bigint_10m = compute_btree_geometry(n_rows=10_000_000, key_bytes=8, fillfactor_pct=90)
btree_comp_10m = compute_btree_geometry(n_rows=10_000_000, key_bytes=32, fillfactor_pct=90)
uuid_bench = simulate_uuid_v4_vs_v7(n_inserts=6000)
sqlite_bench = benchmark_sqlite_indexes_and_pagination(
n_hot_tenant_rows=n_hot_rows,
n_noise_rows=n_rows_sqlite - n_hot_rows if n_rows_sqlite > n_hot_rows else 2_000,
offset_depth=offset_depth,
)
# 4. SQLAlchemy 2.0 Eager Loading vs N+1, PgBouncer Pooling & pgvector Filtered Recall
orm_bench = benchmark_n_plus_1_vs_eager_loading(n_orders=100, items_per_order=5, repeats=10)
pool_bench = simulate_pgbouncer_pool_collapse(app_clients=500, pg_max_connections=200, pgbouncer_pool_size=32)
vec_bench = simulate_pgvector_filtered_recall(n_vectors=20_000, tenant_selectivity=0.02, ef_search=40, top_k=10)
kpis = [
{
"id": "kpi_hot_vs_non_hot_updates",
"label": "HOT Updates (fillfactor=75 vs 100)",
"value": f"{hot['hot_ratio_pct']}% vs {hot['non_hot_ratio_pct']}%",
"unit": f"-{hot['index_write_reduction_pct']}% idx writes",
"status": "ok",
"detail": (
f"1,000 updates across 4 indexes: Non-HOT={hot['non_hot_update_index_writes']} vs "
f"HOT={hot['hot_update_index_writes']} index writes (pruned={hot['hot_pruned_tuples']})."
),
},
{
"id": "kpi_isolation_write_skew_ssi",
"label": "Write Skew: Repeatable Read vs SSI",
"value": f"{iso['si_active_replicas_after']} vs {iso['ssi_active_replicas_after']} active",
"unit": f"SQLSTATE {iso['ssi_sqlstate']}",
"status": "ok",
"detail": (
"SI lets disjoint updates drop active_replicas 2->0; SSI detects rw-antidependency cycle, "
"aborts T2 (40001), and retry preserves invariant (>=1)."
),
},
{
"id": "kpi_sargable_and_keyset_sqlite",
"label": f"SQLite Query & Keyset ({sqlite_bench['total_rows']//1000}k rows)",
"value": f"{sqlite_bench['offset_ms']} -> {sqlite_bench['keyset_ms']} ms",
"unit": f"{sqlite_bench['keyset_speedup']}x seek",
"status": "ok",
"detail": (
f"SARGable Covering Index ({sqlite_bench['sargable_covering_ms']} vs "
f"{sqlite_bench['non_sargable_ms']} ms, {sqlite_bench['sargable_speedup']}x); "
f"Keyset scans 20 rows vs OFFSET {sqlite_bench['offset_rows_scanned']}."
),
},
{
"id": "kpi_uuidv7_vs_uuidv4_wal",
"label": "UUIDv7 vs UUIDv4 B-Tree WAL FPI",
"value": f"{uuid_bench['uuid_v4']['total_wal_mb']} -> {uuid_bench['uuid_v7']['total_wal_mb']} MiB",
"unit": f"-{uuid_bench['wal_reduction_pct']}% WAL",
"status": "ok",
"detail": (
f"Leaf fill {uuid_bench['uuid_v4']['avg_fill_pct']}% -> {uuid_bench['uuid_v7']['avg_fill_pct']}%; "
f"cache hit {uuid_bench['uuid_v4']['cache_hit_pct']}% -> {uuid_bench['uuid_v7']['cache_hit_pct']}% "
f"(FPI ratio {uuid_bench['fpi_ratio_v4_to_v7']}x)."
),
},
{
"id": "kpi_n_plus_1_vs_selectinload",
"label": "ORM N+1 vs selectinload (100 Orders)",
"value": f"{orm_bench['n_plus_1_queries']} -> {orm_bench['selectinload_queries']} SQL",
"unit": f"-{orm_bench['query_reduction_pct']}%",
"status": "ok",
"detail": (
f"1.5ms VPC RTT: {orm_bench['n_plus_1_vpc_rtt_ms']} ms -> "
f"{orm_bench['selectinload_vpc_rtt_ms']} ms (wire rows={orm_bench['selectinload_wire_rows']} "
f"vs joinedload {orm_bench['joinedload_wire_rows']})."
),
},
{
"id": "kpi_pgbouncer_and_pgvector_rag",
"label": "PgBouncer Pool & pgvector Recall@10",
"value": f"{pool_bench['app_clients']} -> {pool_bench['pgbouncer_pool_size']} conns",
"unit": f"Recall {int(vec_bench['post_filter_recall']*100)}%->{int(vec_bench['iterative_scan_recall']*100)}%",
"status": "ok",
"detail": (
f"PgBouncer saves {pool_bench['ram_saved_mb']} MiB (0 rejections vs "
f"{pool_bench['direct_rejected_conns']}); hnsw.iterative_scan restores 10/10 rows at s=2%."
),
},
]
bars = [
{
"id": "bar_query_execution_latency_ms",
"title": f"Real SQLite Query Plan & Pagination Latency at {sqlite_bench['total_rows']:,} Rows (ms)",
"metric_label": "Milliseconds",
"items": [
{
"label": "non_sargable_substr_seq_scan",
"value": sqlite_bench["non_sargable_ms"],
"display": f"{sqlite_bench['non_sargable_ms']} ms (SCAN)",
"css_class": "is-slow",
},
{
"label": f"offset_{sqlite_bench['offset_depth']}_linear_discard",
"value": sqlite_bench["offset_ms"],
"display": f"{sqlite_bench['offset_ms']} ms ({sqlite_bench['offset_rows_scanned']} rows)",
"css_class": "is-slow",
},
{
"label": "sargable_covering_index_only",
"value": sqlite_bench["sargable_covering_ms"],
"display": f"{sqlite_bench['sargable_covering_ms']} ms ({sqlite_bench['sargable_speedup']}x)",
"css_class": "is-fast",
},
{
"label": "keyset_row_value_seek",
"value": sqlite_bench["keyset_ms"],
"display": f"{sqlite_bench['keyset_ms']} ms ({sqlite_bench['keyset_speedup']}x, 20 rows)",
"css_class": "is-fast",
},
],
},
{
"id": "bar_hot_vs_non_hot_index_writes",
"title": "PostgreSQL 8 KiB Page Workload (120 Inserts + 1,000 Updates x 4 Indexes): Total Index Writes",
"metric_label": "Index Writes",
"items": [
{
"label": "non_hot_ff100_indexed_col",
"value": float(hot["non_hot_total_index_writes"]),
"display": f"{hot['non_hot_total_index_writes']} writes ({hot['non_hot_ratio_pct']}% HOT)",
"css_class": "is-slow",
},
{
"label": "hot_ff75_non_indexed_col",
"value": float(hot["hot_total_index_writes"]),
"display": f"{hot['hot_total_index_writes']} writes ({hot['hot_ratio_pct']}% HOT, 0 upd idx)",
"css_class": "is-fast",
},
],
},
{
"id": "bar_orm_loading_queries_and_rtt_ms",
"title": "SQLAlchemy Loading Modes (100 Orders x 5 Items, 1.5ms VPC RTT): Total Latency (ms)",
"metric_label": "Latency (ms)",
"items": [
{
"label": "lazy_select_n_plus_1_storm",
"value": orm_bench["n_plus_1_vpc_rtt_ms"],
"display": f"{orm_bench['n_plus_1_vpc_rtt_ms']} ms ({orm_bench['n_plus_1_queries']} SQL)",
"css_class": "is-slow",
},
{
"label": "selectinload_batched_in",
"value": orm_bench["selectinload_vpc_rtt_ms"],
"display": f"{orm_bench['selectinload_vpc_rtt_ms']} ms ({orm_bench['selectinload_queries']} SQL, 600 rows)",
"css_class": "is-fast",
},
{
"label": "joinedload_left_outer_join",
"value": orm_bench["joinedload_vpc_rtt_ms"],
"display": f"{orm_bench['joinedload_vpc_rtt_ms']} ms ({orm_bench['joinedload_queries']} SQL, 500 wire rows)",
"css_class": "is-mid",
},
],
},
{
"id": "bar_uuidv4_vs_uuidv7_wal_mb",
"title": "B-Tree 6,000-Insert Checkpoint WAL Full-Page Image (FPI) Amplification (MiB)",
"metric_label": "WAL (MiB)",
"items": [
{
"label": "uuid_v4_random_splits",
"value": uuid_bench["uuid_v4"]["total_wal_mb"],
"display": f"{uuid_bench['uuid_v4']['total_wal_mb']} MiB (fill={uuid_bench['uuid_v4']['avg_fill_pct']}%)",
"css_class": "is-slow",
},
{
"label": "uuid_v7_monotonic_append",
"value": uuid_bench["uuid_v7"]["total_wal_mb"],
"display": f"{uuid_bench['uuid_v7']['total_wal_mb']} MiB (fill={uuid_bench['uuid_v7']['avg_fill_pct']}%)",
"css_class": "is-fast",
},
],
},
]
tables = [
{
"id": "table_mvcc_isolation_and_vacuum",
"title": "PostgreSQL MVCC, Write Skew (SI vs SSI), HOT Pruning & PG 17 TidStore Vacuum",
"columns": ["subsystem_experiment", "baseline_or_risk", "optimized_or_guard", "measured_invariant", "status"],
"rows": [
[
"write_skew_isolation",
f"REPEATABLE READ (SI): {iso['si_active_replicas_after']} active",
f"SERIALIZABLE (SSI): {iso['ssi_active_replicas_after']} active",
f"SQLSTATE {iso['ssi_sqlstate']} retry preserved invariant",
"SSI_VERIFIED",
],
[
"hot_updates_4_indexes",
f"ff=100 idx_mut: {hot['non_hot_update_index_writes']} writes",
f"ff=75 non-idx: {hot['hot_update_index_writes']} writes",
f"HOT={hot['hot_ratio_pct']}%, pruned={hot['hot_pruned_tuples']}",
"HOT_OPTIMAL",
],
[
"pg17_tidstore_180m_dead",
f"Legacy array: {vac['legacy_tid_array_mb']} MB ({vac['legacy_index_vacuum_passes']} passes)",
f"PG 17 TidStore: {vac['pg17_tidstore_mb']} MB",
f"{vac['tidstore_memory_reduction_x']}x less RAM (0 multi-pass)",
"ART_VERIFIED",
],
[
"xid_wraparound_horizon",
f"idle_tx pins xmin: blocked={vac['blocked_by_idle_tx']}",
"autovac_freeze=200M / failsafe=1.6B",
f"2.145B -> {vac['xid_states']['2.145B']}",
"GUARD_ACTIVE",
],
],
},
{
"id": "table_btree_uuid_and_sqlite_plans",
"title": "B-Tree Geometry (8 KiB), UUIDv4 vs UUIDv7 & Real SQLite EXPLAIN QUERY PLAN",
"columns": ["benchmark_case", "baseline_metric", "optimized_metric", "query_plan_or_ratio", "verdict"],
"rows": [
[
"btree_10m_bigint_8b",
f"fanout={btree_bigint_10m['fanout_effective']}",
f"height h={btree_bigint_10m['tree_height']}",
f"{btree_bigint_10m['total_size_mb']} MB ({btree_bigint_10m['upper_pages']} upper pgs)",
"3_HOP_SEEK",
],
[
"btree_10m_composite_32b",
f"fanout={btree_comp_10m['fanout_effective']}",
f"height h={btree_comp_10m['tree_height']}",
f"{btree_comp_10m['total_size_mb']} MB ({btree_comp_10m['upper_pages']} upper pgs)",
"4_HOP_SEEK",
],
[
"uuid_v4_vs_v7_6k_inserts",
f"v4={uuid_bench['uuid_v4']['total_wal_mb']} MiB (hit {uuid_bench['uuid_v4']['cache_hit_pct']}%)",
f"v7={uuid_bench['uuid_v7']['total_wal_mb']} MiB (hit {uuid_bench['uuid_v7']['cache_hit_pct']}%)",
f"-{uuid_bench['wal_reduction_pct']}% WAL FPI",
"UUIDV7_WIN",
],
[
"sqlite_sargable_covering",
f"substr()={sqlite_bench['non_sargable_ms']} ms",
f"range={sqlite_bench['sargable_covering_ms']} ms",
sqlite_bench["plan_sargable_covering"][:54],
f"{sqlite_bench['sargable_speedup']}x_FASTER",
],
[
"sqlite_offset_vs_keyset",
f"OFFSET {sqlite_bench['offset_depth']}={sqlite_bench['offset_ms']} ms",
f"Keyset={sqlite_bench['keyset_ms']} ms",
f"parity={sqlite_bench['pagination_parity_exact']} ({sqlite_bench['keyset_speedup']}x)",
"O_LOG_N_SEEK",
],
],
},
{
"id": "table_orm_loading_and_uow_safety",
"title": "SOLID UoW Fail-Closed Atomicity, TCL Savepoints & SQLAlchemy Eager Loading",
"columns": ["pattern_or_mode", "sql_queries", "latency_1_5ms_rtt", "invariant_or_wire_rows", "status"],
"rows": [
[
"uow_crash_rollback_outbox",
"BEGIN IMMEDIATE -> ROLLBACK",
"0 ms leaked",
f"aborted_is_none={uow_summary['aborted_order_is_none']}, outbox={uow_summary['persisted_outbox_events']}",
"ACID_ATOMIC",
],
[
"tcl_savepoint_and_upsert",
"SAVEPOINT -> ROLLBACK TO -> COMMIT",
"< 1 ms",
f"final_sku_qty={uow_summary['tcl_savepoint_qty_after_commit']}",
"TCL_VERIFIED",
],
[
"orm_lazy_n_plus_1_storm",
f"{orm_bench['n_plus_1_queries']} queries",
f"{orm_bench['n_plus_1_vpc_rtt_ms']} ms",
"100 extra child round-trips",
"ANTI_PATTERN",
],
[
"orm_selectinload_batched",
f"{orm_bench['selectinload_queries']} queries",
f"{orm_bench['selectinload_vpc_rtt_ms']} ms",
f"{orm_bench['selectinload_wire_rows']} rows (0 parent dup)",
"SOTA_DEFAULT",
],
[
"orm_joinedload_left_join",
f"{orm_bench['joinedload_queries']} query",
f"{orm_bench['joinedload_vpc_rtt_ms']} ms",
f"{orm_bench['joinedload_wire_rows']} wire rows (parent x5)",
"BEST_FOR_M_TO_1",
],
],
},
{
"id": "table_pgbouncer_and_pgvector_rag",
"title": "PgBouncer Transaction Pooling (500 Clients) & pgvector HNSW Filtered RAG",
"columns": ["subsystem", "naive_baseline", "sota_configuration", "delta_or_sla", "status"],
"rows": [
[
"pgbouncer_500_clients",
f"Direct max=200: {pool_bench['direct_rejected_conns']} rejected, {pool_bench['direct_backend_ram_mb']} MB",
f"Tx pool=32: {pool_bench['pgbouncer_rejected_conns']} rejected, {pool_bench['pgbouncer_backend_ram_mb']} MB",
f"-{pool_bench['backend_reduction_pct']}% backends, p99 {pool_bench['direct_p99_ms']}->{pool_bench['pgbouncer_p99_ms']} ms",
"POOL_SCALED",
],
[
"pgvector_filtered_s_2pct",
f"Post-filter ef=40: {vec_bench['post_filter_returned_rows']}/10 rows",
f"iterative_scan: {vec_bench['iterative_scan_returned_rows']}/10 rows",
f"Recall@10 {vec_bench['post_filter_recall']} -> {vec_bench['iterative_scan_recall']} ({vec_bench['iterative_scan_tuples_scanned']} scanned)",
"RECALL_SAVED",
],
[
"window_rows_vs_range_trap",
f"Default RANGE peer sum={sqlite_bench['window_range_first_row_sum']}",
f"Explicit ROWS sum={sqlite_bench['window_rows_first_row_sum']}",
"Prevents silent peer-grouping bug",
"SQL_VERIFIED",
],
],
},
]
return {
"config": {"quick": quick, "lab_root": "lab-03-postgres-sqlalchemy-optimization"},
"uow_summary": uow_summary,
"isolation": iso,
"hot_vs_non_hot": hot,
"vacuum_xid": vac,
"btree_bigint_10m": btree_bigint_10m,
"btree_composite_10m": btree_comp_10m,
"uuid_v4_vs_v7": uuid_bench,
"sqlite_query_bench": sqlite_bench,
"orm_loading_bench": orm_bench,
"pgbouncer_bench": pool_bench,
"pgvector_filtered_bench": vec_bench,
"workbench_panels": {
"kpis": kpis,
"bars": bars,
"tables": tables,
},
}
def main() -> int:
parser = argparse.ArgumentParser(description="Run FSDS-SOTA-2026 Track 2 Lab 03 Workbench.")
parser.add_argument("--quick", action="store_true", help="Run faster scaled benchmark preset.")
parser.add_argument(
"--output",
type=str,
default="artifacts/t2_ch03_workbench_results.json",
help="Output JSON path relative to lab root or absolute.",
)
args = parser.parse_args()
payload = run_all_benchmarks(quick=args.quick)
out_path = Path(args.output)
if not out_path.is_absolute():
out_path = LAB_ROOT / out_path
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(payload, indent=2), encoding="utf-8", newline="\n")
iso = payload["isolation"]
hot = payload["hot_vs_non_hot"]
sq = payload["sqlite_query_bench"]
orm = payload["orm_loading_bench"]
uu = payload["uuid_v4_vs_v7"]
pb = payload["pgbouncer_bench"]
pv = payload["pgvector_filtered_bench"]
print("[1] OOP Repository/UoW & Isolation:")
print(f" UoW Fail-Closed Rollback OK={payload['uow_summary']['aborted_order_is_none']}, Outbox={payload['uow_summary']['persisted_outbox_events']}")
print(f" Write Skew SI active={iso['si_active_replicas_after']} vs SSI active={iso['ssi_active_replicas_after']} (SQLSTATE={iso['ssi_sqlstate']})")
print("[2] PostgreSQL Storage, HOT & UUIDv7:")
print(f" HOT ratio ff=75: {hot['hot_ratio_pct']}% vs ff=100: {hot['non_hot_ratio_pct']}% (-{hot['index_write_reduction_pct']}% idx writes)")
print(f" UUIDv4 -> UUIDv7 WAL: {uu['uuid_v4']['total_wal_mb']} -> {uu['uuid_v7']['total_wal_mb']} MiB (-{uu['wal_reduction_pct']}%)")
print("[3] Real SQLite Query Plans, Keyset & Eager Loading:")
print(f" SARGable Covering: {sq['non_sargable_ms']} -> {sq['sargable_covering_ms']} ms ({sq['sargable_speedup']}x)")
print(f" Keyset vs OFFSET {sq['offset_depth']}: {sq['offset_ms']} -> {sq['keyset_ms']} ms ({sq['keyset_speedup']}x)")
print(f" ORM N+1 -> selectinload: {orm['n_plus_1_queries']} -> {orm['selectinload_queries']} queries ({orm['n_plus_1_vpc_rtt_ms']} -> {orm['selectinload_vpc_rtt_ms']} ms)")
print("[4] PgBouncer Pooling & pgvector Filtered RAG:")
print(f" PgBouncer 500 -> 32 conns: RAM {pb['direct_backend_ram_mb']} -> {pb['pgbouncer_backend_ram_mb']} MiB, p99 {pb['direct_p99_ms']} -> {pb['pgbouncer_p99_ms']} ms")
print(f" pgvector iterative_scan Recall@10: {pv['post_filter_recall']} -> {pv['iterative_scan_recall']}")
print(f"Saved workbench JSON -> {out_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""16-test verification suite for FSDS-SOTA-2026 Track 2 Lab 03 (db_internals_lab)."""
from __future__ import annotations
import ast
import importlib.util
import json
import os
import signal
import sqlite3
import subprocess
import sys
import threading
from pathlib import Path
import pytest
from pydantic import ValidationError
from sqlalchemy import ForeignKey, Integer, String, create_engine, event, select
from sqlalchemy.exc import InvalidRequestError
from sqlalchemy.orm import (
DeclarativeBase,
Mapped,
Session,
joinedload,
mapped_column,
relationship,
selectinload,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
SRC_DIR = LAB_ROOT / "src"
if str(SRC_DIR) not in sys.path:
sys.path.insert(0, str(SRC_DIR))
from db_internals_lab.mvcc_and_query_engine import ( # noqa: E402
HEAP_XMIN_FROZEN,
MVCCPageEngine,
Snapshot,
benchmark_sqlite_indexes_and_pagination,
compute_btree_geometry,
simulate_hot_vs_non_hot_updates,
simulate_isolation_anomalies,
simulate_pgbouncer_pool_collapse,
simulate_pgvector_filtered_recall,
simulate_uuid_v4_vs_v7,
simulate_vacuum_and_xid_wraparound,
)
from db_internals_lab.repository_and_uow import ( # noqa: E402
DatabaseConfigSpec,
InMemoryUnitOfWork,
OrderCreateSpec,
OrderItemSpec,
OrderRepositoryProtocol,
PaginationQuerySpec,
PlaceOrderService,
PoolRoutingSpec,
SqliteOrderRepository,
SqliteUnitOfWork,
UnitOfWorkProtocol,
benchmark_n_plus_1_vs_eager_loading,
check_db_readiness,
demonstrate_tcl_savepoint_and_ddl_truncate,
initialize_lab_sqlite_schema,
install_signal_handlers,
restore_signal_handlers,
upsert_inventory_item,
)
# Security-only AST ban on unsafe deserialization modules; ORM/HTTP libraries are allowed.
FORBIDDEN_RUNTIME_IMPORTS = frozenset(
{
"pickle",
"_pickle",
"cPickle",
"joblib",
"cloudpickle",
"dill",
"shelve",
"marshal",
}
)
def test_01_solid_protocol_pydantic_v2_and_fail_closed_uow_atomicity(tmp_path: Path) -> None:
# Pydantic v2 strict validation rejects extra keys, type coercion, and unsafe PgBouncer config
with pytest.raises(ValidationError):
DatabaseConfigSpec(db_path="x.db", unknown_key=1) # type: ignore[call-arg]
with pytest.raises(ValidationError):
PaginationQuerySpec(tenant_id="1") # type: ignore[arg-type]
with pytest.raises(ValidationError):
PaginationQuerySpec(tenant_id=1, cursor_ts="2026-11-21T00:00:00Z", cursor_id=None)
with pytest.raises(ValidationError):
PoolRoutingSpec(
app_clients=500,
pgbouncer_pool_size=32,
pgbouncer_mode="transaction",
statement_cache_size=100,
pgbouncer_supports_prepared=False,
)
# Structural typing: both InMemory and Sqlite satisfy Protocols without shared base class
db_file = tmp_path / "orders.sqlite3"
mem_uow = InMemoryUnitOfWork()
sql_uow = SqliteUnitOfWork(db_file)
assert isinstance(mem_uow, UnitOfWorkProtocol)
assert isinstance(sql_uow, UnitOfWorkProtocol)
assert not issubclass(SqliteOrderRepository, InMemoryUnitOfWork)
with SqliteUnitOfWork(db_file) as u:
assert isinstance(u.orders, OrderRepositoryProtocol)
# Identical Domain Service runs cleanly against both InMemory and SQLite adapters (DIP/OCP)
for factory, getter in (
(lambda: mem_uow, lambda: mem_uow),
(lambda: SqliteUnitOfWork(db_file), lambda: SqliteUnitOfWork(db_file)),
):
svc = PlaceOrderService(factory)
with pytest.raises(RuntimeError):
svc.place_order(
OrderCreateSpec(
order_id=900,
tenant_id=7,
status="pending",
created_at="2026-11-21T08:00:00Z",
items=(OrderItemSpec(sku="A100", quantity=1, unit_price_cents=10000),),
),
fail_after_order_insert=True,
)
with getter() as check:
assert check.orders.get_order(900) is None
assert check.outbox.list_events() == []
placed = svc.place_order(
OrderCreateSpec(
order_id=901,
tenant_id=7,
status="paid",
created_at="2026-11-21T08:05:00Z",
items=(OrderItemSpec(sku="H100", quantity=2, unit_price_cents=50000),),
),
fail_after_order_insert=False,
)
assert placed.total_cents == 100000
with getter() as check:
assert check.orders.get_order(901) is not None
assert len(check.outbox.list_events()) == 1
def test_02_dml_on_conflict_upsert_and_tcl_savepoint_rollback(tmp_path: Path) -> None:
db_file = tmp_path / "tcl.sqlite3"
conn = sqlite3.connect(str(db_file))
initialize_lab_sqlite_schema(conn)
q1 = upsert_inventory_item(conn, "GPU-B200", 5, "2026-11-21T09:00:00Z")
q2 = upsert_inventory_item(conn, "GPU-B200", 7, "2026-11-21T09:01:00Z")
conn.commit()
conn.close()
assert q1 == 5
assert q2 == 12
tcl = demonstrate_tcl_savepoint_and_ddl_truncate(tmp_path / "tcl2.sqlite3")
assert tcl["qty_before_sp_rollback"] == 107
assert tcl["qty_after_commit"] == 8
assert tcl["count_mid_delete"] == 0
assert tcl["count_after_rollback"] == 1
def test_03_mvcc_8kib_slotted_page_and_snapshot_visibility_rules() -> None:
eng = MVCCPageEngine(fillfactor=100, n_indexes=2)
x_init = eng.allocate_xid()
t1 = eng.insert_tuple(x_init, {"val": "v1"}, payload_bytes=120)
eng.commit_xid(x_init)
# Frozen tuple is always visible regardless of snapshot xmin/xmax
frozen_t = eng.insert_tuple(1, {"val": "frozen"}, payload_bytes=64)
frozen_t.t_infomask |= HEAP_XMIN_FROZEN
# In-flight update from x_upd (not yet committed) must be invisible to snap_before
x_upd = eng.allocate_xid()
t2, _ = eng.update_tuple(t1, x_upd, {"val": "v2"}, indexed_column_changed=True, oldest_active_xmin=x_init)
snap_before = Snapshot(xmin=x_upd, xmax=eng.next_xid, xip_list=frozenset({x_upd}), current_xid=999)
assert eng.is_tuple_visible(t1, snap_before) is True
assert eng.is_tuple_visible(t2, snap_before) is False
assert eng.is_tuple_visible(frozen_t, snap_before) is True
# After x_upd commits, new snapshot sees t2 and stops seeing t1
eng.commit_xid(x_upd)
snap_after = Snapshot(xmin=eng.next_xid, xmax=eng.next_xid, xip_list=frozenset(), current_xid=999)
assert eng.is_tuple_visible(t1, snap_after) is False
assert eng.is_tuple_visible(t2, snap_after) is True
assert t1.t_ctid == t2.tid
def test_04_isolation_write_skew_under_si_vs_ssi_40001_prevention() -> None:
res = simulate_isolation_anomalies()
assert res["si_ww_overlap"] == 0
assert res["si_write_skew_breached"] is True
assert res["si_active_replicas_after"] == 0
assert res["ssi_rw_cycle_detected"] is True
assert res["ssi_t2_aborted_40001"] is True
assert res["ssi_sqlstate"] == "40001"
assert res["ssi_retry_preserved_invariant"] is True
assert res["ssi_active_replicas_after"] == 1
def test_05_hot_updates_fillfactor_75_vs_non_hot_index_amplification() -> None:
hot = simulate_hot_vs_non_hot_updates(n_rows=120, n_updates=1000, n_indexes=4)
assert hot["non_hot_ratio_pct"] == 0.0
assert hot["non_hot_update_index_writes"] == 4000
assert hot["hot_ratio_pct"] >= 85.0
assert hot["index_write_reduction_pct"] >= 80.0
assert hot["hot_pruned_tuples"] > 0
assert hot["hot_heap_pages"] <= hot["non_hot_heap_pages"]
def test_06_vacuum_tidstore_20x_memory_and_xid_wraparound_thresholds() -> None:
vac = simulate_vacuum_and_xid_wraparound(n_live_tuples=100_000_000, n_dead_tuples=180_000_000)
assert vac["default_autovacuum_trigger"] == 20_000_050
assert vac["tuned_autovacuum_trigger"] == 1_005_000
assert vac["legacy_index_vacuum_passes"] >= 2
assert vac["tidstore_memory_reduction_x"] == 20.0
assert vac["blocked_by_idle_tx"] is True
assert vac["xid_states"]["150M"] == "HEALTHY"
assert vac["xid_states"]["250M"] == "ANTI_WRAPAROUND_FORCED"
assert vac["xid_states"]["1.65B"] == "VACUUM_FAILSAFE_MODE"
assert vac["xid_states"]["2.145B"] == "XID_STOP_LIMIT_SHUTDOWN"
def test_07_btree_8kib_fanout_height_and_real_sqlite_sargable_covering_plan() -> None:
g_bigint = compute_btree_geometry(n_rows=10_000_000, key_bytes=8, fillfactor_pct=90)
assert g_bigint["entry_bytes"] == 20
assert g_bigint["fanout_effective"] == 366
assert g_bigint["tree_height"] == 3
g_comp = compute_btree_geometry(n_rows=10_000_000, key_bytes=32, fillfactor_pct=90)
assert g_comp["entry_bytes"] == 44
assert g_comp["tree_height"] == 4
sq = benchmark_sqlite_indexes_and_pagination(n_hot_tenant_rows=18_000, n_noise_rows=2_000, offset_depth=15_000)
assert "COVERING INDEX" in sq["plan_sargable_covering"].upper()
assert sq["sargable_covering_ms"] < sq["non_sargable_ms"]
assert sq["sargable_speedup"] >= 2.0
def test_08_uuidv4_vs_uuidv7_leaf_fill_cache_and_fpi_wal_amplification() -> None:
uu = simulate_uuid_v4_vs_v7(n_inserts=6000)
assert uu["uuid_v7"]["avg_fill_pct"] >= 85.0
assert uu["uuid_v4"]["avg_fill_pct"] <= 75.0
assert uu["uuid_v7"]["cache_hit_pct"] > uu["uuid_v4"]["cache_hit_pct"]
assert uu["uuid_v7"]["total_wal_mb"] < uu["uuid_v4"]["total_wal_mb"]
assert uu["wal_reduction_pct"] >= 70.0
def test_09_keyset_vs_offset_pagination_parity_and_window_rows_vs_range() -> None:
sq = benchmark_sqlite_indexes_and_pagination(n_hot_tenant_rows=18_000, n_noise_rows=2_000, offset_depth=15_000)
assert sq["pagination_parity_exact"] is True
assert sq["keyset_ms"] < sq["offset_ms"]
assert sq["keyset_speedup"] >= 2.5
assert sq["keyset_rows_scanned"] == 20
assert sq["offset_rows_scanned"] == 15_020
# Window frame trap: tied ts=10 rows (100, 200) yield 300 on default RANGE vs 100 on ROWS
assert sq["window_range_first_row_sum"] == 300
assert sq["window_rows_first_row_sum"] == 100
def test_10_pgbouncer_transaction_pooling_and_pgvector_filtered_recall() -> None:
pb = simulate_pgbouncer_pool_collapse(app_clients=500, pg_max_connections=200, pgbouncer_pool_size=32)
assert pb["direct_rejected_conns"] == 300
assert pb["pgbouncer_rejected_conns"] == 0
assert pb["pgbouncer_backend_ram_mb"] < pb["direct_backend_ram_mb"]
assert pb["pgbouncer_p99_ms"] < pb["direct_p99_ms"]
assert pb["backend_reduction_pct"] >= 90.0
pv = simulate_pgvector_filtered_recall(n_vectors=20_000, tenant_selectivity=0.02, ef_search=40, top_k=10)
assert pv["post_filter_returned_rows"] <= 4
assert pv["post_filter_recall"] <= 0.4
assert pv["iterative_scan_returned_rows"] == 10
assert pv["iterative_scan_recall"] == 1.0
def test_11_real_sqlite_n_plus_1_vs_selectinload_and_joinedload() -> None:
orm = benchmark_n_plus_1_vs_eager_loading(n_orders=100, items_per_order=5, repeats=10)
assert orm["n_plus_1_queries"] == 101
assert orm["selectinload_queries"] == 2
assert orm["joinedload_queries"] == 1
assert orm["query_reduction_pct"] >= 97.0
assert orm["selectinload_wire_rows"] == 600 # 100 orders + 500 items (0 parent duplication)
assert orm["joinedload_wire_rows"] == 500 # 500 joined rows (parent duplicated 5x across columns)
assert orm["selectinload_vpc_rtt_ms"] < orm["n_plus_1_vpc_rtt_ms"]
def test_12_static_validation_of_sql_reference_scripts() -> None:
sql_001 = (LAB_ROOT / "sql" / "001_schema_and_indexes.sql").read_text(encoding="utf-8")
sql_002 = (LAB_ROOT / "sql" / "002_explain_queries_and_tuning.sql").read_text(encoding="utf-8")
for token in (
"CREATE TABLE",
"uuidv7()",
"fillfactor = 75",
"CREATE INDEX CONCURRENTLY",
"INCLUDE",
"WHERE status = 'pending'",
"USING gin",
"USING brin",
"USING hnsw",
"halfvec_cosine_ops",
"lock_timeout",
"NOT VALID",
"VALIDATE CONSTRAINT",
"GRANT",
"REVOKE",
"ENABLE ROW LEVEL SECURITY",
):
assert token in sql_001, f"Missing {token!r} in 001_schema_and_indexes.sql"
for token in (
"ON CONFLICT",
"DO UPDATE",
"NOT MATERIALIZED",
"ROW_NUMBER()",
"ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW",
"LEFT JOIN LATERAL",
"EXPLAIN (ANALYZE, BUFFERS)",
"(created_at, id) <",
"hnsw.iterative_scan",
"ISOLATION LEVEL SERIALIZABLE",
"SAVEPOINT",
"RELEASE SAVEPOINT",
):
assert token in sql_002, f"Missing {token!r} in 002_explain_queries_and_tuning.sql"
# Verify balanced parentheses across both SQL scripts
for name, txt in (("001", sql_001), ("002", sql_002)):
assert txt.count("(") == txt.count(")"), f"Unbalanced parentheses in SQL script {name}"
def test_13_ast_and_runtime_validation_of_sqlalchemy2_reference() -> None:
ref_path = LAB_ROOT / "sqlalchemy2_reference" / "models_and_uow.py"
source = ref_path.read_text(encoding="utf-8")
tree = ast.parse(source, filename=str(ref_path))
imported_mods: set[str] = set()
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
imported_mods.add(alias.name.split(".", 1)[0])
elif isinstance(node, ast.ImportFrom) and node.module:
imported_mods.add(node.module.split(".", 1)[0])
assert "sqlalchemy" in imported_mods
assert "alembic" in imported_mods
for required_symbol in (
"DeclarativeBase",
"Mapped",
"mapped_column",
'lazy="raise"',
"selectinload",
"joinedload",
"expire_on_commit=False",
"NullPool",
"statement_cache_size",
"autocommit_block",
"postgresql_concurrently=True",
):
assert required_symbol in source, f"Missing SQLAlchemy 2.0 SOTA pattern: {required_symbol}"
spec = importlib.util.spec_from_file_location("sqlalchemy2_reference.models_and_uow", ref_path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
try:
spec.loader.exec_module(module)
finally:
sys.modules.pop(spec.name, None)
assert module.OrderModel.__tablename__ == "orders"
assert module.OrderItemModel.__tablename__ == "order_items"
assert module.OutboxEventModel.__tablename__ == "outbox_events"
assert hasattr(module, "SqlAlchemyUnitOfWork")
assert hasattr(module, "SqlAlchemyOrderRepository")
assert hasattr(module, "build_pgbouncer_async_engine")
assert hasattr(module, "alembic_zero_downtime_upgrade")
def test_14_cli_demo_workbench_json_and_zero_forbidden_runtime_imports(tmp_path: Path) -> None:
# AST scan strictly over runtime folders: src/, scripts/, tests/
for folder in ("src", "scripts", "tests"):
for py_file in (LAB_ROOT / folder).rglob("*.py"):
tree = ast.parse(py_file.read_text(encoding="utf-8"), filename=str(py_file))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
top = alias.name.split(".", 1)[0]
assert top not in FORBIDDEN_RUNTIME_IMPORTS, f"Forbidden import {top} in {py_file}"
elif isinstance(node, ast.ImportFrom) and node.module:
top = node.module.split(".", 1)[0]
assert top not in FORBIDDEN_RUNTIME_IMPORTS, f"Forbidden import {top} in {py_file}"
out_json = tmp_path / "workbench.json"
proc = subprocess.run(
[sys.executable, str(LAB_ROOT / "scripts" / "run_lab_demo.py"), "--quick", "--output", str(out_json)],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
check=True,
)
assert "[3] Real SQLite Query Plans, Keyset & Eager Loading:" in proc.stdout
data = json.loads(out_json.read_text(encoding="utf-8"))
panels = data["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
def test_15_real_sqlalchemy_sqlite_selectinload_vs_n_plus_1_and_lazy_raise() -> None:
class TestBase(DeclarativeBase):
pass
class LazyOrder(TestBase):
__tablename__ = "test_lazy_orders"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
tenant_id: Mapped[int] = mapped_column(Integer, nullable=False)
items: Mapped[list[LazyOrderItem]] = relationship(back_populates="order", lazy="select")
class LazyOrderItem(TestBase):
__tablename__ = "test_lazy_order_items"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
order_id: Mapped[int] = mapped_column(ForeignKey("test_lazy_orders.id"), nullable=False)
sku: Mapped[str] = mapped_column(String(32), nullable=False)
order: Mapped[LazyOrder] = relationship(back_populates="items")
class GuardedOrder(TestBase):
__tablename__ = "test_guarded_orders"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
tenant_id: Mapped[int] = mapped_column(Integer, nullable=False)
items: Mapped[list[GuardedOrderItem]] = relationship(back_populates="order", lazy="raise")
class GuardedOrderItem(TestBase):
__tablename__ = "test_guarded_order_items"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
order_id: Mapped[int] = mapped_column(ForeignKey("test_guarded_orders.id"), nullable=False)
sku: Mapped[str] = mapped_column(String(32), nullable=False)
order: Mapped[GuardedOrder] = relationship(back_populates="items", lazy="raise")
engine = create_engine("sqlite:///:memory:")
TestBase.metadata.create_all(engine)
executed_sql: list[str] = []
@event.listens_for(engine, "before_cursor_execute")
def _track_sql(conn, cursor, statement, parameters, context, executemany):
if statement.lstrip().upper().startswith("SELECT"):
executed_sql.append(statement)
n_orders = 6
with Session(engine) as session:
for idx in range(1, n_orders + 1):
lazy_o = LazyOrder(id=idx, tenant_id=42)
lazy_o.items = [LazyOrderItem(sku=f"SKU-{idx}-A"), LazyOrderItem(sku=f"SKU-{idx}-B")]
guarded_o = GuardedOrder(id=idx, tenant_id=42)
guarded_o.items = [
GuardedOrderItem(sku=f"SKU-{idx}-A"),
GuardedOrderItem(sku=f"SKU-{idx}-B"),
]
session.add_all([lazy_o, guarded_o])
session.commit()
# 1. N+1 with lazy="select" issues 1 + N SELECT statements
executed_sql.clear()
with Session(engine) as session:
orders = session.scalars(select(LazyOrder).where(LazyOrder.tenant_id == 42)).all()
skus = [item.sku for order in orders for item in order.items]
assert len(skus) == n_orders * 2
assert len(executed_sql) == 1 + n_orders
# 2. Guarded lazy="raise" catches forgotten eager-load immediately
with Session(engine) as session:
guarded = session.scalars(select(GuardedOrder).where(GuardedOrder.tenant_id == 42)).all()
with pytest.raises(InvalidRequestError):
_ = guarded[0].items
# 3. selectinload reduces 1 + N down to exactly 2 SELECT statements
executed_sql.clear()
with Session(engine) as session:
eager_orders = session.scalars(
select(GuardedOrder)
.where(GuardedOrder.tenant_id == 42)
.options(selectinload(GuardedOrder.items))
).all()
eager_skus = [item.sku for order in eager_orders for item in order.items]
assert len(eager_skus) == n_orders * 2
assert len(executed_sql) == 2
# 4. joinedload with unique() reduces parent+child fetch to 1 SELECT statement
executed_sql.clear()
with Session(engine) as session:
joined_orders = (
session.scalars(
select(GuardedOrder)
.where(GuardedOrder.tenant_id == 42)
.options(joinedload(GuardedOrder.items))
)
.unique()
.all()
)
joined_skus = [item.sku for order in joined_orders for item in order.items]
assert len(joined_skus) == n_orders * 2
assert len(executed_sql) == 1
engine.dispose()
def test_16_sigterm_graceful_shutdown_and_db_readiness(tmp_path: Path) -> None:
db_file = tmp_path / "readiness.db"
conn = sqlite3.connect(str(db_file))
initialize_lab_sqlite_schema(conn)
conn.close()
stop_event = threading.Event()
ready_probe = check_db_readiness(db_file, stop_event=stop_event)
assert ready_probe["status"] == "ready"
assert ready_probe["ready"] is True
assert ready_probe["db_ok"] is True
assert ready_probe["integrity_check"] == "ok"
previous = install_signal_handlers(stop_event)
try:
handler = signal.getsignal(signal.SIGTERM)
assert callable(handler)
handler(signal.SIGTERM, None)
finally:
restore_signal_handlers(previous)
assert stop_event.is_set()
draining_probe = check_db_readiness(db_file, stop_event=stop_event)
assert draining_probe["status"] == "draining"
assert draining_probe["ready"] is False
assert draining_probe["shutting_down"] is True
assert draining_probe["db_ok"] is True
cli_env = os.environ.copy()
existing_pp = cli_env.get("PYTHONPATH", "")
cli_env["PYTHONPATH"] = f"{SRC_DIR}{os.pathsep}{existing_pp}" if existing_pp else str(SRC_DIR)
cli_proc = subprocess.run(
[
sys.executable,
"-m",
"db_internals_lab.mvcc_and_query_engine",
"--healthcheck",
"--db-path",
str(db_file),
],
cwd=str(LAB_ROOT),
env=cli_env,
capture_output=True,
text=True,
check=True,
)
cli_payload = json.loads(cli_proc.stdout)
assert cli_payload["status"] == "ready"
assert cli_payload["ready"] is True
OrderRepository tuyệt đối KHÔNG được tự gọi session.commit(), và làm thế nào typing.Protocol + Transactional Outbox xử lý triệt để lỗi ghi kép (dual-write anomaly)?db_internals_lab: InMemoryUnitOfWork và SqliteUnitOfWork thỏa mãn UnitOfWorkProtocol không qua kế thừa chung; khi PlaceOrderService gặp RuntimeError trước commit(), SqliteUnitOfWork.__exit__ tự động ROLLBACK giữ 0 đơn hàng và 0 sự kiện outbox (không rò rỉ dữ liệu một nửa).
ts = 10 (amt = 100 và amt = 200), câu truy vấn SELECT ..., SUM(amt) OVER (ORDER BY ts) FROM t_win sẽ trả về giá trị bao nhiêu ở hàng đầu tiên, và lệnh nào trên PostgreSQL ẩn chứa bẫy khóa hàng đợi ACCESS EXCLUSIVE hoặc SubtransSLRULock?WHERE (bước 2) trước WINDOW (bước 5) và SELECT (bước 6). Test 09 trên SQLite thật chứng minh mặc định RANGE trả 300 ngay tại hàng đầu tiên so với 100 của ROWS, và Test 02 chứng minh chuỗi SAVEPOINT/ROLLBACK TO/RELEASE + DML INSERT ... ON CONFLICT DO UPDATE an toàn.
active_replicas >= 1 với worker_A = True, worker_B = True. Hai giao dịch đồng thời T1 (tắt A) và T2 (tắt B) cùng đọc thấy sum = 2 >= 2. Điều gì xảy ra dưới REPEATABLE READ (Snapshot Isolation) so với SERIALIZABLE (SSI) trên PostgreSQL?ww_overlap=0), si_active_replicas_after == 0 (vỡ bất biến!); dưới SSI, hệ thống bắt chu trình rw, ném SerializationError('40001') trên T2, và lần chạy lại của T2 thấy còn 1 replica nên từ chối tắt.
4 chỉ mục ở fillfactor = 100 (hoặc cập nhật trúng cột chỉ mục như sự cố Uber) lại bùng phát 4,000 lần ghi chỉ mục trên 1,000 UPDATE, và hai bước nhảy vọt nào ở PostgreSQL 17–18 giải quyết cơn ác mộng VACUUM / XID Wraparound?db_internals_lab: fillfactor=75 kết hợp cập nhật cột ngoài chỉ mục giúp tỉa trang tại chỗ (pruned=970) với 0 ghi chỉ mục cập nhật; còn TidStore nén bộ nhớ dead-TID 20.0x loại bỏ lặp đa pha chỉ mục.
8192 B (8152 B khả dụng), khóa BIGINT (8 B, mục 20 B ở fillfactor = 90%) trên 10,000,000 hàng đạt chiều cao \(h\) bao nhiêu, và vì sao một chỉ mục INCLUDE trên bảng bận rộn không chạy VACUUM lại đột ngột chậm đi dù kế hoạch vẫn ghi Index-Only Scan?8152 / 20 = 407, nhân 0.90 được fanout = 366 và h = 3 ở 10M hàng (h = 4 với khóa 32 B). Giữ autovacuum khỏe là điều kiện tiên quyết để INCLUDE phát huy Index-Only Scan (Heap Fetches: 0).
db_internals_lab (6,000 inserts dưới full_page_writes = on và truy vấn 20,000 hàng tại OFFSET 15000), sự thay đổi định lượng khi chuyển từ khóa chính UUIDv4 + OFFSET sang UUIDv7 (RFC 9562 / PG 18 uuidv7()) + Keyset Seek (created_at, id) < (?, ?) là gì?sqlite3 thực tế: (created_at, id) < (?, ?) giữ độ phức tạp \(O(\log_B N + m)\) và khớp kết quả tuyệt đối (pagination_parity_exact=True), trong khi PG 18 uuidv7() bảo toàn tính đơn điệu dưới mili-giây qua 12 bit rand_a.
WHERE tenant_id = 1 AND substr(created_at, 1, 7) = '2026-06', (b) 500 app clients gọi thẳng vào PostgreSQL max_connections = 200, và (c) truy vấn RAG pgvector WHERE tenant_id = 42 ORDER BY embedding <=> $1 LIMIT 10 với s = 2%, ef_search = 40. Cách xử lý chuẩn và kết quả trong Lab 03 là gì?PgBouncer bảo vệ cụm khỏi sụp đổ bộ nhớ/bối cảnh OS, và hnsw.iterative_scan mở rộng quét biên đồ thị khi bộ lọc hậu kỳ loại bớt ứng viên.
SQLAlchemy 2.0 (asyncpg sau PgBouncer) và Alembic, cặp cấu hình nào ngăn chặn đồng thời cả bão truy vấn N+1, lỗi MissingGreenlet, lỗi DuplicatePreparedStatementError và sự cố dồn hàng đợi khóa DDL kiểu GoCardless?selectinload rút 101 -> 2 truy vấn SQLite với 600 dòng truyền tải (0 nhân bản cha so với 500 dòng có cha lặp 5x ở joinedload), và Test 13 kiểm định tĩnh sqlalchemy2_reference/models_and_uow.py chứa đầy đủ mọi mẫu an toàn SQLAlchemy 2.0 & Alembic.
Hướng dẫn & Gợi ý Từng bước cho 6 Bài tập Trụ cột 5
Bài tập 1 — Kiến trúc OOP typing.Protocol, Fail-Closed Unit of Work & Transactional Outbox
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Giải thích vì sao OrderRepositoryProtocol và UnitOfWorkProtocol loại bỏ khớp nối kế thừa (InMemoryUnitOfWork vs. SqliteUnitOfWork), và liệt kê các bất biến trong __exit__ để bảo đảm fail-closed rollback.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Mở repository_and_uow.py và chạy thử PlaceOrderService với fail_after_order_insert=True rồi False trên cả InMemoryUnitOfWork lẫn SqliteUnitOfWork; kiểm tra các bảng orders và outbox_events.
Tiêu chí Đáp án & Số đối chứng
Khi fail_after_order_insert=True ném RuntimeError, __exit__ gọi ROLLBACK nên get_order(900) is None và outbox.list_events() == [] (0 ghi nửa vời); khi commit() thành công, đơn hàng và sự kiện OrderPlaced cùng bền vững trong 1 giao dịch ACID.
Bài tập 2 — Năm Nhóm lệnh SQL (ON CONFLICT, SAVEPOINT, ROWS vs. RANGE, RLS)
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Vẽ thứ tự thực thi logic 9 bước của DQL (FROM -> WHERE -> GROUP BY -> HAVING -> WINDOW -> SELECT -> DISTINCT -> ORDER BY -> LIMIT) để chứng minh vì sao WHERE không nhìn thấy kết quả ROW_NUMBER(), và phân biệt ROWS với RANGE.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Thực thi upsert_inventory_item, demonstrate_tcl_savepoint_and_ddl_truncate và kiểm tra kết quả t_win trong benchmark_sqlite_indexes_and_pagination(); rà soát sql/001_schema_and_indexes.sql và sql/002_explain_queries_and_tuning.sql.
Tiêu chí Đáp án & Số đối chứng
INSERT ... ON CONFLICT DO UPDATE cộng dồn 5 + 7 = 12 nguyên tử; SAVEPOINT + ROLLBACK TO hoàn tác +99 về đúng 8; DELETE trong ROLLBACK phục hồi nguyên hàng; và trên khóa ts=10 trùng nhau (100, 200), RANGE mặc định trả 300 ở dòng 1 trong khi ROWS trả 100.
Bài tập 3 — Mô phỏng Trang 8 KiB, MVCC, Write Skew (SI vs. SSI) & HOT (fillfactor = 75)
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết điều kiện hiển thị tuple \(\text{HeapTupleSatisfiesMVCC}(v, S)\) theo (t_xmin, t_xmax, xip_list) và hai điều kiện cần–đủ để một UPDATE chạy HOT không chạm \(c\) chỉ mục phụ.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi simulate_isolation_anomalies() và simulate_hot_vs_non_hot_updates(n_rows=120, n_updates=1000, n_indexes=4) trong mvcc_and_query_engine.py, đối chiếu non_hot (fillfactor=100, sửa cột index) với hot (fillfactor=75, sửa cột thường).
Tiêu chí Đáp án & Số đối chứng
Dưới REPEATABLE READ (SI), si_ww_overlap == 0 khiến active_replicas sập 2 -> 0 (Write Skew); SERIALIZABLE (SSI) phát hiện chu trình rw, hủy T2 với SQLSTATE 40001, và retry giữ active_replicas == 1. fillfactor=75 đạt 100.0% HOT (0 ghi chỉ mục cập nhật vs. 4,000, pruned=970).
Bài tập 4 — Tuổi XID Wraparound, VACUUM TidStore (PG 17) & Hình học B-Tree / UUIDv7
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Từ trang B-Tree 8192 - 24 - 16 = 8152 B và S_entry = 4 + 8 + MAXALIGN_8(key_bytes), tính fanout hiệu dụng ở fillfactor=90% cho 8 B (BIGINT) và 32 B (composite) ở \(N = 10^7\), rồi giải thích vì sao UUIDv4 gây bão WAL FPI.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy compute_btree_geometry(), simulate_uuid_v4_vs_v7() và simulate_vacuum_and_xid_wraparound(), kiểm tra mức giảm RAM của TidStore (PG 17) và các ngưỡng XID (200M, 1.6B, 2.145B).
Tiêu chí Đáp án & Số đối chứng
B-Tree 10M BIGINT đạt fanout=366, h=3 (214.05 MB, 76 trang trên) vs. composite 32 B fanout=166, h=4. UUIDv7 nâng mật độ lá 71.4% -> 89.6%, cache hit 64.7% -> 98.9%, và giảm -94.7% WAL (17.17 -> 0.91 MiB). TidStore cắt RAM 1029.97 -> 51.50 MB (20.0x).
Bài tập 5 — Tối ưu Truy vấn Thực tế (EXPLAIN QUERY PLAN, SARGable Covering Index & Keyset Seek)
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chứng minh chi phí quét trang tuần tự của OFFSET k LIMIT m qua \(P = N/m\) trang là \(\Theta(N^2/m)\), và giải thích vì sao substr(created_at, 1, 7) phá vỡ điều kiện tìm kiếm khoảng cột thứ hai trên chỉ mục ghép.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy benchmark_sqlite_indexes_and_pagination(18_000, 2_000, 15_000) để so sánh kế hoạch EXPLAIN QUERY PLAN và kiểm chứng pagination_parity_exact == True giữa OFFSET 15000 và Keyset (created_at, id) < (?, ?).
Tiêu chí Đáp án & Số đối chứng
Truy vấn khoảng SARGable đạt SEARCH TABLE events USING COVERING INDEX ix_events_cov (0.543 -> 0.02 ms, nhanh hơn 27.8x trong workbench); Keyset Seek quét đúng 20 dòng (0.02 ms) so với 15,020 dòng / 0.481 ms của OFFSET 15000 (23.8x nhanh hơn, kết quả trùng khớp 100%).
Bài tập 6 — SQLAlchemy 2.0, Chống Bão N+1, PgBouncer & pgvector RAG (16/16 pytest & AST Scan)
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Phân tích bộ đếm SQL (sqlite3.set_trace_callback lẫn SQLAlchemy before_cursor_execute trên sqlite:///:memory: với DeclarativeBase + lazy="raise" + selectinload), cách cấu hình NullPool + statement_cache_size=0 sau PgBouncer, và lý do ef_search=40 sụp recall khi s=2%.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy python scripts/run_lab_demo.py --output artifacts/t2_ch03_workbench_results.json, kiểm tra CLI --healthcheck, ruff check src tests scripts, và pytest -p no:cacheprovider -v (chú ý Test 13 nạp runtime models_and_uow.py, Test 15 chạy thật SQLAlchemy 2.x, Test 16 kiểm tra SIGTERM & check_db_readiness, Test 14 chỉ cấm giải tuần tự không an toàn pickle/joblib/cloudpickle/dill/shelve/marshal).
Tiêu chí Đáp án & Số đối chứng
selectinload cắt 101 -> 2 truy vấn (-98.0%, RTT 152.25 -> 3.57 ms, 600 dòng không lặp cha); Test 15 kiểm chứng thực thi trực tiếp trên SQLAlchemy 2.x sqlite:///:memory:; PgBouncer gộp 500 -> 32 backend tiết kiệm 1,404.0 MiB (0 từ chối); hnsw.iterative_scan kéo Recall@10 từ 0.2 lên 1.0; và toàn bộ 16/16 pytest đạt xanh tuyệt đối.