端到端的資料治理

閱讀約需 58 分鐘 分鐘,8 節 中共有 6 個範例。

版次 2026.11.31 範例於 2026年11 月 19 通過測試 108 個範例中有 108 個通過 變更內容

由 AI 翻譯。經人工以英文驗證。 我們如何製作書籍

譯自英文書,版次 2026.11.31。 閱讀原文

讀完本章,你就能用程式碼,從頭到尾治理資料平台上的一張資料表。你會將它編入目錄,記錄擁有它的團隊,並為每個欄位標註分類;擷取複製這張表的管線的血緣;決定誰可以讀取哪些資料列,並在查詢上強制執行這項決定;還會看到一個 pull request 因為新增了無人分類的欄位而失敗。每個部分都很小,數秒內即可執行,之後的五章各自把其中一個部分做紮實。

本書寫給資料工程師、分析工程師與平台工程師:你們已經在建置管線與資料倉儲,並且被要求讓它們受到治理。你們熟悉 SQL、Python,以及 Parquet 或湖倉表格,不需要治理理論,需要的是能執行、有測試、並且像其他程式碼一樣在 pull request 中審查的治理。讀完本書,你就能用在 CI 中執行的程式碼治理一個資料平台:

  • 一個目錄,其中每張資料表都有負責人,每個欄位都有分類;
  • 自動找出個人資料,並量測偵測器漏掉了什麼;
  • 從管線擷取的血緣;
  • 以經過測試的程式碼撰寫的存取政策,並以資料列篩選與欄位遮罩的方式強制執行;
  • 真正移除資料的保存期限與刪除機制;
  • 稽核軌跡;
  • 會讓 pull request 失敗的檢查;
  • 同樣的規則,套用在訓練 AI 或作為 AI 依據(grounding)的資料上。

本書全程圍繞同一個案例:一個向成人學習者販售專業課程的線上學習平台,我們稱之為平台。它的資料倉儲是一份 Iceberg 表格的目錄,每張表都放在營運它的團隊的命名空間之下:學習者與講師在 crm 之下,課程、報名、學習事件與課程評價在 learning 之下,付款在 billing 之下,支援工單在 support 之下。SQL 管線以這些表建立報表用的資料表。支援人員、講師、行銷、財務、資料科學家,以及平台的課程助理(也就是它的 AI),各自需要這些表中的不同內容,這正是這個平台值得治理的原因。

平台的資料,也就是本書每個範例所讀取的資料,是生成的。一支腳本以固定的種子搭配 Faker(一個產生假資料的函式庫)一次產生,檔案連同一份說明製作方式的資料卡一併提交。資料中沒有任何真實的人。其電子郵件地址使用保留給範例的網域,因此寄不到任何人手上;其 IP 位址落在保留給文件的範圍內,因此不指向任何人。其電話號碼、信用卡號與 IBAN 是格式有效的隨機值,所以有可能恰好吻合一個正在使用的號碼或帳戶:切勿撥打、傳訊、扣款或付款。資料卡也列出為了讓範例找出而刻意埋入的內容,例如舊版欄位中的完整信用卡號,以及自由文字中的個人資料。

每個範例都離線執行,在單一個 Python 3.12.15 行程中,使用固定版本的函式庫:以 PyIceberg 0.12.0 處理 Iceberg 目錄及其資料表,以 DuckDB 2.0.0 執行查詢,以 sqlglot 30.33.0 剖析 SQL,以 openlineage-python 1.55.0 處理血緣,並以 regopy 1.5.2 處理以 Rego(Open Policy Agent(OPA)的政策語言)撰寫的政策。正式環境的平台會執行六種服務,這裡不執行,每一種都有替代品:

  • Trino,工具藉以查詢的 SQL 引擎:以 DuckDB 搭配本書的強制執行層取代,該層會在執行前改寫每個查詢。
  • OPA 的伺服器,Trino 向它詢問存取決策(Trino 484,OPA 存取控制):以 regopy 取代,在 Python 行程內評估同樣的 Rego。
  • Spark,或任何大規模執行管線的引擎:以 DuckDB 取代,執行每條管線的 SQL 檔案。
  • 目錄伺服器或雲端目錄,透過 API 提供資料表中繼資料,例如 Iceberg REST 目錄的 API(REST 目錄規格,1.12.0):以 PyIceberg 的 SQL 目錄取代,由一個記錄各表中繼資料位置的 SQLite 檔案支撐,中繼資料與資料一同放在本機磁碟上。
  • 血緣伺服器:以一個 OpenLineage 事件檔案取代,本書的程式碼會把它讀回成一張圖。
  • CI 服務與 git:兩個資料夾,一個代表主分支,一個代表 pull request 的分支。

你在這裡學到的,是這些服務所依循的開放標準:Iceberg 的資料表中繼資料、OpenLineage 與 Rego。你所建立的東西,都能對應到它們。

平台的治理從一份試算表開始。有人列出了 crm.learners 的欄位,這張表存放每位學習者的姓名、電子郵件、電話號碼與地址,每個欄位旁標有一個分類,僅此而已。沒有任何團隊被指定為這張表的負責人。一條夜間管線把學習者的姓名與電子郵件複製到行銷用的資料表,卻沒有任何紀錄顯示它這麼做。支援專員各自服務一個地區,但在資料倉儲上執行的查詢會回傳每個地區的學習者。而 CRM 團隊即將新增一個欄位。本章用後面各章所建立的程式碼,以最小而可行的規模逐一回應這些問題:一張表、一條管線、一條規則、一項檢查。四者之中,只有一項是政策引擎;其餘是中繼資料、血緣事件與一個測試,它們放在同一個儲存庫中,並以同樣的方式審查。

