테이블을 포맷 간에 옮기고 사본을 검증하기

읽는 데 약 35분분 걸린다, 7절에 4개 예제이(가) 있음.

2026.11.10판 예제 통과 2026년 11월 20 39개 예제 중 39개 통과 변경 사항

AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식

영어판 2026.11.10판을 번역한 것이다. 원문 읽기

이 장을 마치면 테이블을 한 포맷에서 다른 포맷으로 복사하고, 사본이 같은 행을 담고 있는지 확인할 수 있다. 또한 복사가 남기고 가는 것이 무엇인지 말할 수 있고, 어떤 손실은 받아들이고 어떤 손실은 이동을 멈춰야 하는지 판단할 수 있다.

분석가들은 페이지뷰 테이블을 DuckLake에서 쓰려고 한다. DuckLake에서는 카탈로그 파일을 DuckDB로 조회한다. 페이지뷰 테이블 wiki.pageviews_hourly은 1장부터 Apache Iceberg에 있었다. 다른 팀은 테이블을 Delta Lake에 보관하며, 같은 행을 Iceberg에서도 쓰려고 한다. 두 이동 모두 원본은 그대로 두고, 새 테이블로 복사하는 방식이다. 복사는 한 번 하는 쓰기 작업이며, 작업의 대부분은 그 주변의 검증에 있다. 이 장에서는 두 가지 복사를 모두 수행한 다음, 조용히 발생하는 손실을 잡아내는 검증을 추가한다.

이 장의 예제는 pyiceberg 0.12.0, deltalake 1.6.6, 그리고 DuckLake도 실행하는 DuckDB 2.0.0를 고정해서 사용한다. 각 복사 예제는 임시 웨어하우스에 작은 원본을 직접 만들며, 원본은 페이지뷰 데이터에서 잘라 낸 같은 세 시간 분량이다. 행 수는 1499개이다.

복사가 보존하는 것과 잃는 것

마지막으로 변경된 판: 2026.11.10판

복사는 한 시점에 한 테이블의 행을 읽어 다른 형식의 다른 테이블에 쓴다. 대상 라이브러리는 각자 자신의 데이터 파일, 메타데이터, 이력을 쓴다. 이동을 거쳐 살아남는 것은 양쪽이 모두 표현할 수 있는 것, 곧 행과, 양쪽이 모두 타입을 지원하는 열이다. 그 밖의 것은 원본에 남거나, 대상에서 직접 다시 설정해야 한다.

손실은 표로 보면 가장 이해하기 쉽다. 각 행은 테이블의 한 부분, 복사가 그 부분을 어떻게 다루는지, 그리고 이 장이 결과를 보여 주는 위치를 나타낸다.

테이블의 부분 복사 후 이 장에서 보여 주는 위치
행과 그 값 보존됨 다이제스트 검사
열 이름과 타입 양쪽 형식에 해당 타입이 있으면 보존됨 Delta Lake 절
커밋 이력 손실됨. 복사는 자체 이력을 새로 시작한다 두 복사 절 모두
파티션 스펙 대상에서 설정하지 않으면 손실됨 DuckLake 절
마이크로초 미만의 타임스탬프 형식에 따라 다름: 거부되거나, 잘리거나, 보존됨 타임스탬프 절

이력은 독자가 흔히 알아차리지 못하는 손실이다. Iceberg는 변경을 스냅샷으로 기록하고, Delta Lake는 각 커밋을 버전으로 기록한다. 스냅샷과 타임 트래블에 관한 장에서 독자가 이를 어떻게 사용하는지 보여 주었다. 복사는 대상에서 새 이력을 시작하므로, 대상의 이력은 복사 시점에서 출발한다. 원본은 여러분이 원본을 보관하는 동안 자신의 이력을 그대로 가진다. 복사본에는 원본을 가리키는 것이 아무것도 없다.

