ガバナンスをエンドツーエンドで実現する
読了まで約58 分分、8 節 節の 6 例 例。
この章を終えると、データプラットフォームの1つのテーブルを、コードによってエンドツーエンドでガバナンスできるようになる。そのテーブルを、所有チームと全列の分類を付けてカタログに登録し、それをコピーするパイプラインのリネージを記録し、どの行を誰が読めるかを決めてその決定をクエリに強制し、誰も分類していない列を追加したためにプルリクエストが失敗するところまで確認する。各部分は小さく、数秒で実行できる。後続の5つの章が、それぞれ1つずつを堅牢なものに仕上げる。
本書の対象読者は、すでにパイプラインやウェアハウスを構築していて、それらをガバナンスの効いたものにするよう求められているデータエンジニア、アナリティクスエンジニア、プラットフォームエンジニアである。SQL、Python、そして Parquet またはレイクハウスのテーブルについては既知とする。ガバナンスの理論は必要ない。必要なのは、実行でき、テストされ、ほかのコードと同じようにプルリクエストでレビューされるガバナンスである。本書を読み終えるころには、CI で実行されるコードによってデータプラットフォームをガバナンスできるようになる。
- すべてのテーブルに所有者があり、すべての列に分類があるカタログ
- 自動的に発見される個人データと、検出器が見逃したものの測定
- パイプラインから記録されるリネージ
- テスト済みのコードとして書かれ、行フィルタと列マスクとして強制されるアクセスポリシー
- データを実際に削除する保持と消去
- 監査証跡
- プルリクエストを失敗させるチェック
- AI を学習させたり AI の根拠となったりするデータに適用される同じルール
本書は一貫して1つの事例を扱う。社会人の学習者に専門職向けコースを販売するオンライン学習プラットフォームであり、以下ではこれを単にプラットフォームと呼ぶ。そのウェアハウスは Iceberg テーブルのカタログであり、各テーブルは運用するチームの名前空間に置かれている。学習者と講師は crm、コース、受講登録、学習イベント、コースレビューは learning、支払いは billing、サポートチケットは support にある。SQL パイプラインがこれらからレポーティング用のテーブルを作る。サポート担当者、講師、マーケティング、財務、データサイエンティスト、そしてプラットフォームのコースアシスタント(AI)は、いずれもこれらのテーブルから異なるものを必要とする。そのことが、このプラットフォームをガバナンスする価値のあるものにしている。
本書のすべての例が読むプラットフォームのデータは、生成されたものである。スクリプトが、フェイクデータ用ライブラリである Faker と固定のシードから一度だけデータを作り、そのファイルは、作成方法を記したデータカードとともにコミットされている。実在の人物はデータに含まれていない。メールアドレスは例示用に予約されたドメインのものなので誰にも届かず、IP アドレスはドキュメント用に予約された範囲のものなので特定の誰にも対応しない。電話番号、カード番号、IBAN は有効な形式のランダムな値であるため、稼働中の番号や口座と一致することがある。これらに電話をかけたり、メッセージを送ったり、課金したり、支払ったりしてはならない。データカードには、レガシー列にある完全なカード番号や、自由記述テキスト中の個人データなど、例が見つけられるように仕込んだものも列挙されている。
すべての例はオフラインで、1つの Python 3.12.15 プロセス内で、バージョンを固定したライブラリを使って実行される。Iceberg カタログとそのテーブルには PyIceberg 0.12.0、クエリには DuckDB 2.0.0、SQL の構文解析には sqlglot 30.33.0、リネージには openlineage-python 1.55.0、Open Policy Agent(OPA)のポリシー言語である Rego で書かれたポリシーには regopy 1.5.2 を使う。本番のプラットフォームが運用する6つのサービスはここでは動かさず、それぞれに代役を用意している。
- Trino:ツールがクエリを発行する SQL エンジン。代役は、本書の強制レイヤーの背後にある DuckDB であり、このレイヤーが各クエリを実行前に書き換える。
- OPA のサーバー:Trino がアクセス決定を問い合わせる相手である(Trino 484, OPA access control)。代役は regopy であり、同じ Rego を Python プロセス内で評価する。
- Spark、または大規模にパイプラインを実行するエンジン:代役は DuckDB であり、各パイプラインの SQL ファイルを実行する。
- カタログサーバーまたはクラウドカタログ:Iceberg REST カタログのような API でテーブルのメタデータを提供する(REST catalog spec, 1.12.0)。代役は PyIceberg の SQL カタログであり、各テーブルのメタデータの場所を記録する SQLite ファイルを基盤とし、メタデータはローカルディスク上でデータの隣に置かれる。
- リネージサーバー:OpenLineage イベントのファイル。本書のコードがこれを読み戻してグラフにする。
- CI サービスと git:2つのフォルダ。1つは main ブランチ用、もう1つはプルリクエストのブランチ用である。
ここで学ぶのは、これらのサービスが扱うオープン標準、すなわち Iceberg のテーブルメタデータ、OpenLineage、Rego である。ここで構築するものは、それらに対応づけられる。
このプラットフォームのガバナンスは、1枚のスプレッドシートから始まる。誰かが、すべての学習者の氏名、メールアドレス、電話番号、住所を保持する crm.learners の列を一覧にし、それぞれに分類を添えた。あるのはそれだけである。テーブルの所有者として名前が挙がっているチームはない。夜間のパイプラインが学習者の氏名とメールアドレスをマーケティング用のテーブルにコピーしているが、そのことを記録したものはない。サポート担当者はそれぞれ1つの地域を担当しているが、ウェアハウスへのクエリはすべての地域の学習者を返す。そして CRM チームは、まもなく列を1つ追加しようとしている。この章は、後続の章が構築するコードを可能な限り小さな規模で用いて、これらにそれぞれ答える。扱うのは、1つのテーブル、1つのパイプライン、1つのルール、1つのチェックである。4つのうちポリシーエンジンを使うのは1つだけであり、残りはメタデータ、リネージイベント、テストであって、同じリポジトリに置かれ、同じ方法でレビューされる。
第2章では、カタログをスキーマ変更に追従させ、ローカルモデルが下書きしたメタデータを測定する。第4章では、影響分析と分類の提案にリネージを使う。第5章ではテストを含むポリシー全体を書き、第6章ではそれをすべてのクエリに強制する。第10章では、第2章から第7章までのチェックを、所有者の承認と免除とともに CI で実行する。
この章が扱わないものは、4つの章が補う。第3章では、メタデータが見逃す個人データを見つける。第7章では、保持、同意、消去を扱う。第8章では監査証跡を記録し、第9章では、AI を学習させたり AI の根拠となったりするデータに同じルールを適用する。
共有モジュールは、多くの例が必要とするコードを収めた examples/lib/ 内のファイルであり、自由に開いて読んでよい。各節は、その節が使うモジュールを明示する。
テーブルを所有者と分類つきでカタログ化する
プラットフォームの最初の問題は、何の検査も受けない列の一覧であるスプレッドシートである。カタログはプラットフォームのテーブルとそのスキーマを一覧にしたものだが、ガバナンスにはデータ自体が持たない二つの事実が必要になる。各テーブルに責任を負うのは誰か、各列をどのように保護しなければならないか、の二つである。これらの事実をスプレッドシートやカタログサーバーのウェブページに置くと、レビューを経ずに変更され、内容が揃っているかどうかをテストで確かめることもできない。パイプラインの隣にあるリポジトリ内のファイルに置けば、あらゆる変更は誰かが承認する差分となり、テストでファイルとカタログを突き合わせることができる。
プラットフォームのファイルはgovernance/metadata.tomlである。このファイルは、各テーブルに所有者(owner)、ドメイン(domain、そのテーブルが属する事業上の領域)、説明を与え、各列に説明と分類(classification)を与える。カタログツールが所有者という語で指す内容は、第2章で比較するとおりツールごとに異なる。本書では一貫して一つの意味を使う。所有者とはテーブルに責任を負うチームであり、個人ではない。そうすれば、担当者が退職しても答えが失われない。分類は次の四つの値のいずれかで、保護の弱いものから強いものへ並べてある。
public:プラットフォームの外部の誰に見せてもよい。internal:プラットフォームの職員向けであり、それだけでは個人を識別しない。personal:個人を識別する、または個人について何かを伝える。sensitive:漏えいすれば誰かに直接の害を及ぼすデータ。カード番号などがこれにあたる。
列は、名前変更を経ても変わらないIcebergのフィールド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をカタログ化するのに、数行あれば足りる。検査は、そうして作られたものに対して実行される。
1"""Apply governance/metadata.toml to crm.learners: write its owner, domain and descriptions into the catalog, then run the2check on the catalog. The point rests on the last line, the problems the check finds once the file is applied."""3from collections import Counter45from lib import metadata6from lib.catalog import open_catalog78platform = open_catalog(["crm.learners"]) # a fresh Iceberg catalog holding the learners table9described = metadata.load()10learners = described["crm.learners"]11print("owner:", learners.owner)12print("domain:", learners.domain)13counts = Counter(column.classification for column in learners.columns.values())14print("columns classified personal:", counts["personal"])15print("personal columns:", ", ".join(c.name for c in learners.columns.values() if c.classification == "personal"))16print("columns classified internal:", counts["internal"])1718# Write the descriptions into the table's schema, where readers see them, and the owner and domain into its properties.19metadata.apply(platform, described)20table = platform.load_table("crm.learners")21print("table properties:", ", ".join(f"{key}={value}" for key, value in sorted(table.properties.items())))22print("email's description, in the Iceberg schema:", table.schema().find_field("email").doc)2324# The check: every table in the catalog has an owner, and every column one of the four classifications.25print("problems the check finds:", len(metadata.problems(platform, described)))
python catalog-the-learners.pyowner: 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件である。
スプレッドシートでは、この0件を得ることはできない。検査はカタログをたどるので、ファイルに記述のない列があれば問題として現れる。スプレッドシートの節でwork_emailがそうなるとおりである。
実践ルール: 所有者、ドメイン、説明、分類は、レビューを経る一つのファイルとしてリポジトリに置く。すべてのテーブルの所有者はチームとし、すべての列には閉じた一覧から選んだ分類を一つ付ける。説明はカタログにも書き込み、テーブルを読む誰もが目にできるようにする。カタログをファイルと照合するテストは、ファイルではなくカタログをたどって行う。編集がカタログのウェブページで行われる場合は、どちらか一方を正とし、もう一方をそこから生成する(第2章)。
この部分はまだ翻訳されていないため、英語で表示している。
Capture one pipeline's column lineage
The catalog says what a table holds. Lineage says where its data came from and where it went, and governance needs both: a table built from crm.learners may or may not copy its emails. OpenLineage, an open specification for lineage, describes a job, such as a pipeline, its runs, and the datasets each run reads and writes. A run reports itself in events: a START when it begins, then one that ends it, such as COMPLETE or FAIL. Events carry facets, OpenLineage's name for blocks of metadata attached to a run, a job or a dataset.
The column lineage facet, on the output of a COMPLETE event, lists for each output column the input columns it came from, each marked DIRECT or INDIRECT. DIRECT means the output is derived from the input. INDIRECT means the input shapes the output without being copied: the output column value is "impacted by the value of inputField column, but it's not derived from it" (column lineage facet). The columns of a join or a filter condition are INDIRECT inputs, since they decide which rows exist, and so are those of a grouping, sort, window or condition.
The client library computes no lineage of its own, as chapter 4 finds in its source: it sends what you give it. So the book's module lib.lineage does the work. It parses each pipeline's SQL with sqlglot and adds the INDIRECT inputs that sqlglot's own lineage leaves out. It also wraps lib.pipelines.run, which runs one of the platform's SQL pipelines on DuckDB and writes its output to the catalog: START before the run, COMPLETE with the lineage after it. The events go through OpenLineage's file transport to one file, with a fixed time and a run ID derived from that time and the job's name, so the example writes the same bytes every time.
The platform's marketing_audience pipeline is one create table ... as select ... statement that writes marketing.audience, the list of learners marketing may email. It selects each learner's ID, name, email and country from crm.learners, joins each learner to their favourite course category, ranked from their enrollments, and keeps the learners for whom l.marketing_consent and l.status = 'active' holds.
Run the pipeline with events on, read its lineage back from the events alone, and count the rows through lib.warehouse.connect, which gives DuckDB a view of each catalog table:
1"""Run the marketing_audience pipeline with OpenLineage events, then read its column lineage back from the events alone.2The point rests on the two INDIRECT lines: the filter and the joins decide which rows the audience table holds."""34from lib import lineage, metadata, warehouse5from lib.catalog import open_catalog6from lib.platform import scratch78platform = open_catalog(["crm.learners", "learning.courses", "learning.enrollments"])9events_file = scratch() / "events.jsonl" # the file that stands in for a lineage server: one event per line10lineage.run(platform, "marketing_audience", lineage.client(events_file))11events = lineage.read_events(events_file)1213print("events:", ", ".join(f"{e['eventType']} of {e['job']['name']}" for e in events))14print("the run read:", ", ".join(dataset["name"] for dataset in events[0]["inputs"])) # the START event lists the inputs15print("the run wrote:", events[-1]["outputs"][0]["name"]) # the last event, COMPLETE, names the output1617graph = lineage.graph(events) # built from the COMPLETE events' column lineage, not from the SQL18for column in ("full_name", "email"):19 inputs = [e for e in graph.edges if e.target == f"marketing.audience.{column}"]20 print(f"marketing.audience.{column} comes from:", ", ".join(f"{e.source} ({e.type} {e.subtype})" for e in inputs))21# The INDIRECT inputs of each kind: the inputs that decide which rows exist, not the ones copied into them.22for subtype in ("FILTER", "JOIN"):23 shaping = [e.source for e in graph.edges if e.target == "marketing.audience" and e.subtype == subtype]24 print(f"its rows are shaped by, INDIRECT {subtype}:", ", ".join(shaping))25duckdb = warehouse.connect(platform) # DuckDB on the catalog's tables, to count what the join dropped26# The learners the filter keeps, counted on crm.learners before any join drops one.27consenting = "select count(*) from crm.learners where marketing_consent and status = 'active'"28print("consenting, active learners in crm.learners:", f"{duckdb.sql(consenting).fetchall()[0][0]:,}") # one row, one column29print("rows in marketing.audience:", f"{duckdb.sql('select count(*) from marketing.audience').fetchall()[0][0]:,}") # one row, one column30# Every column a change to email can reach, at any depth of the graph.31reached = lineage.columns_reached(graph, lineage.downstream(graph, "crm.learners.email"))32print("a change to crm.learners.email reaches:", ", ".join(reached))3334# The catalog check, run on the catalog the pipeline wrote to.35for problem in metadata.problems(platform, metadata.load()):36 print("the catalog check finds:", problem)
python audience-pipeline-lineage.pyevents: 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
Read from the events alone, the lineage shows what the table's name leaves out. marketing.audience.email comes from crm.learners.email (DIRECT IDENTITY), and full_name from crm.learners.full_name (DIRECT IDENTITY), both unchanged copies of personal columns.
The filter and the joins decide which rows the table holds. The filter's inputs are crm.learners.marketing_consent, crm.learners.status, so every row says its learner consented. The joins' inputs are crm.learners.learner_id, learning.courses.category, learning.courses.course_id, learning.enrollments.course_id, learning.enrollments.learner_id. A learner with no enrollment has no favourite category, so the join to it drops them. crm.learners holds 1,861 consenting, active learners, and marketing.audience holds 1,829.
A change to crm.learners.email reaches only marketing.audience.email in this pipeline's table, so renaming the column, or changing its format, touches that column alone. With all four of the platform's pipelines sending lineage, chapter 4 finds that it reaches no other.
The catalog check, from the section before and run on the same catalog, finds marketing.audience: no metadata. The pipeline created a table nobody has described, and lineage changes what that gap means: from a table the platform knows nothing about to a copy of two personal columns, chosen by consent. Until someone describes it, the platform's access policy treats every column it can't find a classification for as sensitive. So anyone who reads the copy through the platform's enforcement layer, which a later section introduces, gets no value from it, as chapter 6's who-sees-what test shows.
Working rule: Emit lineage from the code that runs each job, never after it (chapter 4): a START event, then a COMPLETE or FAIL event, with the output's column lineage in the COMPLETE event, parsed from the job's SQL, and the inputs that join and filter rows as well as those that supply values. Read lineage back from the events, never from the SQL, so the graph shows what ran. Where a job isn't SQL that a parser can read, such as a Python script, write its lineage in the same code, and review the two together.
この部分はまだ翻訳されていないため、英語で表示している。
Enforce one access decision on a query
With the platform's tables cataloged, the next question is who may read what. Policy as code starts from OPA's premise that policy can be decoupled from the software it governs, so the people responsible for it can write, analyze, version and distribute it separately (OPA philosophy). A policy answers a request with a decision. The platform's policy answers with a document rather than a yes or no: whether to allow the read, the row filters that keep only the rows the user may see, and the column masks that change how a column is shown. The filters and masks are data, never SQL. A decision does nothing on its own. Something between the user and the engine has to apply it to every table a query reads.
Support agents on the platform each serve one region, americas, emea or apac, and need learners' contact details to answer tickets. The policy, governance/policies/access.rego, denies every request by default. It allows each group, the role a user holds in governance/users.toml, the tables its work needs, and reads the agent's region from the same file. This rule keeps an agent to their region:
row_filters contains {"column": "support_region", "equals": user.region} if {
"support" in groups
table in {"crm.learners", "support.tickets"}
}
lib.policy.decide evaluates the policy with regopy. lib.enforce holds the enforcement layer: its Enforcer asks the policy about every table a query reads, replaces each with a subquery that applies the decision, and runs the rewrite on DuckDB. lib.enforce.answer is the one function a service calls, and it returns rows, never the engine's connection.
agent-a05, a support agent in EMEA, asks for three columns of crm.learners and counts learners by region through the layer. Next, the emails are checked against the generated files that lib.platform.load reads:
1"""One access decision from the platform's Rego policy, and the same agent's query enforced in the layer. The point rests on2the emea line: the query names no region, yet only EMEA learners come back."""3import json45from lib import policy6from lib.catalog import open_catalog7from lib.enforce import Enforcer, answer8from lib.platform import load910# agent-a05, a support agent in EMEA, asks to read three columns of crm.learners.11request = policy.request("agent-a05", "crm.learners", ["learner_id", "email", "support_region"]) # the shape Trino's OPA plugin sends12decision = policy.decide(request)13assert decision["allow"] is True # support may read crm.learners; a policy that denies it fails this run14print("allow:", decision["allow"])15print("row filters:", json.dumps(decision["row_filters"]))16print("column masks:", json.dumps(decision["column_masks"]))17print("reasons:", "; ".join(decision["reasons"]))1819# The enforcement layer asks the policy about every table a query reads, then rewrites the query to apply the answer.20layer = Enforcer(open_catalog(["crm.learners"]))21query = "select support_region, count(*) as learners from crm.learners group by support_region order by support_region"22for region, learners in answer(layer, query, "agent-a05"): # the layer adds the agent's region to the query before the engine runs it23 print(f"learners agent-a05 sees in {region}:", f"{learners:,}")2425# Compare the emails the agent gets with the platform's data, without printing any.26stored = load("crm.learners") # the generated data, not the catalog's copy27emails = dict(zip(stored.column("learner_id").to_pylist(), stored.column("email").to_pylist()))28seen = answer(layer, "select learner_id, email from crm.learners", "agent-a05") # the agent's own query, with no region in it29print("emails agent-a05 sees, as stored:", f"{sum(email == emails[learner] for learner, email in seen):,} of {len(seen):,}")30print("learners in the platform's data:", f"{stored.num_rows:,}")
python support-region-enforced.pyallow: 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
The layer applied the region inside the query, so the agent's SQL didn't have to, and couldn't avoid it. The decision allows the read, with the row filter [{"column": "support_region", "equals": "emea"}] on the agent's own region and the column masks {}, since support is the group that needs contact details. Its reason is support may read crm.learners. The agent's query has no filter on region, yet it returns 1,581 learners, all in EMEA, of the 5,000 the platform holds. Their emails come back as stored, 1,581 of 1,581, because the decision masks nothing.
regopy is the Python binding of rego-cpp, Microsoft's C++ implementation of Rego, which supports Rego v1.18.1 as OPA defines it (rego-cpp README at v1.5.2). regopy differs from OPA in ways chapter 5 lists, so OPA stays the reference for anything in production. Chapter 6 shows why the layer replaces whole tables rather than masking columns where a query names them.
Working rule: Write access rules as one policy in the repository that denies by default and returns its decision as data: allow, row filters and column masks. Apply that decision in one layer that rewrites every query before the engine runs it, and give users that layer's answers, never the engine's connection. When an engine can ask the policy itself, as Trino can ask OPA, let the engine be that layer.
この部分はまだ翻訳されていないため、英語で表示している。
Fail the pull request that adds an unclassified column
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:
1"""The CRM team's pull request adds a column to crm.learners and no metadata for it; the coverage check runs on its branch and2on 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."""3from lib import ci45main = ci.checkout() # the main branch: the governance files and pipelines, and no migrations yet6branch = ci.checkout(main) # the pull request's branch, starting from main7# The pull request's only change: a migration that adds the column, with no metadata for it.8(branch / "migrations" / "0001-add-work-email.sql").write_text("alter table crm.learners add column work_email varchar;\n")9print("files the pull request changes:", ", ".join(ci.changed(main, branch)))1011# Build a scratch platform from each side, run the coverage check on both, and compare their findings by ID.12report = ci.run(main, branch, checks=["coverage"])13for line in ci.lines(report):14 if not line.startswith("change "): # schema changes are chapter 10's report15 print(line)16for line in ci.totals(report):17 if line.startswith(("findings the pull request introduces", "findings already on main", "exit code")):18 print(line)
python unclassified-column-fails.pyfiles 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.
本番環境で何が問題になるか
ガバナンスは、エラーを出さないまま二つの形で失敗する。これらは前述の各要素が対処するものであり、一つは誰も更新しないスプレッドシート、もう一つは他のツールに迂回されるポリシーである。前者がメタデータをコードとして扱う理由であり、後者が強制を一か所に置く理由である。
誰も更新しないガバナンス用スプレッドシート
本章が出発点としたスプレッドシートは、テーブルとカラムを列挙し、それぞれに分類を添えたものである。しかし、スプレッドシートが記述するのは、それが書かれた日のスキーマにすぎない。スキーマは固定されたままではない。合計で160,000を超えるリビジョンを持つ10個のオープンソースのデータベースアプリケーションを調べた研究は、主な知見の第一に、データベーススキーマはアプリケーションの寿命を通じて頻繁に進化することを挙げている(Qiu, Li and Su, 2013)。この研究が対象としたのはアプリケーションのデータベースであり、ウェアハウスではない。しかし、カラムを追加する変更は、そのたびにスプレッドシートに載っていないカラムを一つ増やすことになる。
プラットフォームのスプレッドシートを取り上げよう。これは crm.learners の一覧をCSVとして書き出したもので、1行が1カラムに対応する。そこへ、前述のプルリクエストにあるCRMチームのマイグレーションが work_email を追加する。このマイグレーションの後のカタログと比較して、スプレッドシートが見落としているものを調べる。
1"""A governance inventory kept as a spreadsheet, exported before a schema change, then compared with the catalog after it.2The point rests on the two work_email lines: the spreadsheet doesn't list the column, and the check finds it unclassified."""3import csv4import io56from lib import ci, metadata7from lib.catalog import open_catalog89platform = open_catalog(["crm.learners"])10described = metadata.load()1112# The inventory: one row per column of crm.learners, exported on the day someone was asked for one.13inventory = io.StringIO()14writer = csv.writer(inventory)15writer.writerow(["table", "column", "classification"])16for field in platform.load_table("crm.learners").schema().fields:17 # Metadata is keyed by Iceberg field ID, not by name, so the lookup survives a rename.18 writer.writerow(["crm.learners", field.name, described["crm.learners"].columns[field.field_id].classification])1920# Later, the CRM team's migration adds a column for learners' work email, applied as an Iceberg schema change.21ci.migrate(platform, "alter table crm.learners add column work_email varchar;")2223rows = list(csv.DictReader(io.StringIO(inventory.getvalue())))24print("columns the spreadsheet lists:", len(rows))25print("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 classified26live = [field.name for field in platform.load_table("crm.learners").schema().fields]27print("columns crm.learners has:", len(live))28print("columns the spreadsheet doesn't list:", ", ".join(sorted(set(live) - {row["column"] for row in rows})))29for problem in metadata.problems(platform, described):30 print("the check against the catalog finds:", problem)
python spreadsheet-misses-new-column.pycolumns 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ページ、データディクショナリのいずれであっても、手作業で保つメタデータのコピーは最初のスキーマ変更で古くなり、そのことを知らせるものは何もない。
実践ルール: ガバナンス用のメタデータを、何も検査しないドキュメントに保管してはならない。レビュー済みのファイルに保管し、プルリクエストのたびに、また定期的に、テストでそれを稼働中のカタログと比較する。スプレッドシートが必要な場合は、そのファイルから生成し、生成した日時をスプレッドシートに明記する。
一つのツールが強制し、別のツールが迂回するポリシー
ポリシーが保護するのは、それを強制するものを経由した読み取りだけである。Trino は行フィルタの取得先を指示されたときにだけ行フィルタを適用するため、opa.policy.row-filters-uri の設定がなければ行のフィルタリングはまったく行われない(Trino 484, OPA access control)。Iceberg の REST カタログ仕様は、バージョン 1.12.0 で、カタログがテーブルとともに読み取り制限を返せるようにしており、「読み取り制限に対応するリーダーは、返された制限を完全には適用できない場合、読み込んだテーブルに対するあらゆる読み取りを失敗させなければならない」と定めている(REST catalog spec, 1.12.0)。仕様は、委任されたアクセスについてはリーダーに X-Iceberg-Access-Delegation ヘッダというシグナルを与えているが、読み取り制限についてはシグナルを与えていない。したがって、カタログはどのリーダーが自身の制限を適用するのかを知ることができない。pyiceberg 0.12.0 の REST クライアントは、読み取り制限を一切読み取らない(source)。読み取り制限を返すカタログは、その制限を適用するエンジンにのみストレージへのアクセスを与えることを推奨する。
強制レイヤーは、agent-a05 が参照できる範囲を EMEA に限定している。しかし、このレイヤーには迂回経路がある。カタログへのアクセス権を持つものであれば、テーブルのファイルを読み取れるからである。テーブルをレイヤーの外から二通りの方法で読み取る。一つは、レイヤー自身が使う lib.warehouse.connect を通じた duckdb による読み取りであり、ノートブックが行う読み取りに当たる。もう一つは、カタログへのアクセス権を持つ任意のリーダーが行う読み取りに当たる、pyiceberg 自身のスキャンである。
1"""The same table, read three ways: through the enforcement layer, and around it with DuckDB and with PyIceberg. The point2rests on the two lines around the layer, which return every region where the layer returns only EMEA's."""3from collections import Counter45from lib import warehouse6from lib.catalog import open_catalog7from lib.enforce import Denied, Enforcer, answer89platform = open_catalog(["crm.learners"])10query = "select support_region, count(*) from crm.learners group by support_region order by support_region"111213def show(rows):14 return ", ".join(f"{region} {learners:,}" for region, learners in rows)151617layer = Enforcer(platform)18print("through the enforcement layer, as agent-a05:", show(answer(layer, query, "agent-a05")))1920# A notebook with DuckDB on the same catalog: the same SQL, and no policy in the way.21print("DuckDB on the same catalog:", show(warehouse.connect(platform).sql(query).fetchall()))2223# Any reader that holds the catalog's access, here PyIceberg's own scan: no SQL to rewrite at all.24scan = platform.load_table("crm.learners").scan(selected_fields=("support_region", "email")).to_arrow()25print("PyIceberg's scan of the table:", show(sorted(Counter(scan.column("support_region").to_pylist()).items())))26print("emails PyIceberg's scan returns:", f"{scan.num_rows - scan.column('email').null_count:,}") # rows whose email isn't null2728# lib.warehouse builds each table's view on a scan it registers under a name of its own. Through the layer, it's denied.29try:30 answer(layer, "select count(*) from scan_crm_learners", "agent-a05")31except Denied as reason:32 print("the layer, asked for the raw scan:", reason)
python read-around-the-layer.pythrough 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 を返す。書き換える SQL を持たない pyiceberg のスキャンは 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章が論じるとおり、その一箇所とは、ツールがクエリを発行する際に経由するエンジンである。また、ストレージの権限は強制の一部であるため、ファイルを読み取れるのは、そのエンジンと、テーブルを書き込むジョブだけにすべきである。
実践ルール: ポリシーを強制する場所を一つ選ぶ。それはすべてのツールがクエリを発行する際に経由するエンジンである。ストレージの認証情報は、そのエンジンとテーブルを書き込むジョブにのみ与え、人やノートブックには与えない。その場所では、カタログテーブルを経由せずにデータを読むクエリをすべて拒否する。テーブルを保護済みと数える前に、そのファイルを読めるものをすべて列挙する。ポリシーに問い合わせないリーダーは、読み取り元のテーブルと同様に出力がカタログ化され分類されているジョブでない限り、迂回とみなす。
この章で決めたこと
- ガバナンスは、1 つのリポジトリにある 4 種類のコードである。 メタデータファイル、各ジョブの系譜イベントを送るコード、Rego で書いたアクセスポリシー、そしてプルリクエストごとに実行されるチェックの 4 つである。このうちポリシーエンジンはアクセスポリシーだけである。
- すべてのテーブルには、個人ではなく担当チームが置かれる。 すべての列には、
public、internal、personal、sensitiveの 4 つの分類のいずれかが付けられる。これらはgovernance/metadata.tomlに Iceberg のフィールド ID をキーとして記録される。カタログがこのファイルと一致するかどうかは、カタログをたどって調べる。 - パイプラインは実行のたびに OpenLineage イベントを送る。 列の系譜は SQL を解析して得る。行を結合したり絞り込んだりする列も含む。
- アクセスの判定はデータとして扱う。 許可、行フィルタ、列マスクは、既定で拒否する 1 つのポリシーから導かれる。適用層がこれらをすべてのクエリに適用し、カタログのテーブルに対するものでない読み取りはすべて拒否する。
- メタデータが欠けているときは、拒否の側に倒れる(フェイルクローズ)。 アクセスポリシーは、誰も分類していない列を
sensitiveとして扱う。誰も説明していないテーブルは、誰かが説明するまで、すべてのレポートで指摘事項として残る。 - ガバナンスのジョブは、プルリクエストのたびに実行される。 そのプルリクエストが新たに持ち込む指摘事項があれば失敗とし、main に既にある指摘事項は担当者とともに報告する。
- すべてが 1 つのプロセスの中で、オフラインで動く。 動作に使うのは、この章の冒頭に挙げた代替物である。このように行うガバナンスは小さなルールの集まりであり、各ルールはデータが変わる場所で検査される。そのため、メタデータの欠落は、レポートで突然見つかる問題ではなく、失敗したチェックとして現れる。続く章では、プラットフォーム自身のテーブルを使って、各ルールを順に検証する。
この版における本章
第2026.11.31版2026年11月19日時点で例が通過この章の6 例件のうち6件が合格
英語版の書籍(版2026.11.31)から翻訳した。