第 2 章讓目錄隨結構描述的變更保持同步,並量測本機模型所草擬的中繼資料。第 4 章把血緣用於影響分析,並用來提出分類建議。第 5 章寫出完整的政策及其測試,第 6 章則在每個查詢上強制執行它。第 10 章在 CI 中執行第 2 到第 7 章的檢查,並加入負責人的核准與豁免。

另有四章補上本章未涵蓋的部分。第 3 章找出中繼資料所遺漏的個人資料。第 7 章涵蓋保存期限、同意與刪除。第 8 章維護稽核軌跡,第 9 章則把同樣的規則套用在訓練或支撐 AI 的資料上。

共用模組是放在 examples/lib/ 中、收納許多範例所需程式碼的檔案,歡迎你自行開啟閱讀,每一節都會點出它所使用的模組。

為資料表建立目錄:登錄負責人與分類

最近一次變動於第 2026.11.31 版

平台的第一個問題出在它的試算表:那是一份沒有任何機制檢查的欄位清單。目錄(catalog)列出平台上的資料表及其結構(schema),而治理還需要資料本身不會帶有的兩項事實:每張資料表由誰負責,以及每個欄位必須如何保護。這些事實若存放在試算表或目錄伺服器的網頁上,修改時無須審核,也沒有任何測試能判斷內容是否完整。若改存放在儲存庫中、與資料管線並列的檔案裡,每次修改都是一份需要有人核准的差異(diff),測試也能拿這個檔案與目錄互相比對。

平台的檔案是 governance/metadata.toml。它替每張資料表指定一位負責人(owner)、一個領域(domain,即該資料表所屬的業務範疇)和一段描述,並替每個欄位指定一段描述和一個分類(classification)。各種目錄工具對「負責人」的定義不盡相同,第 2 章有比較;本書全程採用同一種定義:負責人是對該資料表負責的團隊,而不是個人,如此一來,即使有人離職,答案依然成立。分類共有四個值,保護程度由低到高如下:

  • public:可以向平台以外的任何人公開;
  • internal:供平台內部人員使用,本身無法識別出某個人;
  • personal:能識別出某個人,或透露與某人有關的資訊;
  • sensitive:一旦外洩便會直接傷害他人的資料,例如信用卡號。

欄位以其 Iceberg 的欄位 ID作為索引鍵,欄位 ID 在欄位更名後依然不變,旁邊再附上名稱供人閱讀:

[tables."crm.learners"]
owner = "team-crm"
domain = "crm"
description = "Every learner who has signed up, with their contact details and consents. One row per learner."

[tables."crm.learners".columns]
3 = { name = "email", classification = "personal", description = "The email the learner signs in with." }

本書共用的模組中,有三個負責實際工作。lib.catalog.open_catalog 會在暫存資料夾中建立一個全新的 Iceberg 目錄,收錄平台的各張資料表,範例結束時再將資料夾移除。lib.metadata 載入該檔案,以 apply 將內容寫入目錄,並以 problems 拿目錄與檔案比對;凡是沒有中繼資料或沒有負責人的資料表,以及沒有分類的欄位,都會被它回報出來。

載入這個檔案,並用它為 crm.learners 建立目錄,只需寥寥數行,檢查則針對建立出來的結果執行:

catalog-the-learners.py Python 3.12.15 · pyarrow 26.0.1 · pyiceberg 0.12.0 通過
"""Apply governance/metadata.toml to crm.learners: write its owner, domain and descriptions into the catalog, then run thecheck on the catalog. The point rests on the last line, the problems the check finds once the file is applied."""from collections import Counterfrom lib import metadatafrom lib.catalog import open_catalogplatform = open_catalog(["crm.learners"])            # a fresh Iceberg catalog holding the learners tabledescribed = metadata.load()learners = described["crm.learners"]print("owner:", learners.owner)print("domain:", learners.domain)counts = Counter(column.classification for column in learners.columns.values())print("columns classified personal:", counts["personal"])print("personal columns:", ", ".join(c.name for c in learners.columns.values() if c.classification == "personal"))print("columns classified internal:", counts["internal"])# Write the descriptions into the table's schema, where readers see them, and the owner and domain into its properties.metadata.apply(platform, described)table = platform.load_table("crm.learners")print("table properties:", ", ".join(f"{key}={value}" for key, value in sorted(table.properties.items())))print("email's description, in the Iceberg schema:", table.schema().find_field("email").doc)# The check: every table in the catalog has an owner, and every column one of the four classifications.print("problems the check finds:", len(metadata.problems(platform, described)))
輸出python catalog-the-learners.py
owner: team-crm
domain: crm
columns classified personal: 7
personal columns: full_name, email, phone, city, street_address, date_of_birth, notes
columns classified internal: 8
table properties: domain=crm, owner=team-crm
email's description, in the Iceberg schema: The email the learner signs in with.
problems the check finds: 0