복사는 등록과도 다르다. 등록된 메타데이터 파일은 파일을 건드리지 않고 테이블을 두 번째 카탈로그에서 보이게 하므로, 두 카탈로그가 같은 데이터를 읽는다. 복사는 새 파일을 쓰고 원본은 그대로 두므로, 이제 두 테이블이 각각 쓰기를 받으며 서로 어긋날 수 있다. 대상이 자신의 파일과 이력을 소유해야 한다면 복사를 선택한다. 두 카탈로그가 한 벌의 파일을 공유해야 한다면 등록을 선택하되, 공유하는 파일을 제자리에 두어야 한다는 점을 받아들여야 한다.

행이 보존되는 것은 복사가 파일이 아니라 값을 옮기기 때문이다. 복사는 데이터 파일을 옮기지 않는다. 한 테이블에서 값을 읽어 다른 테이블을 위한 새 Parquet 파일을 쓴다. 그래서 원본과 복사본의 파일 이름과 파일 개수가 다르며, 파일 이름이나 파일 개수를 비교해서는 복사를 검증할 수 없다. 검증은 행을 비교해야 한다.

작업 규칙: 복사하기 전에, 원본에는 있지만 대상이 보존하지 않을 것을 나열한다. 그것은 이력, 파티션 스펙, 그리고 대상이 저장할 수 있는 것보다 더 세밀한 값이다. 각 항목에 손실을 받아들이거나, 대상에서 속성을 직접 설정하거나, 이동을 중단하는 결정 중 하나를 내린다. 런북에는 모든 결정이 명시되어야 한다.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Copy the pageviews table into DuckLake

마지막으로 변경된 판: 2026.11.10판

The copy reads the Iceberg table with scan_arrow, then gives those rows to DuckLake. DuckLake creates an empty table with their columns, sets the partition spec on it, and then inserts the rows with INSERT ... SELECT. Arrow is the bridge because each side keeps its own library. pyiceberg reads the source, and DuckDB writes the DuckLake table through its own ducklake extension. Neither side reads the other's files. The catalog chapter showed how the DuckLake catalog is attached, and the helper in this chapter attaches it the same way.

The source is partitioned by the hour of hour_utc, which is the layout that moving from daily to hourly partitions arrives at. Here pyiceberg builds that source with the hourly spec, then appends three hours, one commit each:

iceberg-to-ducklake-copy.py Python 3.12.15 · deltalake 1.6.6 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 통과
"""Copy an Iceberg table into DuckLake through Arrow, then print what the copy kept of the layout and the history.The point rests on the copy partition transforms and copy files per partition lines, which show whether thelayout arrived with the rows, and on the copy snapshot lines, which show the history starting at the copy."""from pyiceberg.partitioning import PartitionField, PartitionSpecfrom pyiceberg.transforms import HourTransformfrom lib.lakehouse import (copy_to_ducklake, create_iceberg_table, ducklake_files_by_partition, ducklake_partition_transforms,                           new_warehouse, read_cut_hour, safe_error, scan_arrow, TABLE)def main():    try:        with new_warehouse() as wh:            # source_id 1 is the field ID of hour_utc in the table lib creates            spec = PartitionSpec(PartitionField(source_id=1, field_id=1000, transform=HourTransform(), name="ts_hour"))            table = create_iceberg_table(wh, partition_spec=spec)            for hour in range(3):                table.append(read_cut_hour(hour))            arrow = scan_arrow(table)            print(f"source rows: {arrow.num_rows}")            print(f"source snapshots: {len(table.metadata.snapshots)}")            for field in table.spec().fields:                print(f"source partition field: {field.name}")            # the helper creates the copy empty, sets this spec with ALTER, and only then inserts the rows            target = copy_to_ducklake(wh, arrow, partition_by="hour(hour_utc)")            print(f"copy rows: {wh.con.execute(f'SELECT count(*) FROM {target}').fetchall()[0][0]}")            # current=True keeps only the spec still in force; an earlier spec would otherwise be listed too            print(f"copy partition transforms: {ducklake_partition_transforms(wh.con, table=TABLE, current=True)}")            # one (partition value, files, rows) tuple per partition, in value order            files = ducklake_files_by_partition(wh.con, "lake", TABLE)            print(f"copy partition values: {[value for value, _, _ in files]}")            print(f"copy files per partition: {[count for _, count, _ in files]}")            print(f"copy rows per partition: {[int(rows) for _, _, rows in files]}")            changes = wh.con.execute("SELECT changes FROM ducklake_snapshots('lake') ORDER BY snapshot_id").fetchall()            # labels start at 1, so label N is the snapshot whose snapshot_id is N-1            for number, (change,) in enumerate(changes, start=1):                print(f"copy snapshot {number}: {', '.join(sorted(change))}")    except Exception as exc:        print(safe_error(exc))        raise SystemExit(1)if __name__ == "__main__":    main()
출력python iceberg-to-ducklake-copy.py
source rows: 1499
source snapshots: 3
source partition field: ts_hour
copy rows: 1499
copy partition transforms: ['hour']
copy partition values: ['0', '1', '2']
copy files per partition: [1, 1, 1]
copy rows per partition: [499, 500, 500]
copy snapshot 1: schemas_created
copy snapshot 2: schemas_created
copy snapshot 3: tables_created
copy snapshot 4: tables_altered
copy snapshot 5: tables_inserted_into

