Repository navigation
Decision: catalog snapshot validated by a fingerprint on every query #187
CharmingGroot
announced in
Announcements
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Background
Discussion #87 decided to read keys, column types and resolved column names on every query, with no cache, so that a dropped key or a changed column type is never trusted. The reads share one pipelined round trip with the preparation of the statement, so a known plan takes 2 round trips.
Three coming needs change the trade-off:
NOT NULL(Omit IS NOT NULL conditions on NOT NULL columns #111) and foreign keys (Eliminate joins that foreign keys make redundant #112) need more of the catalog. Read on every query, each adds to the per-query catalog query.UNIONtyping) run insidePostgresBackend::run, so every database adapter would repeat them.#87 rejected caching because a sound invalidation check needs the database anyway. That holds; this decision keeps the check and changes what it reads.
Decision
The engine keeps a catalog snapshot and checks, on every query, a fingerprint of the catalog entries the query depends on.
NOT NULL, its unique keys under the conditions of Decision: read catalog metadata on every query, in one round trip #87 (valid, not deferrable, not partial, on plain columns, no inheritance children), and its foreign keys. For eachrr:sqlQuery: its result columns and their types. Each table also has a fingerprint.pg_attribute), its unique indexes (pg_index) and its foreign keys (pg_constraint). Non-unique indexes are not included, since they do not change results.v12n-core(CatalogSnapshot). TheBackendport gains a method that loads it for a set of tables. Mapping compilation,v12n check --dband query planning read the same structure.v12n-coreresolves names, eliminates self-joins, decides duplicate removal, typesUNIONbranches and renders the final SQL before any round trip.Backend::executethen checks the fingerprints and runs that SQL.rr:sqlQueryalso parses its column probe in that round trip, as now, and compares the types with the snapshot.v12n serveloads the snapshot for every table of the mapping at startup, on the connection that already checks the database.v12n queryloads only the tables of its plan, pipelined with the session setup at connect.v12n check --dbreports tables and columns that the mapping names and the catalog lacks.v12n servelogs them at startup and starts. A query that reads such a table is still checked, so a table created later is found; if it is still missing, the query fails with an error that names it.Why
NOT NULLand foreign keys enter the snapshot and the fingerprint; the check still returns one hash per table.Measurement
The fingerprint query and the key query of #87 were run alternately with
pgbench -M preparedinside the PostgreSQL 17 container, 6 runs of 4,000 executions each, on tables with a primary key, a unique column, a foreign key and 17 columns. The host was under load (load average about 10), so the numbers compare the two queries and are not absolute costs.For the tables of one plan, the check costs about the same as the key query it replaces. Over every table of a larger mapping it would cost more, which is why the check covers only the tables the plan reads.
The fingerprint changed after each of these statements: dropping a unique constraint, adding it again, changing a column type, dropping
NOT NULL, dropping a foreign key, renaming a column, and adding or dropping an inheritance child. It did not change after creating a non-unique index.Alternatives
Limits
ALTER DOMAINadding a constraint) are not detected. They do not affect keys, types or names.Implementation
#110 implements the snapshot, the check and the move of the planning steps, and measures round trips per query and startup time before and after with
bench/. #111 and #112 then useNOT NULLand foreign keys from the snapshot.References
pg_attribute,pg_index,pg_constraint,pg_inherits— https://www.postgresql.org/docs/17/catalogs.html배경
Discussion #87은 키, 컬럼 타입, 해석한 컬럼 이름을 쿼리마다 읽고 캐시하지 않기로 정했다. 삭제된 키나 바뀐 컬럼 타입을 믿지 않기 위해서다. 읽기는 문장 준비와 같은 파이프라인 왕복으로 보내므로 아는 계획은 왕복 2번이다.
앞으로 필요한 세 가지가 이 판단을 바꾼다.
NOT NULL(Omit IS NOT NULL conditions on NOT NULL columns #111)과 외래 키(Eliminate joins that foreign keys make redundant #112)는 카탈로그를 더 많이 읽는다. 쿼리마다 읽으면 쿼리당 카탈로그 쿼리가 그만큼 커진다.UNION타입 맞춤)가PostgresBackend::run안에 있어, DB 어댑터마다 같은 단계를 다시 구현해야 한다.#87은 올바른 무효화 검사도 결국 DB에 물어야 하므로 캐시를 쓰지 않았다. 이 판단은 그대로이며, 이번 결정은 검사를 유지하고 검사가 읽는 대상을 바꾼다.
결정
엔진은 카탈로그 스냅샷을 가지고, 쿼리마다 그 쿼리가 의존하는 카탈로그 항목의 지문을 확인한다.
NOT NULL), #87의 조건(유효, 지연 불가, 부분 인덱스 아님, 일반 컬럼, 상속 자식 없음)을 만족하는 유일 키, 외래 키를 담는다.rr:sqlQuery마다 결과 컬럼과 타입을 담는다. 테이블마다 지문이 있다.pg_attribute), 유일 인덱스(pg_index), 외래 키(pg_constraint)를 포함한다. 유일하지 않은 인덱스는 결과를 바꾸지 않으므로 넣지 않는다.v12n-core의 데이터 구조(CatalogSnapshot)다.Backend포트에 테이블 목록의 스냅샷을 읽는 메서드를 추가한다. 매핑 컴파일,v12n check --db, 쿼리 계획이 같은 구조를 읽는다.v12n-core가 스냅샷으로 이름 해석, self-join 제거, 중복 제거 판단,UNION브랜치 타입 맞춤, 최종 SQL 렌더링을 왕복 전에 끝낸다.Backend::execute는 지문을 확인하고 그 SQL을 실행한다.rr:sqlQuery를 읽는 계획은 지금처럼 같은 왕복에서 컬럼 probe도 파싱하고, 그 타입을 스냅샷과 비교한다.v12n serve는 DB 확인용으로 이미 여는 연결에서 시작할 때 매핑의 모든 테이블을 읽는다.v12n query는 계획이 읽는 테이블만, 접속할 때 세션 설정과 같은 파이프라인으로 읽는다.v12n check --db는 매핑에 있지만 카탈로그에 없는 테이블과 컬럼을 알린다.v12n serve는 시작할 때 이를 로그로 남기고 시작한다. 그런 테이블을 읽는 쿼리도 확인을 거치므로 나중에 만든 테이블은 반영된다. 여전히 없으면 그 테이블 이름을 담은 오류로 실패한다.이유
NOT NULL과 외래 키는 스냅샷과 지문에 들어가고, 확인은 여전히 테이블마다 해시 하나를 돌려준다.측정
지문 쿼리와 #87의 키 쿼리를 PostgreSQL 17 컨테이너 안에서
pgbench -M prepared로 번갈아 실행했다. 4,000번 실행을 6회 반복했고, 테이블마다 기본 키, 유일 컬럼, 외래 키, 컬럼 17개가 있다. 호스트 부하가 높았으므로(load average 약 10) 수치는 두 쿼리의 비교이며 절대 비용이 아니다.계획 하나의 테이블에서는 확인 비용이 대체하는 키 쿼리와 비슷하다. 큰 매핑의 모든 테이블을 확인하면 더 비싸므로 확인 대상은 계획이 읽는 테이블로 한정한다.
지문은 다음 문장마다 바뀌었다: 유일 제약 삭제와 재추가, 컬럼 타입 변경,
NOT NULL삭제, 외래 키 삭제, 컬럼 이름 변경, 상속 자식 추가와 삭제. 유일하지 않은 인덱스를 만든 뒤에는 바뀌지 않았다.다른 방안
한계
ALTER DOMAIN으로 제약 추가)은 감지하지 않는다. 키, 타입, 이름에는 영향이 없다.구현
#110이 스냅샷, 확인, 계획 단계 이동을 구현하고, 쿼리당 왕복 수와 시작 시간을
bench/로 변경 전후에 측정한다. 이어서 #111과 #112가 스냅샷의NOT NULL과 외래 키를 쓴다.참고
pg_attribute,pg_index,pg_constraint,pg_inherits— https://www.postgresql.org/docs/17/catalogs.htmlAll reactions