檔案將 crm.learners 交給 team-crm 負責,領域為 crm,並將其中 7 個欄位歸類為個人(personal):full_name, email, phone, city, street_address, date_of_birth, notes。notes 也在其中,雖然從名稱看不出任何端倪,但支援人員會在這個欄位裡隨意輸入任何內容。其餘欄位則為 internal:學員的 ID、兩個日期、所在國家、兩個同意旗標、帳號狀態,以及支援區域。

套用該檔案時,也會把負責人與描述放到每位讀者都看得到的地方。資料表的屬性顯示為 domain=crm, owner=team-crm,而 email 的描述則寫在 Iceberg 的結構中,任何讀取這張資料表的人都能找到:「The email the learner signs in with.」分類則留在檔案裡,因為存取政策與各項檢查都是從那裡讀取的。執行 apply 之後,檢查找到的問題數為 0。

試算表給不出這個零。檢查是走訪目錄本身,所以檔案中沒有描述的欄位會被當成問題揭露出來,就像 work_email 在談試算表的那一節所發生的那樣。

**實用原則:**把負責人、領域、描述與分類集中在儲存庫中一個經過審核的檔案裡,每張資料表的負責人都是一個團隊,每個欄位都從一份封閉的清單中選定一個分類。把描述寫入目錄,讓每位讀取資料表的人都看得到,並以走訪目錄、而非走訪檔案的方式,拿目錄來測試這個檔案。若修改是在目錄的網頁上進行,就選定其中一方作為來源,再由它產生另一方(第 2 章)。

擷取單一管線的欄位血緣

最近一次變動於第 2026.11.31 版

資料目錄說明一張資料表裡有什麼。血緣則說明其資料從何而來、流向何處,治理需要兩者兼備:一張由 crm.learners 建立的資料表,可能複製了電子郵件,也可能沒有。OpenLineage 是一套開放的血緣規格,用來描述作業(例如一條管線)、作業的執行,以及每次執行所讀取與寫入的資料集。一次執行以事件回報自身狀態:開始時送出 START,結束時再送出一個終結事件,例如 COMPLETE 或 FAIL。事件帶有面向(facet),這是 OpenLineage 對附加在執行、作業或資料集上的中介資料區塊的稱呼。

COMPLETE 事件輸出上的欄位血緣面向,會為每個輸出欄位列出它所來自的輸入欄位,並各自標示為 DIRECT 或 INDIRECT。DIRECT 表示輸出衍生自輸入。INDIRECT 表示輸入影響了輸出,但並未被複製到輸出中:輸出欄位的值「受 inputField 欄位的值影響,但並非衍生自它」(欄位血緣面向)。連接(join)或篩選條件所用的欄位屬於 INDIRECT 輸入,因為它們決定哪些列會存在;分組、排序、視窗或條件式所用的欄位也是如此。

用戶端函式庫本身不計算任何血緣,這一點第 4 章已在其原始碼中查明:它只負責送出你交給它的內容。因此本書的模組 lib.lineage 負責這項工作。它以 sqlglot 剖析每條管線的 SQL,並補上 sqlglot 自身血緣功能所遺漏的 INDIRECT 輸入。它也包裝了 lib.pipelines.run,後者在 DuckDB 上執行平台的其中一條 SQL 管線,並將輸出寫入資料目錄:執行前送出 START,執行後送出附帶血緣的 COMPLETE。這些事件經由 OpenLineage 的檔案傳輸寫入同一個檔案,時間固定,執行 ID 則由該時間與作業名稱推導而得,因此本範例每次寫出的位元組都完全相同。

平台的 marketing_audience 管線是一條 create table ... as select ... 陳述式,寫出 marketing.audience,也就是行銷部門可以寄送電子郵件的學習者名單。它從 crm.learners 選出每位學習者的 ID、姓名、電子郵件與國家,把每位學習者與其最喜愛的課程類別連接起來(該類別依其選課紀錄排名而得),並保留使 l.marketing_consent and l.status = 'active' 成立的學習者。

開啟事件後執行這條管線,僅從事件讀回其血緣,並透過 lib.warehouse.connect 計算列數;該函式為 DuckDB 提供每張資料目錄資料表的檢視:

audience-pipeline-lineage.py Python 3.12.15 · duckdb 2.0.0 · openlineage-python 1.55.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · pyyaml 6.0.3 · sqlglot 30.33.0 通過
"""Run the marketing_audience pipeline with OpenLineage events, then read its column lineage back from the events alone.The point rests on the two INDIRECT lines: the filter and the joins decide which rows the audience table holds."""from lib import lineage, metadata, warehousefrom lib.catalog import open_catalogfrom lib.platform import scratchplatform = open_catalog(["crm.learners", "learning.courses", "learning.enrollments"])events_file = scratch() / "events.jsonl"                 # the file that stands in for a lineage server: one event per linelineage.run(platform, "marketing_audience", lineage.client(events_file))events = lineage.read_events(events_file)print("events:", ", ".join(f"{e['eventType']} of {e['job']['name']}" for e in events))print("the run read:", ", ".join(dataset["name"] for dataset in events[0]["inputs"]))  # the START event lists the inputsprint("the run wrote:", events[-1]["outputs"][0]["name"])                             # the last event, COMPLETE, names the outputgraph = lineage.graph(events)                            # built from the COMPLETE events' column lineage, not from the SQLfor column in ("full_name", "email"):    inputs = [e for e in graph.edges if e.target == f"marketing.audience.{column}"]    print(f"marketing.audience.{column} comes from:", ", ".join(f"{e.source} ({e.type} {e.subtype})" for e in inputs))# The INDIRECT inputs of each kind: the inputs that decide which rows exist, not the ones copied into them.for subtype in ("FILTER", "JOIN"):    shaping = [e.source for e in graph.edges if e.target == "marketing.audience" and e.subtype == subtype]    print(f"its rows are shaped by, INDIRECT {subtype}:", ", ".join(shaping))duckdb = warehouse.connect(platform)                     # DuckDB on the catalog's tables, to count what the join dropped# The learners the filter keeps, counted on crm.learners before any join drops one.consenting = "select count(*) from crm.learners where marketing_consent and status = 'active'"print("consenting, active learners in crm.learners:", f"{duckdb.sql(consenting).fetchall()[0][0]:,}")  # one row, one columnprint("rows in marketing.audience:", f"{duckdb.sql('select count(*) from marketing.audience').fetchall()[0][0]:,}")  # one row, one column# Every column a change to email can reach, at any depth of the graph.reached = lineage.columns_reached(graph, lineage.downstream(graph, "crm.learners.email"))print("a change to crm.learners.email reaches:", ", ".join(reached))# The catalog check, run on the catalog the pipeline wrote to.for problem in metadata.problems(platform, metadata.load()):    print("the catalog check finds:", problem)
輸出python audience-pipeline-lineage.py
events: START of marketing_audience, COMPLETE of marketing_audience
the run read: crm.learners, learning.courses, learning.enrollments
the run wrote: marketing.audience
marketing.audience.full_name comes from: crm.learners.full_name (DIRECT IDENTITY)
marketing.audience.email comes from: crm.learners.email (DIRECT IDENTITY)
its rows are shaped by, INDIRECT FILTER: crm.learners.marketing_consent, crm.learners.status
its rows are shaped by, INDIRECT JOIN: crm.learners.learner_id, learning.courses.category, learning.courses.course_id, learning.enrollments.course_id, learning.enrollments.learner_id
consenting, active learners in crm.learners: 1,861
rows in marketing.audience: 1,829
a change to crm.learners.email reaches: marketing.audience.email
the catalog check finds: marketing.audience: no metadata

僅從事件讀取,血緣顯示出資料表名稱所未說明的事。marketing.audience.email 來自 crm.learners.email (DIRECT IDENTITY),full_name 來自 crm.learners.full_name (DIRECT IDENTITY),兩者都是個人資料欄位的原樣複製。

篩選與連接決定這張資料表包含哪些列。篩選的輸入是 crm.learners.marketing_consent, crm.learners.status,所以每一列都表明其學習者已同意。連接的輸入是 crm.learners.learner_id, learning.courses.category, learning.courses.course_id, learning.enrollments.course_id, learning.enrollments.learner_id。沒有任何選課紀錄的學習者沒有最喜愛的類別,因此與它的連接會把這位學習者排除。crm.learners 中有 1,861 位同意且活躍的學習者,而 marketing.audience 中有 1,829 列。

對 crm.learners.email 的更動,在這條管線的資料表中只會影響到 marketing.audience.email,因此重新命名該欄位或變更其格式,只會動到那一個欄位。待平台的四條管線都送出血緣後,第 4 章會查明它不會影響其他任何欄位。

前一節的資料目錄檢查,在同一份資料目錄上執行,發現了 marketing.audience: no metadata。這條管線建立了一張無人描述過的資料表,而血緣改變了這個缺口的意義:從一張平台一無所知的資料表,變成兩個個人資料欄位的複本,並且依同意狀態篩選而成。在有人為它補上描述之前,平台的存取政策會把每個找不到分類的欄位視為 sensitive。因此,任何透過平台的強制執行層(後面的一節會介紹)讀取這份複本的人,都讀不到任何值,如第 6 章的誰能看到什麼測試所示。

**實用原則:**由執行每項作業的程式碼本身發出血緣,絕不事後補發(第 4 章):先送出 START 事件,再送出 COMPLETE 或 FAIL 事件,並在 COMPLETE 事件中附上輸出的欄位血緣,該血緣由作業的 SQL 剖析而得,其中除了提供值的輸入,也要包含連接與篩選列的輸入。血緣一律從事件讀回,絕不從 SQL 讀取,這樣圖譜呈現的才是實際執行過的內容。若作業不是剖析器能讀取的 SQL,例如 Python 腳本,就在同一份程式碼中寫下它的血緣,並將兩者一併審查。

對查詢強制執行單一存取決策

最近一次變動於第 2026.11.31 版

平台的資料表已完成編目,接下來的問題是誰可以讀取什麼。以程式碼管理政策(policy as code)的出發點是 OPA 的前提:政策可以與其所規範的軟體解耦,因此負責政策的人可以將它獨立撰寫、分析、版本控管與散布(OPA philosophy)。政策(policy)以一項決策(decision)回應請求。平台的政策回覆的是一份文件,而不是單純的是或否:是否允許讀取、只保留使用者可見資料列的列篩選條件(row filters),以及改變欄位呈現方式的欄位遮罩(column masks)。篩選條件與遮罩都是資料,而不是 SQL。決策本身不會產生任何作用,必須由位於使用者與引擎之間的某個環節,將它套用到查詢讀取的每一張資料表上。