The helper scan_arrow reads the source at its current snapshot and returns every row of that snapshot as one Arrow table. The copy therefore holds the rows of one moment, the last commit that the scan saw. Writers that commit after the scan are not in the copy, and nothing in the copy tells you so. Commits that land after a copy's scan and never reach the copy are the cutover problem, which the production section returns to.

Two questions decide the copy: did the rows and layout arrive, and what history came with them? The output answers both.

The source comes first. It prints the row count, the number of snapshots and the partition fields. The source has 3 snapshots, one for each append, and one partition field, ts_hour, an hour transform of hour_utc.

The copy's row count comes next, and it is 1499. The row count is the same as the source's. It is a useful first check, but the digest section below explains why it is not enough on its own.

A copy can lose its layout without any error, so the order of the statements matters. The helper creates the copy as an empty table, runs ALTER TABLE ... SET PARTITIONED BY (hour(hour_utc)) on it, and only then inserts the rows. The DuckLake partitioning docs say the partition keys "only affect new data written to the table", so an ALTER after the rows are in place would leave them unpartitioned. The helper keeps only the spec still in force, and it lists one transform, hour. The list says what the copy was given. The files say what it holds: the copy writes [1, 1, 1] files, and the rows are divided between them as [499, 500, 500]. A copy made in one statement carries no partition spec, so its list is empty and its rows sit in unpartitioned files. The rows are all there either way, so the check has to look at the layout.

The partition list reads the catalog table ducklake_partition_column, as the DuckLake specification defines it, through the attached metadata database. No public function returns it at this pin.

Last, the snapshot list shows the copy's history. Each line gives a snapshot's number and the changes it made. The labels count every snapshot DuckLake records, setup included, as in chapter 2. The first two snapshots create the default schema and the wiki schema. The third creates the empty table, the fourth sets its partition spec, and the fifth writes the rows into the table that is already partitioned. The three hourly appends from the source do not appear. The copy's history starts at its own creation, so time travel on the copy reaches back only that far. To read the source as it was after the first hour, you still need the Iceberg table.

The attach helper also sets DATA_INLINING_ROW_LIMIT to 0, so the copied rows are written as Parquet files, and the counts above are of those files.

Working rule: Copy through Arrow with the target's own writer. Create the target empty, set its partition spec with an ALTER, and only then insert the rows. Print the target's partition list and its files per partition. Read the copy's snapshots as the copy's own history, and keep the source until the checks in the last two sections have passed.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Copy the Delta table into a pyiceberg table

마지막으로 변경된 판: 2026.11.7판

The Delta source is built the way a team's pipeline would build it: three appends with deltalake, one per hour. The three appends are versions 0, 1 and 2. The copy reads the current rows with read_delta and appends them to an Iceberg table made with the target schema:

