이전 스냅숏 시점의 테이블 읽기
읽는 데 약 28분분 걸린다, 7절에 3개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.10판을 번역한 것이다. 원문 읽기
이 장에서는 이전 커밋 이후의 테이블 상태를 세 가지 포맷 각각에서 읽는 방법을 익힌다. 커밋 목록을 확인하고, 각 포맷이 사용하는 번호로 특정 커밋 시점의 상태를 읽고, 포맷 간 번호를 혼동하지 않고 비교한다.
wiki.pageviews_hourly의 대시보드 합계가 있다고 하자. 이 합계는 views를 시간별로 합산하며, 세 번째 시간대의 데이터가 들어온 뒤 값이 달라졌다. 담당자는 두 가지를 묻는다. 그 커밋 이전의 합계는 얼마였는가? 그리고 바뀐 것은 테이블인가, 쿼리뿐인가? 이에 답하려면 테이블의 이력과 테이블의 이전 상태를 읽는 방법이 필요하다. 이 테이블은 hour_utc, domain_code, page_title, views, response_bytes의 다섯 개 열로 이루어져 있다. 이 장의 각 예제는 1장과 마찬가지로 테이블의 사본을 직접 만든다. 테이블을 생성한 다음 00시, 01시, 02시의 데이터를 세 번의 커밋으로 추가한다. 00시의 행 수는 499이고, 나머지 두 시간대는 각각 500이다.
모든 커밋은 스냅샷이다
1장은 세 시간 분량의 데이터를 세 개의 커밋으로 적재한다. 각 커밋은 스냅샷을 남기며, 나중에 읽게 되는 것이 바로 이 스냅샷이다.
커밋은 하나의 원자적 단계로 테이블의 메타데이터를 변경하므로, 독자는 커밋 이전의 테이블이나 이후의 테이블만 볼 수 있고 그 중간 상태는 결코 볼 수 없다. Apache Iceberg에서는 각 커밋이 스냅샷을 만든다. Iceberg 명세는 스냅샷을 "어느 시점의 테이블 상태"로 정의하며, 테이블에 속한 데이터 파일의 전체 집합에 접근하는 데 쓰인다고 설명한다. 또한 각 변경을 메타데이터 파일의 원자적 교체로 기술한다. 스냅샷에는 고유한 ID, 생성 시각, 요약이 있다. 스냅샷 요약에는 필수 필드인 operation이 있으며, 이 값은 append, replace, overwrite, delete 중 하나이다. append는 데이터 파일을 추가하고 하나도 제거하지 않은 커밋이다. 이후의 커밋은 스냅샷을 새로 추가할 뿐 이전 스냅샷은 건드리지 않으며, 덕분에 대시보드 소유자는 더 이상 최신이 아닌 상태에 대해서도 질문할 수 있다.
스캔에 앞서 먼저 이력을 읽는다. 이 예제는 세 커밋을 순서대로, 각 커밋의 연산과 추가된 행 수와 함께 나열하며, Iceberg를 먼저 보이고 이어서 Delta Lake를 보인다.
1"""Commit three hours to an Iceberg table and a Delta Lake table, then list each commit with its operation and rows added.2The prose's point that all three Iceberg commits are appends rests on the operation lines for the snapshots."""34from deltalake import DeltaTable, write_deltalake56from lib.lakehouse import ICEBERG_ID, PAGEVIEWS_SCHEMA, new_warehouse, read_cut_hour, snapshot_labels789def main():10 with new_warehouse() as wh:11 table = wh.catalog.create_table(ICEBERG_ID, schema=PAGEVIEWS_SCHEMA)12 delta_path = str(wh.root / "delta" / "pageviews_hourly")13 for hour in range(3): # hours 00, 01 and 02: one commit to each table per hour14 batch = read_cut_hour(hour)15 table.append(batch)16 write_deltalake(delta_path, batch, mode="append")1718 # sequence_number counts commits, so sorting by it puts the labels in commit order.19 snapshots = sorted(table.snapshots(), key=lambda snapshot: snapshot.sequence_number)20 labels = snapshot_labels([snapshot.snapshot_id for snapshot in snapshots])21 for snapshot in snapshots:22 label = labels[snapshot.snapshot_id]23 operation = snapshot.summary.operation.value24 print(f"{label} operation: {operation}")25 # added-records counts only this commit's rows, not the table's running total.26 print(f"{label} rows added: {snapshot.summary['added-records']}")2728 # Sorted by version, so the lines follow Delta's own numbering whatever order history returns.29 history = sorted(DeltaTable(delta_path).history(), key=lambda entry: entry["version"])30 for entry in history:31 rows = entry["operationMetrics"]["num_added_rows"] # Delta's count of the rows this WRITE added32 print(f"version {entry['version']} operation: {entry['operation']}")33 print(f"version {entry['version']} rows added: {rows}")343536if __name__ == "__main__":37 main()
python snapshot-history.pysnapshot 1 operation: append
snapshot 1 rows added: 499
snapshot 2 operation: append
snapshot 2 rows added: 500
snapshot 3 operation: append
snapshot 3 rows added: 500
version 0 operation: WRITE
version 0 rows added: 499
version 1 operation: WRITE
version 1 rows added: 500
version 2 operation: WRITE
version 2 rows added: 500
세 커밋은 모두 append를 사용했으므로 어느 것도 파일을 다시 쓰거나 제거하지 않았다. 00시는 499행을 추가했는데, 다른 시간보다 한 행이 적다. 데이터 README가 설명하듯 데이터를 자르는 과정에서 한 행이 빠졌기 때문이다. 01시와 02시는 각각 500행을 추가했다. 소유자의 질문은 여기서 시작된다. 테이블에는 고를 수 있는 상태가 세 개 있고, 이력이 그 상태들의 이름을 알려 준다.
pyiceberg는 각 스냅샷에 긴 정수 ID를 부여한다. 이 책은 그 ID를 출력하지 않는다. 대신 snapshot_labels가 ID를 커밋 순서대로 "snapshot 1", "snapshot 2", "snapshot 3"이라는 레이블에 대응시키고, 출력에는 레이블만 나타난다.
같은 세 시간 분량의 데이터를 write_deltalake를 통해 Delta Lake 테이블에도 시간마다 한 번씩 썼다. Delta Lake는 각 커밋을 버전이라고 부르며, 그 이력에는 커밋마다 연산과 기록된 행 수가 나열된다. Delta는 버전을 0부터 매기므로 첫 번째 쓰기가 버전 0이다. 이 책은 Delta 자체의 번호를 그대로 출력하므로, 예제는 이력을 버전 순으로 정렬해 "version 0", "version 1", "version 2"를 출력한다. Delta의 각 쓰기는 WRITE 연산이며, 대응하는 Iceberg 스냅샷과 같은 행을 추가한다. 버전 0은 499행이고, 이어서 500행, 500행이다.
이력은 소유자 질문의 앞부분에 답한다. 어느 커밋이 테이블을 바꾸었는지, 그 커밋이 몇 행을 추가했는지를 알려 준다. append는 행을 추가할 뿐이므로 이미 테이블에 있는 시간대의 합계를 바꿀 수 없다. 어떤 시간대의 합계가 달라졌다면 이력에서 원인이 되는 overwrite, delete, replace 중 하나를 찾아야 하고, 그다음에 그 앞뒤의 스냅샷을 읽는다. 이력은 쿼리가 무엇을 했는지는 알려 주지 않으며, 질문의 그 부분에는 다음 절의 읽기가 필요하다.
작업 규칙: 테이블을 읽거나 변경하기 전에, 사용하는 형식으로 그 이력을 나열하고 그 목록을 커밋 번호의 유일한 출처로 삼는다. 목록은 커밋 순서로 정렬하고, Iceberg 스냅샷은 출력하기 전에 snapshot_labels로 레이블을 붙이며, Delta 버전은 Delta가 매기는 번호 그대로 출력한다. 각 커밋과 함께 연산을 읽는다. append는 파일을 추가할 뿐이므로 행을 제거했을 수 없지만, overwrite나 delete는 제거했을 수 있다.
스냅숏이 가리키는 것
스냅숏은 행을 담고 있지 않다. 행을 담은 파일을 가리킬 뿐이다. 포맷 버전 2와 3에서 스냅숏은 매니페스트 목록(manifest list)을 기록하며, 스냅숏이 가진 파일은 그 목록에서 찾는다. 이전 절의 정의는 스냅숏을 데이터 파일 전체 집합으로 들어가는 입구로 삼으므로, 독자는 스냅숏에서 출발해 그 파일들로 따라간다.
따라서 스냅숏은 포인터의 집합이며, 이 사실은 뒤따르는 모든 절에 영향을 준다. 스냅숏은 그것이 지정한 파일이 아직 존재하는 동안에만 읽힌다. 그러므로 타임 트래블은 백업이 아니다. 타임 트래블은 테이블이 아직 보관하고 있는 파일만 읽을 수 있고, 테이블은 어떤 스냅숏이 그 파일을 지정하고 있는 동안에만 그 파일을 보관한다. 7장은 오래된 스냅숏과 그 스냅숏만 지정하던 파일을 제거하며, 그러면 해당 상태로의 타임 트래블도 끝난다.
커밋의 연산은 어떤 공유가 가능한지를 보여 준다. 명세는 append를 "데이터 파일만 추가되고 제거된 파일은 없는" 연산으로 정의한다. 그래서 스냅숏 3은 0시 구간의 파일을 다시 지정한다. 세 번째 커밋이 그 파일들을 다시 쓰지 않았기 때문이다. 여러 스냅숏이 같은 파일을 지정할 수 있으며, 커밋의 비용은 그 커밋이 쓴 파일과 그 파일을 가리키는 포인터에 그친다.
pyiceberg의 스냅숏에 나온 행 수는 포인터가 작동하는 모습을 보여 준다. 스냅숏 2는 999행을 읽어 내는데, 이는 hour 00은 "00시 구간", hour 01은 "01시 구간"처럼 원문 표기에 맞춰 옮긴다: 00시 구간의 499행과 01시 구간의 500행을 합한 값이며 2시 구간의 행은 하나도 없다. 스냅숏 3은 세 시간 구간을 모두 읽는다. 각 스냅숏은 그 시점까지 커밋이 보이게 만든 행을 읽으며, 그보다 더 읽지는 않는다. 두 행 수의 차이는 세 번째 커밋이 추가한 행, 곧 500행이므로 이력과 읽기 결과가 일치한다.
작업 규칙: 오래된 스냅숏은 그 파일이 존재하는 동안에만 읽을 수 있는 것으로 취급한다. 파일을 제거하기 전에 어떤 스냅숏을 남길지 정하고, 나머지는 먼저 만료시킨다. 정리 후에 오래된 스냅숏에 대한 쿼리가 실패한다면 그것은 파일이 없어진 것이다. 해결책은 테이블의 사본에서 그 파일을 찾는 것이며, 다른 스냅숏을 대신 읽는 것이 아니다.
이전 스냅샷 읽기
이전 스냅샷을 읽는다는 것은 테이블을 스캔할 때 그 스냅샷을 지정한다는 뜻이다. 스냅샷을 지정하는 방법은 형식마다 다르다. Iceberg는 스냅샷 ID를 받는다. DuckLake는 AT (VERSION => n)에 스냅샷 번호를 받는다. Delta Lake는 버전 번호를 받는다. 이 세 가지 번호는 서로 같은 대상을 세지 않는다.
소유자가 가장 먼저 묻는 것은 세 번째 시간대의 데이터가 반영되기 전의 합계가 얼마였느냐는 것이다. 그 답은 두 번째 커밋 이후의 상태, 곧 스냅샷 2이다.
pyiceberg의 스냅숏
pyiceberg 0.12.0에서 scan(snapshot_id=...)는 해당 스냅숏 시점의 테이블을 읽고, 스냅숏 ID 없이 수행한 스캔은 현재 스냅숏을 읽는다. ID로 수행한 두 번의 스캔은 테이블 자체의 이력으로 소유자의 첫 번째 질문에 답한다. 이 예제는 현재 테이블도 읽어 스냅숏 3과 비교한다.
1"""Read an Iceberg table as of snapshot 2 and snapshot 3, by ID, then compare the current table with snapshot 3.2The prose's answer to the owner's first question rests on the snapshot 2 views line, and the failed read on the last line."""34from lib.lakehouse import (5 ICEBERG_ID, PAGEVIEWS_SCHEMA, new_warehouse, read_cut_hour, safe_error, scan_arrow, snapshot_labels, sql_rows,6)789def main():10 with new_warehouse() as wh:11 table = wh.catalog.create_table(ICEBERG_ID, schema=PAGEVIEWS_SCHEMA)12 for hour in range(3):13 table.append(read_cut_hour(hour))1415 snapshots = sorted(table.snapshots(), key=lambda snapshot: snapshot.sequence_number)16 ids = [snapshot.snapshot_id for snapshot in snapshots]17 labels = snapshot_labels(ids)18 # ids[1] is snapshot 2 and ids[2] is snapshot 3: the list is in commit order, counted from 0.19 for snapshot_id in (ids[1], ids[2]):20 arrow = scan_arrow(table, snapshot_id=snapshot_id)21 # The scan is registered in DuckDB as t, so the SQL can count and sum its rows.22 rows, views = sql_rows(wh.con, "SELECT count(*), sum(views) FROM t", t=arrow)[0]23 print(f"{labels[snapshot_id]} rows: {rows}")24 print(f"{labels[snapshot_id]} views: {views}")2526 current = scan_arrow(table) # no snapshot_id, so this reads the current snapshot27 last = scan_arrow(table, snapshot_id=ids[2])28 print(f"current rows: {current.num_rows}")29 # equals compares every row and column, in order; scan_arrow sorts both tables by every column, so row order cannot differ.30 assert current.equals(last)3132 try:33 scan_arrow(table, snapshot_id=2) # 2 is the label's number, not an ID, so this fails on purpose34 except Exception as exc:35 print(f"read by label: {safe_error(exc, wh)}")363738if __name__ == "__main__":39 main()
python read-as-of-snapshot.pysnapshot 2 rows: 999
snapshot 2 views: 580963
snapshot 3 rows: 1499
snapshot 3 views: 899451
current rows: 1499
read by label: ValueError: Snapshot not found: 2
스냅숏 2는 소유자의 첫 번째 질문에 답한다. 세 번째 커밋 이전에 테이블에는 조회 수가 총 580963만큼 있었고, 그 이후인 스냅숏 3은 899451이다. ID 없이 테이블을 읽으면 스냅숏 3과 같은 행이 나오며, 이 검사는 행의 개수만이 아니라 행 자체를 비교한다.
views 열은 소유자의 두 번째 질문에 답한다. 스냅숏 3은 스냅숏 2보다 조회 수가 많고, 그 차이는 02시에 추가된 조회 수이다. 총합이 달라진 것은 대시보드의 쿼리가 바뀌었기 때문이 아니라 세 번째 커밋이 행을 추가했기 때문이다. 같은 테이블을 두 번 읽으면 쿼리를 전혀 바꾸지 않고도 이를 확인할 수 있다.
"스냅숏 2"라는 레이블을 염두에 둔 독자는 숫자 2를 ID로 전달할 수 있다. 이 호출은 실패하며, 이 실패는 안전한 결과이다.
ValueError: Snapshot not found: 2
오류는 전달된 숫자를 그대로 알려 주며, 이 숫자는 스냅숏 ID가 아니다. 테이블에서는 아무것도 바뀌지 않았다. 그러면 독자는 ID를 찾아봐야 한다는 것을 알게 된다. 이 예제는 각 ID를 table.snapshots()에서 찾아 쓰며, 개수로 ID를 계산하지 않는다. 레이블은 본문 설명을 위한 것이고, ID는 스캔을 위한 것이다.
작업 규칙: 스냅숏 ID는 table.snapshots()에서 가져오고, 레이블의 번호가 아니라 직접 찾아본 ID를 전달한다. 무엇이든 출력하기 전에 ID를 커밋 순서대로 레이블에 대응시킨다. 질문이 커밋 이후의 상태에 관한 것이라면, 먼저 이력에서 그 커밋을 찾고 그 커밋이 만든 스냅숏을 읽는다.
각 형식에서 번호로 커밋 읽기
Delta Lake는 DeltaTable(path, version=n)로 이전 버전을 읽는다. 버전은 테이블 이력에서 그 커밋이 놓인 위치이며 0부터 센다. 따라서 버전 0이 첫 번째 쓰기다. 도우미 read_delta는 경로와 선택적 버전을 받아 정렬된 Arrow 테이블로 행을 반환한다. 이 책에서 Delta를 읽는 모든 작업은 deltalake의 QueryBuilder를 거치며, 도우미가 이를 대신 호출한다. 그 이유는 결정 절에서 설명한다.
DuckLake는 카탈로그에 변경이 생길 때마다 스냅샷을 하나씩 남기며, 스키마 생성과 테이블 생성도 변경에 포함된다. DuckLake도 스냅샷 번호를 0부터 매기므로, 새 카탈로그에서 첫 번째 insert의 번호는 1이 아니다. DuckLake 시간 여행 페이지는 스냅샷을 읽는 구문 SELECT * FROM tbl AT (VERSION => 3);을 보여 주며, 조회할 스냅샷을 타임스탬프로 지정하거나 "스냅샷 식별자를 명시적으로" 지정할 수 있다고 설명한다. 이 책은 식별자를 사용한다. 번호는 직접 센 insert 횟수가 아니라 ducklake_snapshots에서 읽어야 한다.
세 버전 예제에서는 행 수는 일치하는데 번호는 서로 어긋난다. 이 예제는 같은 세 시간 분량의 데이터를 Delta 테이블과 DuckLake 테이블에 쓰며, 형식마다 시간당 커밋 하나를 만든다. 각 커밋을 번호로 다시 읽어 두 행 수를 출력하고, 첫 번째 insert 이전의 DuckLake 스냅샷 수를 세며, 실패 사례 하나를 보여 준다.
1"""Commit the same three hours to Delta Lake and DuckLake, then read each commit back by its own number.2The prose's point that each hour gives the same row count in both formats rests on the paired row-count lines."""34from deltalake import DeltaTable, write_deltalake56from lib.lakehouse import (DUCKLAKE_ALIAS, NAMESPACE, TABLE, attach_ducklake, connect_ducklake, new_warehouse,7 read_cut_hour, read_delta, safe_error, snapshot_labels, sql_rows)89LAKE_TABLE = f"{DUCKLAKE_ALIAS}.{NAMESPACE}.{TABLE}"10CATALOG_SNAPSHOTS = f"SELECT snapshot_id FROM ducklake_snapshots('{DUCKLAKE_ALIAS}')"11# Fetches snapshot_time, which turns into Python values through pytz; the pins do not install pytz, so this fails on purpose.12TIME_COLUMN = f"SELECT snapshot_time FROM ducklake_snapshots('{DUCKLAKE_ALIAS}')"131415def main():16 with new_warehouse() as wh:17 delta_path = str(wh.root / "delta" / TABLE)18 connect_ducklake(wh.con)19 attach_ducklake(wh.con, DUCKLAKE_ALIAS, wh.root)20 wh.con.execute(f"CREATE SCHEMA {DUCKLAKE_ALIAS}.{NAMESPACE}")21 # A zero-row slice of hour 00: it gives the table its columns and types, and no rows.22 sql_rows(wh.con, f"CREATE TABLE {LAKE_TABLE} AS SELECT * FROM empty", empty=read_cut_hour(0).slice(0, 0))23 for hour in range(3): # hours 00, 01 and 02, one commit to each table per hour24 batch = read_cut_hour(hour)25 write_deltalake(delta_path, batch, mode="append")26 sql_rows(wh.con, f"INSERT INTO {LAKE_TABLE} SELECT * FROM batch", batch=batch)2728 # Keeps only the snapshots that inserted rows, so the schema and table creations are left out.29 inserts = sorted(row[0] for row in sql_rows(wh.con, CATALOG_SNAPSHOTS + " WHERE map_contains(changes, 'tables_inserted_into')"))30 # Snapshot IDs count up with each change, so these are the snapshots made before the first insert.31 before = sql_rows(wh.con, CATALOG_SNAPSHOTS + f" WHERE snapshot_id < {inserts[0]}")32 print(f"snapshots before the first insert: {len(before)}")3334 # Labels count every DuckLake snapshot from 1, setup snapshots included, not DuckLake's own numbers.35 lake_labels = snapshot_labels(sorted(row[0] for row in sql_rows(wh.con, CATALOG_SNAPSHOTS)))36 delta_versions = list(range(DeltaTable(delta_path).version() + 1)) # Delta versions run from 0 to the latest37 # zip pairs each hour's Delta version with its DuckLake insert, in order; strict fails if the counts differ.38 for hour, (delta_version, snapshot) in enumerate(zip(delta_versions, inserts, strict=True)):39 # DuckLake reads by the snapshot ID from ducklake_snapshots, never by counting the inserts.40 lake = sql_rows(wh.con, f"SELECT count(*) FROM {LAKE_TABLE} AT (VERSION => {snapshot})")[0][0]41 rows = len(read_delta(delta_path, version=delta_version)) # read_delta goes through QueryBuilder, because to_pyarrow_table() aborted at exit in some test runs at these pins.42 print(f"after hour {hour:02d}, Delta version {delta_version} rows: {rows}")43 print(f"after hour {hour:02d}, DuckLake {lake_labels[snapshot]} rows: {lake}")4445 try:46 wh.con.execute(TIME_COLUMN).fetchall()47 except Exception as exc:48 print(f"select time: {safe_error(exc, wh)}")495051if __name__ == "__main__":52 main()
python three-version-numbers.pysnapshots before the first insert: 3
after hour 00, Delta version 0 rows: 499
after hour 00, DuckLake snapshot 4 rows: 499
after hour 01, Delta version 1 rows: 999
after hour 01, DuckLake snapshot 5 rows: 999
after hour 02, Delta version 2 rows: 1499
after hour 02, DuckLake snapshot 6 rows: 1499
select time: InvalidInputException: Invalid Input Error: Required module 'pytz' failed to import, due to the following Python exception:
ModuleNotFoundError: No module named 'pytz'
첫 번째 insert가 "스냅샷 1"이 아니라 "스냅샷 4"인 까닭은 그 앞에 DuckLake 카탈로그가 이미 스냅샷 3개를 가지고 있기 때문이다. 이 스냅샷은 attach할 때 DuckLake가 만드는 기본 스키마, wiki 스키마, 그리고 테이블이다. 이 책은 설정 단계를 포함해 DuckLake의 스냅샷을 1부터 표기하므로, "스냅샷 4"는 DuckLake 자체 번호 3에 1을 더한 값이다. insert를 1부터 세는 독자는 잘못된 번호 표기를 얻게 된다.
두 형식은 커밋 번호 체계가 달라도 매 시간이 지난 뒤 같은 수의 행을 담고 있다. 두 형식이 번호 체계를 공유하지 않으므로, 둘을 맞추는 키는 시간이다. 전체 테이블인 02시 이후에는 Delta 버전 2가 1499개 행을, DuckLake 스냅샷 6이 1499개 행을 가지며, 앞선 시간대도 같은 방식으로 일치한다.
아래 표는 세 가지 번호를 나란히 비교한다.
| 형식 | 커밋을 가리키는 번호 | 세는 변경의 범위 | 읽는 방법 |
|---|---|---|---|
| Iceberg | 스냅샷 ID, 긴 정수 | 테이블에 대한 각 커밋 | scan(snapshot_id=...) |
| Delta Lake | 버전, 0부터 셈 | 테이블에 대한 각 커밋 | DeltaTable(path, version=n) |
| DuckLake | 스냅샷 번호, 0부터 셈 (이 책의 표기는 1 더 큼) | 스키마와 테이블 생성을 포함한 카탈로그의 모든 변경 | AT (VERSION => n) |
작업 규칙: 형식을 비교할 때는 원시 번호가 아니라 각 커밋이 적재한 시간을 기준으로 삼는다. Iceberg와 DuckLake의 스냅샷은 표기와 함께 출력하고, Delta 버전은 Delta가 매기는 번호 그대로 출력하며, 행 수를 그 번호에 연결한다. Delta는 read_delta로만 읽고, DuckLake는 ducklake_snapshots에서 얻은 번호로만 읽는다. 한 형식의 테이블에만 커밋이 추가되면 표기가 더는 맞지 않게 되며, 그때는 각 형식의 이력만이 유일하게 신뢰할 수 있는 기록이 된다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
What goes wrong in production
The failures in this chapter are the ones a reader is likely to meet first. The first two appear in this chapter's examples. The third and fourth are argued from the documentation and the book's rules, and the fifth and sixth lean on chapter 1 and chapter 7. The first is the number that is not an ID. A failed scan is a safe failure, because the error says what was wrong. Worse failures come from reading a number that is valid in one format and means something else in another, or from a query that runs and returns something unexpected. The read-as-of-snapshot example shows the first kind: the ID guess fails loudly, and the error text names the value that was passed.
Fetching a time column fails for a different reason, a missing module. The three-version example includes a select of snapshot_time from ducklake_snapshots, and the call fails:
InvalidInputException: Invalid Input Error: Required module 'pytz' failed to import, due to the following Python exception:
The message says the pytz module is missing. The pinned environment does not install it. DuckDB's Python client needs pytz to turn a TIMESTAMPTZ column such as snapshot_time into Python values. The three-version example avoids the problem by selecting only snapshot_id and filtering on changes, so it never fetches snapshot_time. To read the time anyway, cast it with snapshot_time::VARCHAR. Leave out the column or cast it; we would rather not add a package the book does not pin.
Reading by timestamp is the third trap. DuckLake accepts a timestamp in AT (TIMESTAMP => ...), and Iceberg snapshots have a creation time. A timestamp picks a state by the clock, and the clock is the time when each commit ran. In production that is a good way to ask for "the table as it was at nine in the morning". An example would have to take a clock time from the run, which changes on every run, so the book uses IDs and version numbers instead. Choose the timestamp form when you need a point in wall-clock time and you have a record of when each commit ran. Choose the number form when you need the same answer every time.
Numbers drift between formats. Two formats can hold the same table, and the same label can then name different states. The book's example commits the same hours in the same order, so the labels agree. A production table that receives a repair in one format and not the other will not agree. Even with identical histories, the raw numbers do not line up across formats, because DuckLake's snapshot numbers also count schema and table creation. A dashboard that reads "version 4" from both formats will show different totals, so compare commits by their labels. The check is to compare the row counts for the label in both formats before you trust either number. The three-version example does that.
A file count can also read low, because DuckLake may keep a small insert in the catalog instead of writing a Parquet file, under the default chapter 1 names. The example's first hourly batch alone holds 499 rows, far over that limit, so under that default each of its inserts is written as a file. A count of data files is only meaningful once you know the row limit.
The failure this chapter warns about most comes later, at a read after a cleanup. What a snapshot points to gives the reason: the error appears only when a reader asks for a snapshot whose files are gone. Nothing fails at the cleanup itself. Chapter 7 shows which files a cleanup removes.
Working rule: Read the error text before you change the query. It names the value, the module or the version that failed, and that is the fastest route to the fix. Compare each count in one format with the same label in the other format before you trust either one. Keep the snapshot your question needs readable until the question is answered, and expire only the snapshots that no question still needs. Record the label and the format's name with every number you report, so that a reader of the report can reproduce it.
이 장에서 내린 결정
- ID가 아니라 레이블을 쓴다. 출력되는 줄에는 Iceberg와 DuckLake에 대해 "snapshot 2" 같은 레이블이 붙는다. 이 레이블은 형식이 기록하는 모든 스냅샷을 1부터 센 번호다. DuckLake의 경우 설정 단계의 스냅샷 세 개가 여기에 포함되므로, DuckLake 자체의 번호는 레이블보다 1 작다. Iceberg ID와 DuckLake 스냅샷 번호는 출력에 나타나지 않는다. Delta는 0부터 세는 자신의 버전 번호를 그대로 출력하며, 독자는 이 번호를
DeltaTable에 전달한다. 독자는 예제를 다시 실행해 출력 텍스트를 줄 단위로 비교할 수 있다. diff에는 데이터나 라이브러리의 변경만 나타나고, 무작위 ID의 변경은 나타나지 않는다. 레이블은 커밋 순서대로 대응시키므로, 라이브러리가 이력을 다른 순서로 돌려주어도 레이블의 의미는 유지된다. - 타임스탬프가 아니라 ID와 버전 번호를 쓴다. 타임스탬프로 읽으면 시계와 각 커밋이 실행된 시점에 결과가 좌우된다. 우리는 ID나 번호로 읽으므로, 예제를 언제 실행하든 같은 커밋에서 같은 행을 얻는다. 실제 시각이 필요한 운영 환경의 독자는 타임스탬프 형식을 사용하고 각 커밋이 실행된 시점의 기록을 따로 보관해야 한다.
- Delta는
read_delta만으로 읽는다. 헬퍼는 deltalake의QueryBuilder를 통해 읽는다. 이 고정 버전에서는 8장에서 측정하듯이to_pyarrow_table()경로가 일부 실행에서 종료 시 비정상 종료한다. 우리는 이 비정상 종료를 우회하는 대신 읽기 경로를 하나로 고정한다. 따라서 어떤 예제도os._exit를 호출하거나 종료 상태를 숨기지 않는다. - DuckLake는 헬퍼만으로 쓴다. 모든 DuckLake 실행은
connect_ducklake로 DuckLake를 로드하고attach_ducklake로 연결한다.allow_unsigned_extensions는 설정하지 않는다. 이 책의 실행은 헬퍼가 두 해시를SOURCE.toml와 대조해 확인한 뒤, 저장소에 포함된 파일에서 DuckDB의 공식 서명 DuckLake 확장을 로드한다. 따라서 오프라인 실행에도 다운로드가 필요 없다. 독자 자신의 컴퓨터에서 포함된 그 파일이 없을 때만connect_ducklake가INSTALL ducklake를 실행한다. - 카탈로그에는 좁은 쿼리를 쓴다.
ducklake_snapshots에 대한 쿼리는 열 이름을 명시하고snapshot_time을 제외한다. 이 열은 고정 버전에 설치되지 않은 모듈을 필요로 하기 때문이다. 고정 버전에 기록되지 않은 의존성을 추가하기보다 필요한 열의 이름을 명시하는 편이 낫다. - Delta는 자신의 번호를 유지한다. Delta는 0부터 센 실제 버전을 출력한다. 각 레이블은 해당 커밋이 자신의 테이블에서 어느 커밋인지만 말해 주며, 두 형식이 같은 상태를 담고 있다는 뜻은 결코 아니다. 같은 상태인지는 레이블별 행 수를 비교해서 확인한다.
- 실패는 발생시키지 않고 출력한다. 두 예제는 일부러 실패하는 호출로 끝나며, 각각 오류를 잡아 출력한다. 독자가 이 실패를 만나게 되므로 실패를 보여 주며, 독자가 자신의 출력과 대조할 수 있도록 오류 텍스트를 전부 출력한다.
- 상태보다 이력을 먼저 읽는다. 코드는 각 형식의 커밋을 먼저 나열하고, 그다음에 번호로 커밋을 읽는다. 이 장의 독자는 스캔에 앞서 각 커밋의 작업과 행 수를 먼저 확인할 수 있으므로, 이상해 보이는 행 수를 그 수를 만든 커밋과 대조해 확인할 수 있다.
이 판의 이 장
2026.11.10판예제 통과 2026년 11월 20이 장에서 3개 예제개 중 3개가 통과한다
영어판 2026.11.10판을 번역한 것이다.