平台上的客服人員各自服務一個地區,即 americas、emea 或 apac,並且需要學習者的聯絡資料才能回覆客服單。政策 governance/policies/access.rego 預設拒絕所有請求。它允許每個群組(即使用者在 governance/users.toml 中所擔任的角色)讀取其工作所需的資料表,並從同一個檔案讀取客服人員所屬的地區。下列規則將客服人員限制在自己的地區內:

row_filters contains {"column": "support_region", "equals": user.region} if {
	"support" in groups
	table in {"crm.learners", "support.tickets"}
}

lib.policy.decide 以 regopy 評估政策。lib.enforce 包含強制執行層(enforcement layer):其 Enforcer 針對查詢讀取的每一張資料表詢問政策,將每張資料表替換為套用決策的子查詢,並在 DuckDB 上執行改寫後的查詢。lib.enforce.answer 是服務唯一會呼叫的函式,它回傳資料列,而不會回傳引擎的連線。

agent-a05 是 EMEA 的客服人員,他透過這一層查詢 crm.learners 的三個欄位,並依地區統計學習者人數。接著,電子郵件會與 lib.platform.load 讀取的產生檔案進行核對:

support-region-enforced.py Python 3.12.15 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 · sqlglot 30.33.0 通過
"""One access decision from the platform's Rego policy, and the same agent's query enforced in the layer. The point rests onthe emea line: the query names no region, yet only EMEA learners come back."""import jsonfrom lib import policyfrom lib.catalog import open_catalogfrom lib.enforce import Enforcer, answerfrom lib.platform import load# agent-a05, a support agent in EMEA, asks to read three columns of crm.learners.request = policy.request("agent-a05", "crm.learners", ["learner_id", "email", "support_region"])  # the shape Trino's OPA plugin sendsdecision = policy.decide(request)assert decision["allow"] is True           # support may read crm.learners; a policy that denies it fails this runprint("allow:", decision["allow"])print("row filters:", json.dumps(decision["row_filters"]))print("column masks:", json.dumps(decision["column_masks"]))print("reasons:", "; ".join(decision["reasons"]))# The enforcement layer asks the policy about every table a query reads, then rewrites the query to apply the answer.layer = Enforcer(open_catalog(["crm.learners"]))query = "select support_region, count(*) as learners from crm.learners group by support_region order by support_region"for region, learners in answer(layer, query, "agent-a05"):   # the layer adds the agent's region to the query before the engine runs it    print(f"learners agent-a05 sees in {region}:", f"{learners:,}")# Compare the emails the agent gets with the platform's data, without printing any.stored = load("crm.learners")                                  # the generated data, not the catalog's copyemails = dict(zip(stored.column("learner_id").to_pylist(), stored.column("email").to_pylist()))seen = answer(layer, "select learner_id, email from crm.learners", "agent-a05")   # the agent's own query, with no region in itprint("emails agent-a05 sees, as stored:", f"{sum(email == emails[learner] for learner, email in seen):,} of {len(seen):,}")print("learners in the platform's data:", f"{stored.num_rows:,}")
輸出python support-region-enforced.py
allow: True
row filters: [{"column": "support_region", "equals": "emea"}]
column masks: {}
reasons: support may read crm.learners
learners agent-a05 sees in emea: 1,581
emails agent-a05 sees, as stored: 1,581 of 1,581
learners in the platform's data: 5,000

強制執行層在查詢內部套用了地區條件,因此客服人員的 SQL 不必自行處理,也無法繞過。這項決策允許讀取,並對客服人員自己的地區套用列篩選條件 [{"column": "support_region", "equals": "emea"}],以及欄位遮罩 {},因為客服是需要聯絡資料的群組。其理由為 support may read crm.learners。客服人員的查詢沒有對地區設定任何篩選,卻只回傳 1,581 位學習者,全部位於 EMEA,而平台資料中共有 5,000 位。他們的電子郵件以儲存時的原貌回傳,即 1,581 of 1,581,因為這項決策沒有遮罩任何內容。

regopy 是 rego-cpp 的 Python 綁定;rego-cpp 是 Microsoft 以 C++ 實作的 Rego,支援 OPA 所定義的 Rego v1.18.1(rego-cpp README at v1.5.2)。regopy 與 OPA 之間的差異列於第 5 章,因此在正式環境中的任何用途,仍應以 OPA 為準。第 6 章說明為何這一層要替換整張資料表,而不是在查詢指名欄位之處進行遮罩。

實用原則: 將存取規則寫成儲存庫中的單一政策,預設拒絕,並以資料形式回傳決策:允許與否、列篩選條件與欄位遮罩。在單一的一層中套用該決策,於引擎執行之前改寫每一個查詢,並且只讓使用者取得這一層的回答,而不是引擎的連線。當引擎本身能詢問政策時,例如 Trino 可以詢問 OPA,就讓引擎擔任這一層。

此部分尚未翻譯,因此以英文呈現。

Fail the pull request that adds an unclassified column

最近一次變動於第 2026.11.31 版

The catalog check proves the catalog complete on the day it runs, and the platform changes every week. A check that waits for someone to remember it gets run rarely and read less. Run on every pull request, where its exit code can fail it, the same check becomes a gate, and its findings appear where engineers already work. The authors of Tricorder, Google's platform for code analysis, found time and again that when developers have to open a dashboard or run a separate command line tool, their use of analysis drops off (Sadowski et al., 2015). That is one company's experience with code analysis, not data, but governance checks meet the same people. A gate also fails a pull request only for what it changes, so a finding already on main is reported with its owner and fails no pull request that leaves it as it is.