delta-to-iceberg-copy.py Python 3.12.15 · deltalake 1.6.6 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 통과
"""Copy a Delta Lake table into Iceberg through Arrow, then compare the copy with its source.The point rests on the delta versions and iceberg snapshots lines, which show several commits becoming one,and on the two column listings, which show the names carried across."""from deltalake import DeltaTablefrom lib.lakehouse import (create_iceberg_table, new_warehouse, print_schema, read_delta, safe_error, scan_arrow,                           write_delta_hours)def main():    try:        with new_warehouse() as wh:            path = write_delta_hours(wh.root, range(3))            source = read_delta(path)            # Delta numbers its versions from 0, so the count is the last version plus one            print(f"delta versions: {DeltaTable(path).version() + 1}")            print(f"delta rows: {source.num_rows}")            print("delta columns (name, type, nullability):")            print_schema(source.schema)            table = create_iceberg_table(wh)            table.append(source)            print(f"iceberg snapshots: {len(table.metadata.snapshots)}")            print(f"iceberg rows: {scan_arrow(table).num_rows}")            print("iceberg columns (name, type, requirement):")            # sorted by name, so the two listings line up row for row            for field in sorted(table.schema().fields, key=lambda field: field.name):                # Iceberg calls a nullable field optional, so the listing says optional where Delta says nullable                requirement = "required" if field.required else "optional"                print(f"{field.name}\t{field.field_type}\t{requirement}")    except Exception as exc:        print(safe_error(exc))        raise SystemExit(1)if __name__ == "__main__":    main()
출력python delta-to-iceberg-copy.py
delta versions: 3
delta rows: 1499
delta columns (name, type, nullability):
domain_code	string	nullable
hour_utc	timestamp[us]	nullable
page_title	string	nullable
response_bytes	int64	nullable
views	int64	nullable
iceberg snapshots: 1
iceberg rows: 1499
iceberg columns (name, type, requirement):
domain_code	string	optional
hour_utc	timestamp	optional
page_title	string	optional
response_bytes	long	optional
views	long	optional

The copy has as many rows as the source but leaves its history behind. The Delta table has 3 versions and 1499 rows. The Iceberg table is built from one append of all of them, so it has 1 snapshot, the start of its own history, like the DuckLake copy. Its row count, 1499, is the same as the source's.

The rest of the output lists both schemas, one column per line. Read them side by side:

Column Delta Lake (Arrow type) Iceberg type
domain_code string string
hour_utc timestamp[us] timestamp
page_title string string
response_bytes int64 long
views int64 long

Names come across unchanged, because the copy takes them from the Arrow schema. The types map one to one. The only spelling change is int64 in Arrow, which Iceberg calls long. Both sides use microseconds for hour_utc, and the timestamp check below explains what happens when they do not.

pyiceberg is strict about names. It checks the Arrow schema against the table's schema before it writes. It stops with a mismatch error when a column name differs, or when a type cannot be promoted to the table's type. It accepts a type it can promote, such as int to long. That check is in the pinned library's _check_pyarrow_schema_compatible function in pyiceberg/io/pyarrow.py. The Delta table also cannot rename a column at this pin, as the rename section of the schema chapter showed. If the two sides disagree on a name, you change the target, not the source. pyiceberg matches the Arrow columns to the table by name, so the target's field IDs come from the schema you write. You write the target schema yourself, rather than letting the first batch decide it.

Working rule: Write the target schema yourself, with the types you want, and print both schemas after the copy, as the example does. Accept a near-equal type such as int64 to long only after you have checked it in the output. Do not accept a name that differs.

복사 전에 타임스탬프 정밀도를 확인한다

마지막으로 변경된 판: 2026.11.7판

타임스탬프는 형식마다 동작이 달라지는 부분이며, 때로는 아무 표시 없이 달라진다. Iceberg 사양은 나노초 타임스탬프를 버전 3의 타입으로 정의하므로, 버전 2 테이블에는 나노초를 위한 타입이 없다(Iceberg 사양, 버전 3 절). 이 예제의 테이블은 기본값인 버전 2이다. 이 시점의 pyiceberg는 버전 3 쓰기를 거부하므로, 나노초 값은 Iceberg가 아닌 다른 형식으로만 보존할 수 있다. 이 예제는 마이크로초 아래에서만 차이가 나는 두 값, 곧 1000000500나노초와 1000000999나노초를 각 형식에 기록한다.