The book's module for this is lib.ci, the platform's governance job. A schema change on the platform is a migration, an alter table statement in a file in the branch's migrations/ folder. Each side of a pull request is a checkout in its own folder, one of main and one of the branch. For each side, lib.ci.run builds a scratch platform, a fresh catalog made the way the platform runs. It holds the source tables, the side's migrations, its metadata written into the catalog, and its pipelines. It runs the checks it's given on the branch's platform, runs them on main's alone to learn what is already there, and compares the findings by ID.

This section runs one check, coverage. The coverage check is the catalog check, lib.metadata.problems, run on the branch's platform, and for each column nobody classified it adds what a rule on column names suggests, from the rules chapter 3 writes.

The CRM team's pull request adds a column for learners' work email in one migration and forgets the column's metadata, so the coverage check has something to find:

unclassified-column-fails.py Python 3.12.15 · duckdb 2.0.0 · openlineage-python 1.55.0 · phonenumbers 9.0.43 · presidio-analyzer 2.2.366 · pyarrow 26.0.1 · pyiceberg 0.12.0 · pyyaml 6.0.3 · regopy 1.5.2 · sqlglot 30.33.0 · tldextract 5.4.0 通過
"""The CRM team's pull request adds a column to crm.learners and no metadata for it; the coverage check runs on its branch andon main. The point rests on the exit code line: the pull request's own finding fails the job, and the findings on main don't."""from lib import cimain = ci.checkout()                      # the main branch: the governance files and pipelines, and no migrations yetbranch = ci.checkout(main)                # the pull request's branch, starting from main# The pull request's only change: a migration that adds the column, with no metadata for it.(branch / "migrations" / "0001-add-work-email.sql").write_text("alter table crm.learners add column work_email varchar;\n")print("files the pull request changes:", ", ".join(ci.changed(main, branch)))# Build a scratch platform from each side, run the coverage check on both, and compare their findings by ID.report = ci.run(main, branch, checks=["coverage"])for line in ci.lines(report):    if not line.startswith("change "):    # schema changes are chapter 10's report        print(line)for line in ci.totals(report):    if line.startswith(("findings the pull request introduces", "findings already on main", "exit code")):        print(line)
輸出python unclassified-column-fails.py
files the pull request changes: migrations/0001-add-work-email.sql
coverage: failed, findings 3, new 1, on main 2, waived 0, 12 tables checked
coverage/ai.review_corpus: no metadata; on main, owner team-platform
coverage/crm.learners.work_email: not classified; its name suggests personal
coverage/marketing.audience: no metadata; on main, owner team-platform
job: failed
findings the pull request introduces: 1
findings already on main: 2
exit code: 1

The pull request fails on 1 finding of its own, the column nobody classified. The file it changes is migrations/0001-add-work-email.sql, and the coverage check reports failed, findings 3, new 1, on main 2, waived 0, 12 tables checked, which counts the platform's eight source tables and the four its pipelines write. The new finding is crm.learners.work_email, reported as not classified; its name suggests personal. The name rule matches email, which suggests the classification, and its ID, coverage/crm.learners.work_email, stays the same from run to run, so it can be discussed and counted.

The findings already on main were there before the pull request: coverage/ai.review_corpus, and coverage/marketing.audience, the table the lineage section found undescribed. Nobody owns either table, so the job names the platform team, the team answerable for tables without an owner. The job exits with code 1, so the pull request fails until the column has a classification, and the findings on main fail no pull request that leaves them as they are. Chapter 10's job runs the checks of chapters 2 to 7 on the same pull request, 11 of them.

Working rule: Run every governance check as one job on every pull request, required by branch protection, and fail it by exit code on any finding the pull request introduces. Report the findings already on the main branch with their owners, without failing the pull request for them. Put every finding in the pull request itself, under an ID that stays the same from run to run, with what to do about it. Run the same checks on a schedule against the production catalog too, for what changes outside pull requests.

正式環境中會出什麼問題

治理失敗時不會出現任何錯誤訊息,而且有兩種情形,前述各個部分都已提出對應的做法:一份沒有人更新的試算表,以及一項被其他工具繞過的政策。前者說明了中介資料為何要以程式碼管理,後者則說明了強制執行為何要集中在同一處。

沒有人更新的治理試算表

最近一次變動於第 2026.11.27 版

本章一開始採用的試算表列出了資料表與欄位,並在每個欄位旁標示分類,但試算表描述的只是撰寫當天的綱要(schema)。綱要不會一成不變。一項針對十個開源資料庫應用程式、共計超過 160,000 次修訂的研究,在其主要發現中首先指出,資料庫綱要在應用程式的生命週期中經常演進(Qiu, Li and Su, 2013)。該研究探討的是應用程式資料庫,而非資料倉儲,但每一次新增欄位的變更,都會多出一個試算表沒有列出的欄位。

以平台的試算表為例,它是 crm.learners 的清單,匯出為 CSV,每個欄位一列。接著,CRM 團隊在上述提取請求中的遷移新增了 work_email。將試算表與遷移之後的目錄(catalog)比對,就能找出它遺漏了什麼:

spreadsheet-misses-new-column.py Python 3.12.15 · duckdb 2.0.0 · openlineage-python 1.55.0 · phonenumbers 9.0.43 · presidio-analyzer 2.2.366 · pyarrow 26.0.1 · pyiceberg 0.12.0 · pyyaml 6.0.3 · regopy 1.5.2 · sqlglot 30.33.0 · tldextract 5.4.0 通過
"""A governance inventory kept as a spreadsheet, exported before a schema change, then compared with the catalog after it.The point rests on the two work_email lines: the spreadsheet doesn't list the column, and the check finds it unclassified."""import csvimport iofrom lib import ci, metadatafrom lib.catalog import open_catalogplatform = open_catalog(["crm.learners"])described = metadata.load()# The inventory: one row per column of crm.learners, exported on the day someone was asked for one.inventory = io.StringIO()writer = csv.writer(inventory)writer.writerow(["table", "column", "classification"])for field in platform.load_table("crm.learners").schema().fields:    # Metadata is keyed by Iceberg field ID, not by name, so the lookup survives a rename.    writer.writerow(["crm.learners", field.name, described["crm.learners"].columns[field.field_id].classification])# Later, the CRM team's migration adds a column for learners' work email, applied as an Iceberg schema change.ci.migrate(platform, "alter table crm.learners add column work_email varchar;")rows = list(csv.DictReader(io.StringIO(inventory.getvalue())))print("columns the spreadsheet lists:", len(rows))print("of them without a classification, by the spreadsheet:", sum(not row["classification"] for row in rows))  # a blank classification cell: a column the spreadsheet never classifiedlive = [field.name for field in platform.load_table("crm.learners").schema().fields]print("columns crm.learners has:", len(live))print("columns the spreadsheet doesn't list:", ", ".join(sorted(set(live) - {row["column"] for row in rows})))for problem in metadata.problems(platform, described):    print("the check against the catalog finds:", problem)
輸出python spreadsheet-misses-new-column.py
columns the spreadsheet lists: 15
of them without a classification, by the spreadsheet: 0
columns crm.learners has: 16
columns the spreadsheet doesn't list: work_email
the check against the catalog finds: crm.learners.work_email: not classified

這份試算表看起來完整,卻遺漏了一個欄位。依其自身的記載,它列出了 15 個欄位,其中 0 個沒有分類。該資料表實際有 16 個欄位,而試算表沒有列出的欄位是 work_email。試算表本身無法顯示這一點,因為沒有任何機制將它與目錄比對。lib.metadata.problems,也就是目錄檢查,會走訪目錄並發現 crm.learners.work_email: not classified,這與使 CRM 團隊的提取請求失敗的發現相同。依我們的經驗,以人工維護的中繼資料副本,無論是試算表、wiki 頁面或資料字典,在第一次綱要變更時就會過時,而且不會有任何提示。

實用原則: 切勿把治理中繼資料放在沒有任何檢查機制的文件中。應將它放在經過審查的檔案裡,並由測試在每次提取請求時與定期排程中,拿它和線上目錄比對。若有人需要試算表,就由該檔案產生,並在試算表上註明產生的時間。

一項政策,一個工具執行,另一個工具繞過

最近一次變動於第 2026.11.27 版

政策只保護經過其執行機制的讀取。Trino 只有在被告知從何處取得資料列篩選條件時,才會套用這些條件,因此若沒有 opa.policy.row-filters-uri 設定,它完全不會進行資料列篩選(Trino 484, OPA access control)。Iceberg 的 REST 目錄規格在 1.12.0 版中,允許目錄隨資料表一併回傳讀取限制,並指出「A reader that supports read restrictions must fail any read against the loaded table that cannot apply a returned restriction in full」(REST catalog spec, 1.12.0)。規格為讀取端提供了委派存取的訊號,也就是 X-Iceberg-Access-Delegation 標頭,但沒有提供讀取限制的訊號。因此目錄無法得知哪些讀取端會套用它的限制。PyIceberg 0.12.0 的 REST 用戶端完全不讀取這類限制(原始碼)。我們建議,回傳讀取限制的目錄,只應將儲存空間的存取權限提供給會套用這些限制的引擎。

執行層將 agent-a05 限制在 EMEA。然而這一層有繞過它的路徑,因為任何擁有該目錄存取權限的對象,都能讀取資料表的檔案。我們繞過這一層讀取資料表兩次:一次是透過 lib.warehouse.connect 使用 DuckDB,這是執行層本身使用的方式,筆記本也會這樣做;另一次是使用 PyIceberg 自己的掃描,任何持有該目錄存取權限的讀取端都能這樣做:

read-around-the-layer.py Python 3.12.15 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 · sqlglot 30.33.0 通過
"""The same table, read three ways: through the enforcement layer, and around it with DuckDB and with PyIceberg. The pointrests on the two lines around the layer, which return every region where the layer returns only EMEA's."""from collections import Counterfrom lib import warehousefrom lib.catalog import open_catalogfrom lib.enforce import Denied, Enforcer, answerplatform = open_catalog(["crm.learners"])query = "select support_region, count(*) from crm.learners group by support_region order by support_region"def show(rows):    return ", ".join(f"{region} {learners:,}" for region, learners in rows)layer = Enforcer(platform)print("through the enforcement layer, as agent-a05:", show(answer(layer, query, "agent-a05")))# A notebook with DuckDB on the same catalog: the same SQL, and no policy in the way.print("DuckDB on the same catalog:", show(warehouse.connect(platform).sql(query).fetchall()))# Any reader that holds the catalog's access, here PyIceberg's own scan: no SQL to rewrite at all.scan = platform.load_table("crm.learners").scan(selected_fields=("support_region", "email")).to_arrow()print("PyIceberg's scan of the table:", show(sorted(Counter(scan.column("support_region").to_pylist()).items())))print("emails PyIceberg's scan returns:", f"{scan.num_rows - scan.column('email').null_count:,}")  # rows whose email isn't null# lib.warehouse builds each table's view on a scan it registers under a name of its own. Through the layer, it's denied.try:    answer(layer, "select count(*) from scan_crm_learners", "agent-a05")except Denied as reason:    print("the layer, asked for the raw scan:", reason)
輸出python read-around-the-layer.py
through the enforcement layer, as agent-a05: emea 1,581
DuckDB on the same catalog: americas 2,276, apac 1,143, emea 1,581
PyIceberg's scan of the table: americas 2,276, apac 1,143, emea 1,581
emails PyIceberg's scan returns: 5,000
the layer, asked for the raw scan: not a table in the catalog: scan_crm_learners