timestamp-precision-check.py Python 3.12.15 · deltalake 1.6.6 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 통과
"""Write two timestamps that differ only below a microsecond to Iceberg, Delta Lake and DuckLake, and show what each kept.The point rests on the Iceberg error line and on the Delta and DuckLake read-back lines."""import pyarrow as pafrom deltalake import write_deltalakefrom pyiceberg.schema import Schemafrom pyiceberg.types import NestedField, TimestampTypefrom lib.lakehouse import copy_to_ducklake, new_warehouse, NAMESPACE, read_delta, safe_error, sql_rows# nanoseconds since 1970: one second plus 500 and 999 nanoseconds, so the two values differ below a microsecondNANOSECONDS = pa.table({"hour_utc": pa.array([1000000500, 1000000999], pa.timestamp("ns"))})def main():    try:        with new_warehouse() as wh:            # cast to int64 gives the integer behind each timestamp, so distinct values are counted exactly            print(f"written distinct values: {len(set(NANOSECONDS['hour_utc'].cast(pa.int64()).to_pylist()))}")            # TimestampType stores microseconds; a version 2 table has no nanosecond type to declare instead            table = wh.catalog.create_table(                f"{NAMESPACE}.precision",                schema=Schema(NestedField(1, "hour_utc", TimestampType(), required=False)),            )            try:                # this append raises, because the table cannot hold nanoseconds; the except prints the error                table.append(NANOSECONDS)            except Exception as exc:                print(f"iceberg append: {safe_error(exc, wh)}")            path = str(wh.root / "precision")            write_deltalake(path, NANOSECONDS, mode="overwrite")            # the cast reads the count in the column's unit, which Delta wrote as microseconds, so 1000000 is one second            kept = read_delta(path)["hour_utc"].cast(pa.int64()).to_pylist()            print(f"delta read back as microseconds: {kept}")            print(f"delta distinct values read back: {len(set(kept))}")            target = copy_to_ducklake(wh, NANOSECONDS)            # epoch_ns returns nanoseconds since 1970, so a value cut to microseconds would end in three zeros            rows = sql_rows(wh.con, f"SELECT epoch_ns(hour_utc) FROM {target}")            print(f"ducklake epoch nanoseconds read back: {[row[0] for row in rows]}")    except Exception as exc:        print(safe_error(exc))        raise SystemExit(1)if __name__ == "__main__":    main()
출력python timestamp-precision-check.py
written distinct values: 2
iceberg append: UnsupportedPyArrowTypeException: Column 'hour_utc' has an unsupported type: timestamp[ns]
delta read back as microseconds: [1000000, 1000000]
delta distinct values read back: 1
ducklake epoch nanoseconds read back: [1000000500, 1000000999]

첫 줄은 입력이며, 서로 다른 두 값이다. 이어서 각 형식이 제각기 응답한다.

Iceberg 추가는 실패한다. 오류는 UnsupportedPyArrowTypeException: Column 'hour_utc' has an unsupported type: timestamp[ns]이다. 오류에 열과 타입이 명시되므로 세 경우 가운데 이 실패가 가장 분명하며, 기본적으로는 아무것도 몰래 바뀌지 않는다. pyiceberg의 오류는 쓰기 때 나노초를 마이크로초로 내림하는 설정인 PYICEBERG_DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE을 알려 준다. 이 설정을 켜면 같은 추가가 성공하고, 값은 경고 로그 하나만 남긴 채 마이크로초 단위로 잘려 읽힌다. 이는 Delta가 수행하는 절단과 같으므로, 값을 자르기로 결정한 작업에만 설정하고 모든 작성자가 공유하는 환경에는 설정하지 않는다.

Delta 쓰기는 성공하며, 다시 읽은 결과는 [1000000, 1000000]이다. 두 값 모두 마이크로초 단위로 잘렸고, 서로 다른 두 값이 하나가 되었다. 쓰기는 오류를 내지 않았고 행 수도 같다. 값을 확인해야만 손실이 드러난다. 고유 값의 수는 2에서 1로 줄어든다.

DuckLake는 나노초를 보존한다. 이 테이블은 두 값을 기록한 그대로 저장하며, 예제는 이를 [1000000500, 1000000999]로 다시 읽는다.

pageviews 테이블은 시(hour) 단위를 기록하므로 이 문제에 이르지 않는다. 원시 요청 로그 테이블은 그렇지 않다. 이 테이블의 타임스탬프는 마이크로초보다 세밀하게 세는 시계에서 나오며, 복사본은 그 자릿수에 적용할 규칙을 골라야 한다. 답은 값에서만 드러나므로 첫 복사 전에 모든 타임스탬프 열에 대해 이 질문을 던져야 한다. 이 장의 복사본은 세 형식이 모두 보존하는 마이크로초 타임스탬프를 사용하므로 복사본이 일치한다. 실제 테이블은 원본에서 마이크로초 아래의 값을 가질 수 있으며, 복사는 첫 쓰기 전에 그 값을 어떻게 할지 정해야 한다.

작업 규칙: 첫 복사 전에 마이크로초 아래의 값으로 타임스탬프 정밀도를 확인한다. 규칙은 미리 정한다. 열을 마이크로초로 변환하고 변환이 바꾸는 값의 수를 세거나, 복사를 거부하거나, 나노초를 보존하는 형식으로 기록한다. 선택을 쓰기 라이브러리에 맡기지 않는다. 조용한 절단은 대응할 오류를 남기지 않기 때문이다.

정렬된 다이제스트로 각 복사본 검증하기

마지막으로 변경된 판: 2026.11.10판

행 수가 일치한다고 해서 값이 일치한다는 것이 증명되지는 않는다. 복사본이 행 수를 그대로 유지한 채 값 하나를 바꿀 수 있고, 행 수는 이를 보여 주지 못한다. 다이제스트는 보여 준다. 테이블의 다이제스트는 정렬된 행들의 해시다. digest_rows는 행을 정렬하고, 각 행을 한 줄의 텍스트로 쓴 다음 그 결과를 해시한다. 정렬 덕분에 다이제스트는 행이 반환되는 순서와 무관해지므로, 같은 행을 가진 두 복사본은 각 형식이 행을 어떤 순서로 돌려주든 같은 다이제스트를 얻는다. digest_rows는 두 복사본에서 실행되고, 조회수 하나를 일부러 바꾼 복사본에서도 실행된다.

verify-copies-by-digest.py Python 3.12.15 · deltalake 1.6.6 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 통과
"""Check each copy against its source with a sorted digest, and show that one changed value fails it.The point rests on the two iceberg to ducklake digest lines: the copy matches its source, and a copy with onechanged count does not."""from lib.lakehouse import (copy_to_ducklake, create_iceberg_table, digest_rows, new_warehouse, read_cut_hour,                           read_delta, safe_error, scan_arrow, sql_rows, write_delta_hours)def same(source, copy):    return digest_rows(source) == digest_rows(copy)def check_iceberg_to_ducklake():    with new_warehouse() as wh:        table = create_iceberg_table(wh)        for hour in range(3):            table.append(read_cut_hour(hour))        target = copy_to_ducklake(wh, scan_arrow(table))        source_rows = sql_rows(wh.con, "SELECT * FROM source", source=scan_arrow(table))        copy_rows = wh.con.execute(f"SELECT * FROM {target}").fetchall()        first = copy_rows[0]        # the copy's columns are hour_utc, domain_code, page_title, views, response_bytes, so index 3 is views        changed = [(*first[:3], first[3] + 1, first[4]), *copy_rows[1:]]        print(f"iceberg to ducklake rows: {len(source_rows)} and {len(copy_rows)}")        matches = same(source_rows, copy_rows)        # printed before the assert, so a failing run still shows the word        print(f"iceberg to ducklake digests: {'match' if matches else 'differ'}")        assert matches        still_matches = same(source_rows, changed)        print(f"iceberg to ducklake with one changed view count digests: {'match' if still_matches else 'differ'}")        # one changed count must change the digest        assert not still_matchesdef check_delta_to_iceberg():    with new_warehouse() as wh:        path = write_delta_hours(wh.root, range(3))        table = create_iceberg_table(wh)        table.append(read_delta(path))        source_rows = sql_rows(wh.con, "SELECT * FROM source", source=read_delta(path))        copy_rows = sql_rows(wh.con, "SELECT * FROM copy", copy=scan_arrow(table))        print(f"delta to iceberg rows: {len(source_rows)} and {len(copy_rows)}")        assert same(source_rows, copy_rows)def main():    try:        check_iceberg_to_ducklake()        check_delta_to_iceberg()    except Exception as exc:        print(safe_error(exc))        raise SystemExit(1)if __name__ == "__main__":    main()
출력python verify-copies-by-digest.py
iceberg to ducklake rows: 1499 and 1499
iceberg to ducklake digests: match
iceberg to ducklake with one changed view count digests: differ
delta to iceberg rows: 1499 and 1499