位於執行層之外的讀取端會取得所有區域的資料,因為從未向政策查詢。透過執行層時,代理程式的查詢回傳 emea 1,581。在前面沒有執行層的 DuckDB 上執行相同的 SQL,則回傳 americas 2,276, apac 1,143, emea 1,581。PyIceberg 的掃描沒有 SQL 可供改寫,回傳 americas 2,276, apac 1,143, emea 1,581,其中有 5,000 個電子郵件地址。只要有第二個引擎、Spark 作業,或持有儲存空間憑證的指令碼,讀取受管控引擎所讀的檔案,正式環境中就會發生同樣的繞過。

lib.warehouse 以自己命名註冊的掃描來建立每個資料表的檢視,這張資料表的掃描名稱為 scan_crm_learners,所以執行層的連線同樣持有原始掃描。輸出的最後一行顯示,當查詢指名該掃描時執行層的回應:not a table in the catalog: scan_crm_learners。這正是第 6 章所採用的設計:只在一處執行政策,並拒絕其他一切讀取資料的行為,也就是任何不是目錄資料表的來源。在正式環境中,這個位置就是各工具用來查詢的引擎,如第 6 章所論述。而且既然儲存空間權限屬於執行機制的一部分,就只有該引擎與寫入資料表的作業應能讀取這些檔案。

實用原則: 選定一個執行政策的位置,也就是所有工具都經由它查詢的引擎,並且只把儲存空間憑證交給該引擎與寫入資料表的作業,絕不交給個人或筆記本。在該位置拒絕每一個不經由目錄資料表而讀取資料的查詢。在將某個資料表視為已受保護之前,先列出所有能讀取其檔案的對象,並將任何不向政策查詢的讀取端視為繞過,除非它是一項作業,且其輸出已如其所讀取的資料表一樣被編入目錄並分類。

本章的決定

最近一次變動於第 2026.11.27 版
  • 治理是同一個儲存庫中的四種程式碼: 一個中繼資料檔案、負責送出每項作業歷程事件的程式碼、以 Rego 撰寫的存取政策,以及在每個 pull request 上執行的檢查。其中只有一種是政策引擎。
  • 每張資料表都有負責的團隊, 而不是個人;每個欄位都屬於四種分類之一:public、internal、personal 或 sensitive。這些資訊存放在 governance/metadata.toml,以 Iceberg 欄位 ID 作為鍵,並透過走訪目錄(catalog)的方式,對照該檔案來測試目錄。
  • 每次管線執行都會送出 OpenLineage 事件, 其中的欄位歷程由該管線的 SQL 解析而來,包括用於連接與篩選資料列的欄位。
  • 存取決策就是資料: 允許、資料列篩選與欄位遮罩,皆出自一份預設拒絕的政策。強制執行層會將這些決策套用到每個查詢,並拒絕所有並非讀取目錄中資料表的讀取。
  • 中繼資料缺漏時一律拒絕: 存取政策會將無人分類的欄位視為 sensitive;無人描述的資料表,則會在每份報告中持續列為發現事項,直到有人為它撰寫描述。
  • 治理作業在每個 pull request 上執行, 對該 pull request 新增的發現事項判定失敗,並連同負責團隊回報 main 上既有的發現事項。
  • 一切都在單一程序中離線執行, 使用本章開頭所列的替代元件。以這種方式進行治理,是一組小型規則,每條規則都在資料變動之處檢查,因此中繼資料的缺口會以檢查失敗的形式出現,而不是在報告中成為意外。後續各章會依序在平台自身的資料表上測試每條規則。

本章,於本版次中

版次 2026.11.31範例於 2026年11 月 19 通過測試本章 6 個範例 個範例中有 6 個通過

譯自英文書,版次 2026.11.31。

引用本節

格式

各種格式皆引用英文原書,本譯本即依循該原書。

每種格式都會標示本版。其連結會開啟目前版次,節標題會說明該節內文最後一次變動的時間。存取日期與擷取日期即為你開啟此頁的當日。

本頁內容

第 1 章,共 10 章: 端到端的資料治理

  1. 為資料表建立目錄:登錄負責人與分類
  2. 擷取單一管線的欄位血緣
  3. 對查詢強制執行單一存取決策
  4. Fail the pull request that adds an unclassified column
  5. 正式環境中會出什麼問題
  6. 沒有人更新的治理試算表
  7. 一項政策,一個工具執行,另一個工具繞過
  8. 本章的決定

返回頂端所有章節