숫자 하나만 바뀌어도 다이제스트가 바뀌기에 충분하다. 따라서 다이제스트가 일치하면 그것은 증거이고, 다르면 중단해야 한다는 신호다. Iceberg에서 DuckLake로의 복사에서는 출력이 먼저 서로 같은 두 행 수를 출력하고, 이어서 다이제스트 match를 출력한다. Delta에서 Iceberg로의 복사에 같은 검사를 해도 일치한다. 조회수 하나를 바꾸면 다이제스트는 differ.

다이제스트는 데이터베이스가 반환하는 그대로의 값을 비교하며, 한계가 있다. 해시하기 전에 양쪽을 텍스트로 변환하면 서로 다른 타입의 두 값이 같은 텍스트를 만들 수 있다. 정수 1과 텍스트 '1'은 같은 텍스트다. 예제처럼 타입이 있는 값을 비교하고, Delta에서 Iceberg로의 복사에서 했던 것처럼 스키마를 출력한다. 다이제스트는 컬럼 이름이나 타입에 대해서도 아무것도 알려 주지 않는다. 행은 같지만 컬럼 이름이 다른 두 테이블은 같은 다이제스트를 가진다. 앞선 절의 스키마 목록은 이름을 검사하고 다이제스트는 값을 검사하므로, 복사본에는 둘 다 필요하다.

다이제스트는 파일의 해시가 아니다. 행은 타입이 있는 값을 기준으로 정렬되고, 각 행은 그 Python 표현으로 된 한 줄이 되며, 이어 붙인 텍스트가 SHA-256으로 해시된다. 값이 같은 두 행은 같은 줄을 만들며, 비교에 필요한 것이 바로 이것이다. 값 하나가 바뀌면 한 줄이 바뀌고, 따라서 다이제스트 전체가 바뀐다.

검사 시점도 정해야 한다. 다이제스트는 실행된 시점에 존재하던 행에 대해서만 참이다. 그 이후 원본에 쓰기가 일어나면 복사본은 최신이 아니게 되고, 쓰기 이전의 다이제스트는 더 이상 유효하지 않다. 검사는 원본에 대한 마지막 쓰기 이후, 그리고 누군가 복사본에서 읽기 시작하기 이전에 해야 한다.

작업 규칙: 원본에 대한 마지막 쓰기 이후에, 같은 컬럼을 대상으로, 타입이 있는 값으로 양쪽의 다이제스트를 계산한다. 행 수와 다이제스트를 함께 비교한다. 둘 다 일치하기 전에는 읽는 쪽을 옮기거나 원본을 삭제하지 않는다. 복사하는 동안 쓰기가 실행되었다면 복사와 다이제스트를 다시 수행한다.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

What goes wrong in production

마지막으로 변경된 판: 2026.11.7판

A failed migration usually passes the first check and fails later. These are the failures to look for, and how you would notice each.

  • A cutover that races a writer. A digest covers only the rows it read, as the digest section says. The first append after it makes the copy stale, and the digest does not warn you. Stop the writers, copy, digest and then move the readers. If the writers cannot stop, copy in windows and check the rows that arrived after the last window.
  • Deleting the source before the checks pass. The source holds the history that the copy does not. Once the source is gone, time travel into its snapshots and versions goes with it. Keep the source until the digests match and every reader has moved. Then decide how long to keep it, in writing.
  • A copy with the rows and without the layout. A copy made without the ALTER would hold every row and match the digest, with no partition set. The partition list and the files per partition are the checks that show the layout is missing, so print both after the copy.
  • Timestamps that change without an error. Delta Lake cut the nanosecond values to microseconds and raised no error. The row count stayed the same. A check on the values is the only thing that catches it, so a copy with sub-microsecond data needs that check before it runs.
  • Names and types that differ. pyiceberg refuses an append whose column names differ from the table's, or whose type it cannot promote, and that refusal is the clearest failure. The harder case is a column whose name matches and whose type it accepts, such as a long that was an int. Print both schemas and read them, rather than trusting that the append succeeded.
  • Size and memory. The helpers in this chapter read a whole table into memory before they write it. That suits 1499 rows. A table of billions of rows needs a copy that reads and writes in batches, and the digest must then be computed over the same batches on both sides, so it stays a check of the whole table.
  • Readers that write to both tables. During a copy, a job that writes to both tables by mistake makes the two tables differ, and the digest will show a mismatch that no single write explains. Name one writer per table in the runbook before the cutover starts.
  • A digest over text. A digest over casts can match when the types differ. The check in this chapter compares typed values, and the runbook should say so, so that a later edit to the check does not quietly drop the types.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Decisions this chapter made

마지막으로 변경된 판: 2026.11.7판
  • Copies go through Arrow, and each target is written by the library that owns its format. pyiceberg writes Iceberg, DuckDB's ducklake extension writes DuckLake, and deltalake writes Delta Lake. This book does not use DuckDB's iceberg or delta extensions, so no copy in it depends on them.
  • Delta tables are read through read_delta, for the reason in chapter 8. Every Delta read in this chapter goes through it.
  • A copy is one-time, starts a new history and is checked before anyone switches to it. The source stays in place until the digests match and the readers have moved.
  • The partition spec is set on the target by hand, with an ALTER before the rows are inserted, and printed. The copy does not bring it across.
  • Each copy example builds its own source from the same three hours of the cut. Every example runs alone, and each check reads only the rows that its own example wrote.
  • Checks run on typed values, after the last write, over the same columns. The row count and the digest are read together, and neither one is used alone to call a copy good.
  • The copies use microsecond timestamps, and a separate example checks sub-microsecond values. Each copy in this chapter keeps its microsecond values, so the digests match. The precision example shows what each format does with a value it cannot keep.
  • Metadata-only migration is not used here. pyiceberg's Table.add_files adds Parquet files that already exist to an Iceberg table as data files (Table.add_files in pyiceberg/table/__init__.py, pyiceberg 0.12.0). Its API docs, which are not pinned to that version, describe this as committing the files without rewriting them. That keeps the data files in place, which a copy does not. This chapter did not run it, and it copies rows instead.

이 판의 이 장

2026.11.10판예제 통과 2026년 11월 20이 장에서 4개 예제개 중 4개가 통과한다

영어판 2026.11.10판을 번역한 것이다.

이 절 인용

형식

각 형식은 이 번역이 따르는 영문 원서를 출처로 표기한다.

모든 형식은 이 판을 명시한다. 링크는 현재 판을 열며, 여기서 절의 제목은 본문이 마지막으로 바뀐 시점을 알려 준다. 접근 날짜와 검색 날짜는 이 자료를 여는 날짜다.

이 페이지의 내용

10장 중 9장: 테이블을 포맷 간에 옮기고 사본을 검증하기

  1. 복사가 보존하는 것과 잃는 것
  2. Copy the pageviews table into DuckLake
  3. Copy the Delta table into a pyiceberg table
  4. 복사 전에 타임스탬프 정밀도를 확인한다
  5. 정렬된 다이제스트로 각 복사본 검증하기
  6. What goes wrong in production
  7. Decisions this chapter made

맨 위로 돌아가기전체 장