Agent Build智能体搭建 Tutor教程
Databricks, native buildDatabricks 原生构建

Build a production agent workflow on Databricks在 Databricks 上构建生产级智能体工作流

One enterprise workflow, built end to end on Databricks with GitLab as the source of truth: invoices, purchase orders and receipts in Unity Catalog; Lakeflow pipelines for the three-way match; AI Functions on the invoice PDFs; policy in AI Search; numbers through Genie and Unity Catalog functions; an agent that proposes, code that checks, a person who approves in a Databricks App; an evaluation gate in CI; and the levers to scale it from one business unit to the enterprise.一个企业级工作流,以 GitLab 作为唯一可信来源,在 Databricks 上从头到尾构建:发票、采购订单和收货记录放在 Unity Catalog 中;用 Lakeflow pipeline 做三单匹配;用 AI Functions 处理发票 PDF;政策放在 AI Search 中;通过 Genie 和 Unity Catalog 函数获取数字;智能体负责提议,代码负责检查,人在 Databricks App 中批准;CI 中有评估门槛;以及把它从一个业务单元扩展到整个企业的各种杠杆。

The workflow this page builds本页构建的工作流

The workflow: for each invoice that fails the three-way match (invoice against purchase order against receipt) or disagrees with its own PDF, propose one resolution (approve payment, hold, request a credit memo, or escalate) with cited policy and grounded figures, for a person to approve. The agent never pays, holds or changes anything itself. Every pattern here carries over to other decisions: claims, onboarding, reconciliations, contract review.工作流:对于每张未通过三单匹配(发票对采购订单对收货记录)或与自身 PDF 不一致的发票,提出一个处置建议(批准付款、暂缓、要求贷项通知单或升级处理),附带引用的政策和有据的数字,交由人批准。智能体自己从不付款、暂缓或修改任何东西。这里的每一种模式都可以迁移到其他决策场景:理赔、准入、对账、合同审查。

Not executed on Databricks未在 Databricks 上执行Nothing on Databricks was run for this page: there was no workspace. API names, SQL and YAML come from the vendor pages listed at the bottom, read in October 2026. Where a step depends on a detail those pages did not show, it says so in a 'Not confirmed' box. The parts of the kit that run without a workspace (contract validation, the proposal policy, the reviewer rules, the release gate, the scorers, the classifier gate, chunking, the Genie result comparison, batch and load-test logic) were executed here; the check results are below.本页涉及的 Databricks 操作一项都没有实际运行过:这里没有工作区。API 名称、SQL 和 YAML 来自页面底部列出的厂商文档,阅读时间为 2026 年 10 月。凡是某一步依赖了这些页面没有展示的细节,都会在“未确认”框中注明。工具包中无需工作区即可运行的部分(契约校验、提议政策、审核规则、发布门槛、scorer、分类器门槛、切块、Genie 结果比较、批处理和负载测试逻辑)已在这里执行过;检查结果见下方。

What was checked here在这里检查过的内容

Run by replicate/databricks/check.py on由 replicate/databricks/check.py 运行于 2026-10-08, Python 3.13.16.

23Python files compile个 Python 文件可编译
7YAML files parse个 YAML 文件可解析
3shell scripts pass bash -n个 shell 脚本通过 bash -n
7SQL files parsed by sqlglot (a typo net, not the engine)个 SQL 文件经 sqlglot 解析(用于发现笔误,并非真实引擎)
49/49portable tests passed项可移植测试通过
Test names测试名称
  • test_catches_contradictions (test_native.Contract.test_catches_contradictions)
  • test_level_three_needs_limit (test_native.Contract.test_level_three_needs_limit)
  • test_shipped_contract_is_valid (test_native.Contract.test_shipped_contract_is_valid)
  • test_catalog_substitution (test_native.Deploy.test_catalog_substitution)
  • test_render_env (test_native.Deploy.test_render_env)
  • test_split_statements (test_native.Deploy.test_split_statements)
  • test_baseline_list_is_reduced (test_native.Evals.test_baseline_list_is_reduced)
  • test_classifier_per_class_gate (test_native.Evals.test_classifier_per_class_gate)
  • test_gate_blocks (test_native.Evals.test_gate_blocks)
  • test_gate_passes (test_native.Evals.test_gate_passes)
  • test_regression_beyond_spread_only (test_native.Evals.test_regression_beyond_spread_only)
  • test_release_verifies_the_exact_commit (test_native.Evals.test_release_verifies_the_exact_commit)
  • test_spread (test_native.Evals.test_spread)
  • test_summary_and_safe_direction (test_native.Evals.test_summary_and_safe_direction)
  • test_chunks_carry_heading_path (test_native.Knowledge.test_chunks_carry_heading_path)
  • test_genie_result_compare (test_native.Knowledge.test_genie_result_compare)
  • test_action_not_allowed_for_type (test_native.Policy.test_action_not_allowed_for_type)
  • test_every_type_can_escalate (test_native.Policy.test_every_type_can_escalate)
  • test_good_proposal (test_native.Policy.test_good_proposal)
  • test_invented_figure_and_missing_citation (test_native.Policy.test_invented_figure_and_missing_citation)
  • test_low_confidence_must_escalate (test_native.Policy.test_low_confidence_must_escalate)
  • test_no_po_type_is_conservative (test_native.Policy.test_no_po_type_is_conservative)
  • The contract, the reviewer app's source of truth, and the database trigger use one number.
  • test_two_person_rule_is_strictly_above (test_native.Policy.test_two_person_rule_is_strictly_above)
  • test_closed_proposal (test_native.ReviewApp.test_closed_proposal)
  • test_exactly_the_threshold_needs_one_approver (test_native.ReviewApp.test_exactly_the_threshold_needs_one_approver)
  • test_label_only_when_final (test_native.ReviewApp.test_label_only_when_final)
  • test_model_text_is_escaped (test_native.ReviewApp.test_model_text_is_escaped)
  • test_origin_check_behind_proxy (test_native.ReviewApp.test_origin_check_behind_proxy)
  • test_rejection_needs_the_right_answer (test_native.ReviewApp.test_rejection_needs_the_right_answer)
  • test_scope_enforced (test_native.ReviewApp.test_scope_enforced)
  • test_small_amount_single_approval (test_native.ReviewApp.test_small_amount_single_approval)
  • test_two_person_flow (test_native.ReviewApp.test_two_person_flow)
  • test_backoff_grows_and_caps (test_native.Scale.test_backoff_grows_and_caps)
  • test_batch_selection_and_limit (test_native.Scale.test_batch_selection_and_limit)
  • test_changed_invoice_is_triaged_again_only_while_pending (test_native.Scale.test_changed_invoice_is_triaged_again_only_while_pending)
  • test_load_stats_and_knee (test_native.Scale.test_load_stats_and_knee)
  • test_vendored_pg_matches (test_native.Scale.test_vendored_pg_matches)
  • CI sets REQUIRE_PG=1, so a missing Postgres fails the pipeline instead of skipping the control tests.
  • test_agent_can_supersede_its_own_pending_proposal (test_review_queue_pg.ReviewQueueOnPostgres.test_agent_can_supersede_its_own_pending_proposal)
  • test_agent_cannot_approve_without_a_decision (test_review_queue_pg.ReviewQueueOnPostgres.test_agent_cannot_approve_without_a_decision)
  • test_agent_cannot_insert_a_decided_proposal (test_review_queue_pg.ReviewQueueOnPostgres.test_agent_cannot_insert_a_decided_proposal)
  • test_closed_proposal_cannot_change (test_review_queue_pg.ReviewQueueOnPostgres.test_closed_proposal_cannot_change)
  • test_decisions_are_append_only (test_review_queue_pg.ReviewQueueOnPostgres.test_decisions_are_append_only)
  • test_large_amount_needs_two_different_approvers (test_review_queue_pg.ReviewQueueOnPostgres.test_large_amount_needs_two_different_approvers)
  • test_nobody_can_rewrite_the_amount (test_review_queue_pg.ReviewQueueOnPostgres.test_nobody_can_rewrite_the_amount)
  • test_one_live_proposal_per_exception (test_review_queue_pg.ReviewQueueOnPostgres.test_one_live_proposal_per_exception)
  • test_small_amount_one_approver (test_review_queue_pg.ReviewQueueOnPostgres.test_small_amount_one_approver)
  • The attack: shadow decisions with a temporary table holding two fake approvals, then approve.

All files live in native/databricks/ in this repository and form a complete GitLab project: copy the folder as the root of a new repository, fill the placeholders marked <...>, and follow the steps in order, or in any order the dependency map allows.所有文件都在本仓库的 native/databricks/ 目录中,构成一个完整的 GitLab 项目:把这个目录复制为新仓库的根目录,填好标记为 <...> 的占位符,然后按顺序完成各步骤,或按依赖图允许的任意顺序进行。

Architecture架构

Six layers, twenty components. Click one to see its role and the steps that build it; the numbers on each component are those steps.六层、二十个组件。点击任意一个,查看它的作用以及构建它的步骤;每个组件上的数字就是这些步骤的编号。

Sources数据源
Lakehouse湖仓
AI and knowledgeAI 与知识
Decision决策
Quality质量
Delivery and operations交付与运维

Agent app智能体 App

Reads through MCP, returns one structured proposal; code checks it, retries once, writes to the queue or escalates.通过 MCP 读取,返回一个结构化提议;由代码检查,重试一次,然后写入队列或升级处理。

Built in steps构建于以下步骤14 · Build the agent: tools via MCP, structured output, code-side checks构建智能体:通过 MCP 使用工具、结构化输出、代码侧检查21 · Load test, find the knee, then scale the limit you hit做负载测试,找到拐点,再扩展你碰到的那个限制

The path every change takes每项改动都要走的路径

GitLab is the only road to production. Each arrow is enforced by something you can point to: a test, a protected branch, an evaluation gate, a federation policy, a named approver.GitLab 是通往生产的唯一道路。每个箭头都有可以指认的机制来强制执行:一项测试、一个受保护分支、一道评估门槛、一条联合策略、一位具名审批人。

  1. Merge request合并请求Contract check and tests, including the review queue on a real Postgres. No workspace access at all.契约检查和测试,包括在真实 Postgres 上运行的审核队列测试。完全不访问任何工作区。tests + approval测试 + 批准
  2. mainmainProtected branch. Its pipeline is the only one the staging principal trusts.受保护分支。预发服务主体只信任它的流水线。
  3. stagingstagingRender settings, deploy, apply SQL, restart apps, then the eval set three times and the Genie benchmark.写入设置、部署、执行 SQL、重启 App,然后跑三遍评估集和 Genie 基准测试。eval gate, per commit评估门槛(按提交)
  4. releasereleaseProtected branch, fast-forwarded to a gated main commit by a maintainer. The only ref the production principal trusts.受保护分支,由维护者 fast-forward 到 main 上一个通过门槛的提交。生产服务主体只信任这一个分支。same sha passed同一 sha 已通过
  5. productionproductionManual job in a protected environment, after verify_gate.在 verify_gate 之后,由受保护环境中的手动作业完成。named approver具名审批人
  6. baseline基线The release that reached production, kept as an artifact; the next gate compares against it.进入生产的版本,作为产出物保留;下一次门槛将与它比较。

Autonomy is earned, one level at a time自主权要一级一级地挣

This build runs at level 2. Moving one exception class to level 3 is a decision with evidence, written into contract.yml.本构建运行在第 2 级。把某一类异常提升到第 3 级,是一个基于证据、写入 contract.yml 的决定。

0
Report报告

The agent summarizes; people decide everything.智能体做汇总;所有事情由人决定。

To get here达到这一级需要: Read access and tracing.读取权限和追踪。

1
Recommend建议

The agent suggests an action; people may ignore it.智能体建议一个动作;人可以忽略它。

To get here达到这一级需要: An eval set and measured accuracy.一个评估集和实测准确率。

2
Act with approval经批准后执行this build本构建

The agent proposes; nothing happens until a person approves. This build.智能体提议;在人批准之前什么都不会发生。本构建处于这一级。

To get here达到这一级需要: Code-side checks, a review queue, a reviewer app, a release gate.代码侧检查、审核队列、审核 App、发布门槛。

3
Act within limits在限额内执行

For one class below an amount, the agent acts; people audit samples.对于某一类低于某个金额的事项,智能体直接执行;人做抽样审计。

To get here达到这一级需要: A quarter at level 2 with zero unsafe errors, approval at the human agreement rate, an owner's signature, a kill switch.在第 2 级运行一个季度、不安全错误为零、批准率达到人与人一致率、负责人签字、紧急停止开关。

4
Autonomous自主

The agent acts; people review outcomes.智能体执行;人审查结果。

To get here达到这一级需要: Rare for payment decisions. Regulators and auditors will ask who is accountable.付款决策中很少见。监管和审计人员会问谁来负责。

Build order and dependencies构建顺序与依赖

Click a step to see what it needs (green) and what it unlocks (purple). Steps in the same phase with no line between them can be built in either order.点击某一步,查看它需要什么(绿色)和它解锁什么(紫色)。同一阶段中彼此没有连线的步骤,先做哪个都可以。

1 Frame and govern定框架与治理
2 Data: ingest, quality, semantics数据:摄取、质量、语义
3 Document AI in the pipelinepipeline 中的文档 AI
4 Knowledge and tools知识与工具
5 The agent and the human in the loop智能体与人在回路
6 Quality: the release gate and production monitoring质量:发布门槛与生产监控
7 Ship: CI/CD, orchestration, observability上线:CI/CD、编排、可观测性
8 Scale and operate扩展与运维

1 Frame and govern定框架与治理

Decide what the workflow decides, who is accountable, where the code lives and who may touch which data, before any data moves. Most enterprise agent projects that stall do so here: no written decision, no owner, credentials pasted into CI, one catalog for everything. These four steps cost a few days and remove the reasons a security review or an auditor would stop you later.在任何数据流动之前,先确定这个工作流要做什么决策、由谁负责、代码放在哪里、谁可以碰哪些数据。大多数停滞的企业级智能体项目都卡在这里:没有书面的决策定义,没有负责人,凭证直接贴进 CI,所有东西都放在一个 catalog 里。这四步只花几天,却能消除日后安全审查或审计人员叫停你的那些理由。

01Write the workflow contract写下工作流契约
Builds构建内容contract.yml: the decision, the allowed actions, the autonomy level, and the release thresholds, in one reviewed file.contract.yml:决策、允许的动作、自主等级和发布门槛,都写在一个经过审查的文件里。
Do first先完成Nothing. This is a starting point.没有。这是一个起点。

Why this step, and why here为什么要做这一步,为什么在这里

An agent with no written decision grows until it does everything badly. The contract fixes four things everyone argues about later: what the agent decides (one resolution per match exception), what it may do (propose, never pay), how much autonomy it has (level 2: act with approval), and what number makes a release acceptable. Code reads its thresholds from this file, so a business owner changes a tolerance in one reviewed line, and CI rejects a contract that contradicts itself.没有书面决策定义的智能体会不断膨胀,直到什么都做不好。契约固定了日后大家都会争论的四件事:智能体决定什么(每个匹配异常给出一个处置建议),它可以做什么(只提议,绝不付款),它有多大的自主权(第 2 级:经批准后执行),以及什么样的数字才算可以发布。代码从这个文件读取门槛值,所以业务负责人只需在一行经过审查的配置里修改容差,而 CI 会拒绝自相矛盾的契约。

What it does它做什么

contract.yml names the workflow, its owner, the decision, four allowed actions, autonomy level 2, the write boundary (review_queue only), the two-person rule above 25,000, five success metrics, one catalog per environment, and retention. contract.py validates it: escalate must always be allowed, level 2 may write only to the queue, grounded figures must be 1.0, and each environment needs its own catalog.contract.yml 写明了工作流名称、负责人、决策内容、四个允许的动作、自主等级 2、写入边界(只能写 review_queue)、超过 25,000 的双人复核规则、五项成功指标、每个环境一个 catalog,以及保留期限。contract.py 负责校验:escalate 必须始终允许,第 2 级只能写入队列,有据数字比例必须为 1.0,每个环境必须有自己的 catalog。

How to do it怎么做

  1. Copy contract.yml and replace the decision, owner and thresholds with your workflow's. Keep the shape.复制 contract.yml,把决策、负责人和门槛值换成你自己工作流的内容。保持结构不变。
  2. Get the business owner to sign the success metrics in the merge request. A threshold nobody owns is moved the first time it fails.让业务负责人在合并请求里签字确认成功指标。没人负责的门槛,第一次没达标就会被挪走。
  3. Run `python3 src/common/contract.py`. CI runs the same check on every merge request.运行 `python3 src/common/contract.py`。CI 在每个合并请求上都会执行同样的检查。

Scripts脚本

contract.yml · yaml parses
# Step 1. The workflow contract. Written before any code, reviewed like code, checked in CI
# (src/common/contract.py validates it; tests/test_native.py runs that check).
# Every later step points back to a line in this file: if a step cannot, it is scope creep.
workflow: spend-exceptions
owner: finance-operations            # the business owner who signs off each autonomy change
decision: >
  For each invoice that fails the three-way match (invoice vs purchase order vs receipt),
  propose one resolution with its evidence, for a person to approve.
actions:                             # the only things the agent may propose
  - approve_payment
  - hold_payment
  - request_credit_memo
  - escalate
autonomy_level: 2                    # 0 report, 1 recommend, 2 act with approval, 3 act within limits, 4 autonomous
writes:
  allowed: [review_queue]            # the agent writes proposals, nothing else
  forbidden: [erp, payments, vendors]
human_in_the_loop:
  every_proposal: true
  second_approver_above: 25000       # two-person rule, in the invoice currency
success_metrics:                     # measured on the sealed eval set before every release
  action_accuracy_min: 0.85
  grounded_figures_min: 1.0          # every figure in a rationale must be in the evidence
  policy_cited_min: 0.95
  p95_latency_s_max: 30
  cost_per_exception_usd_max: 0.25
service_levels:
  backlog_max_days: 5                # an exception waits at most this long for a decision (alert in step 20)
data:
  catalog_per_env: {dev: fin_dev, stg: fin_stg, prd: fin_prd}
  sensitive_columns: [vendors.bank_account, vendors.tax_id]
  row_scope: business_unit           # a reviewer sees only their business units
retention_days:
  traces: 365
  proposals: 2555                    # seven years, the record-retention rule for payment decisions
src/common/contract.py · compiles
"""Load and validate contract.yml. Pure Python plus PyYAML; runs in CI before anything deploys.

The contract is the single place where scope, autonomy and release thresholds are written down.
Code reads its numbers from here: the eval gate (success_metrics), the agent (actions), the reviewer
app (second_approver_above). The database trigger repeats the threshold, and a test fails if it
differs. A threshold changes in one reviewed line, never in places that drift apart.
"""
from __future__ import annotations

import os
from pathlib import Path

LEVELS = {0: "report", 1: "recommend", 2: "act with approval", 3: "act within limits", 4: "autonomous"}
REQUIRED = ("workflow", "owner", "decision", "actions", "autonomy_level", "writes", "human_in_the_loop",
            "success_metrics", "data")
METRICS = ("action_accuracy_min", "grounded_figures_min", "policy_cited_min", "p95_latency_s_max",
           "cost_per_exception_usd_max")
DEFAULT_PATH = Path(__file__).resolve().parents[2] / "contract.yml"


def load(path: str | os.PathLike | None = None) -> dict:
    import yaml
    with open(path or DEFAULT_PATH) as f:
        return yaml.safe_load(f)


def problems(c: dict) -> list:
    """Every way the contract is incomplete or self-contradictory. Empty list means valid."""
    out = [f"missing key: {k}" for k in REQUIRED if k not in c]
    if out:
        return out
    if not isinstance(c["actions"], list) or len(c["actions"]) < 2:
        out.append("actions: list at least two, one of which must be a safe default such as escalate")
    elif "escalate" not in c["actions"]:
        out.append("actions: 'escalate' must be allowed, so the agent always has a safe answer")
    lvl = c["autonomy_level"]
    if lvl not in LEVELS:
        out.append(f"autonomy_level: {lvl} is not one of {sorted(LEVELS)}")
    hitl = c["human_in_the_loop"]
    if lvl is not None and lvl <= 2 and not hitl.get("every_proposal"):
        out.append("human_in_the_loop.every_proposal must be true at autonomy level 2 or below")
    if lvl == 3 and "act_limit" not in hitl:
        out.append("autonomy_level 3 needs human_in_the_loop.act_limit: the amount below which it may act alone")
    writes = c["writes"]
    overlap = set(writes.get("allowed", [])) & set(writes.get("forbidden", []))
    if overlap:
        out.append(f"writes: {sorted(overlap)} is both allowed and forbidden")
    if lvl is not None and lvl <= 2 and set(writes.get("allowed", [])) - {"review_queue"}:
        out.append("writes.allowed: at level 2 or below the agent may write only to review_queue")
    m = c["success_metrics"]
    for k in METRICS:
        if k not in m:
            out.append(f"success_metrics.{k} missing")
    for k in ("action_accuracy_min", "grounded_figures_min", "policy_cited_min"):
        if k in m and not (0 <= float(m[k]) <= 1):
            out.append(f"success_metrics.{k} must be between 0 and 1")
    if m.get("grounded_figures_min", 1.0) < 1.0:
        out.append("success_metrics.grounded_figures_min below 1.0 means shipping invented numbers on purpose")
    envs = c["data"].get("catalog_per_env", {})
    if set(envs) != {"dev", "stg", "prd"}:
        out.append("data.catalog_per_env needs exactly dev, stg and prd")
    elif len(set(envs.values())) != 3:
        out.append("data.catalog_per_env: each environment needs its own catalog")
    return out


if __name__ == "__main__":
    import sys
    p = problems(load(sys.argv[1] if len(sys.argv) > 1 else None))
    for line in p:
        print("CONTRACT:", line)
    print("contract ok" if not p else f"{len(p)} contract problems")
    sys.exit(1 if p else 0)

How to read the result如何解读结果

  • `contract ok` means the file is internally consistent. It does not mean the thresholds are right; only the eval in step 16 can say whether 0.85 is achievable.`contract ok` 说明文件内部一致。它不代表门槛值是对的;只有第 16 步的评估才能告诉你 0.85 是否可以达到。
  • A problem line such as `grounded_figures_min below 1.0 means shipping invented numbers on purpose` is the check refusing a business decision nobody should make by accident.像 `grounded_figures_min below 1.0 means shipping invented numbers on purpose` 这样的提示,是检查在拒绝一个任何人都不该无意中做出的业务决定。

Troubleshooting排障

You see现象Why原因Do this处理
The owner will not commit to numbers负责人不肯给出具体数字There is no baseline yet, so any number feels like a guess.还没有基线,所以任何数字都像是猜测。Measure today's manual process first: how long a reviewer takes per exception and how often a second reviewer disagrees. Set the agent's bar relative to that.先测量当前人工流程:审核人员处理一个异常要多久,第二位审核人员不同意的频率有多高。以此为参照设定智能体的标准。
Scope keeps growing in review评审中范围不断扩大Every stakeholder adds an action.每个干系人都要加一个动作。New actions go into the next contract version with their own eval cases. A step that cannot point to a line of this file is out of scope.新动作放进下一个契约版本,并配上各自的评估用例。指不到本文件某一行的步骤就属于范围之外。

How this scales如何扩展

  • One contract per workflow. When you add a second workflow (say, vendor onboarding), it gets its own contract, catalog schemas and eval set, and reuses the platform pieces. That is how ten workflows stay governable.每个工作流一份契约。增加第二个工作流(比如供应商准入)时,它有自己的契约、catalog schema 和评估集,并复用平台层的组件。这样十个工作流也能保持可治理。
Architecture review: questions you will be asked架构评审:你会被问到的问题
Why level 2 and not straight to automation, if the agent is accurate?如果智能体足够准确,为什么停在第 2 级,而不直接自动化?

Accuracy on last quarter is not accountability today. Level 2 produces the evidence for level 3: thousands of human decisions labelled against the agent's proposals, with the unsafe-error count at zero. The contract lets you raise the level per exception type later, for example price variances under 500, without touching the rest.上个季度的准确率不等于今天的责任归属。第 2 级为第 3 级积累证据:成千上万条针对智能体提议的人工决定标签,并且不安全错误数为零。契约允许你日后按异常类型逐步提高等级,例如低于 500 的价格差异,而不影响其他部分。

Who signs off a change to a threshold?谁来批准门槛值的修改?

The owner named in the contract, in the merge request that changes it. GitLab CODEOWNERS on contract.yml makes that approval mandatory.契约中指定的负责人,在修改它的合并请求中批准。对 contract.yml 设置 GitLab CODEOWNERS,可以让这项批准成为强制要求。

Done when完成标准contract.yml is merged with the owner's approval, and the validator passes in CI.contract.yml 已在负责人批准后合并,校验器在 CI 中通过。
02Set up the GitLab repository and the bundle建立 GitLab 仓库和 bundle
Builds构建内容One repository with the bundle (databricks.yml), pipelines, src, app, agent, tests, and the CI file.一个仓库,包含 bundle(databricks.yml)、pipeline、src、app、agent、测试和 CI 文件。

Why this step, and why here为什么要做这一步,为什么在这里

If a resource can be created by clicking, it will be, and staging will drift from production in ways nobody can list. A bundle declares every Databricks resource of the workflow (pipeline, jobs, apps, experiment) in git, with one target per environment. GitLab then becomes the only way anything reaches staging or production, and the merge request history is the change log an auditor asks for.只要资源能通过点击创建,就一定会有人去点,预发环境就会以没人说得清的方式偏离生产环境。bundle 在 git 中声明工作流的每个 Databricks 资源(pipeline、job、app、实验),每个环境一个 target。这样 GitLab 就成为任何东西进入预发或生产的唯一途径,而合并请求的历史就是审计人员要的变更日志。

What it does它做什么

databricks.yml declares the bundle, its variables, a workload tag applied to every resource (for cost attribution), and three targets: dev in development mode, stg and prd in production mode with a service principal as run_as. resources/*.yml hold the pipeline, jobs and apps.databricks.yml 声明 bundle、它的变量、一个应用到所有资源上的 workload 标签(用于成本归属),以及三个 target:开发模式的 dev,和以服务主体为 run_as、处于生产模式的 stg 与 prd。resources/*.yml 存放 pipeline、job 和 app。

How to do it怎么做

  1. Create the GitLab project. Protect `main` (merge only through merge requests, at least one approval, pipeline must pass) and `release` (maintainers only, fast-forward from main).创建 GitLab 项目。保护 `main` 分支(只能通过合并请求合入,至少一人批准,流水线必须通过)和 `release` 分支(只有维护者,从 main fast-forward)。
  2. Add CODEOWNERS: finance operations owns contract.yml and the policy tables; the platform team owns databricks.yml and .gitlab-ci.yml.添加 CODEOWNERS:财务运营负责 contract.yml 和政策表;平台团队负责 databricks.yml 和 .gitlab-ci.yml。
  3. Copy the native/databricks/ tree as the repository root. Fill the workspace hosts and warehouse ids per target.把 native/databricks/ 目录树复制为仓库根目录。按 target 填写工作区地址和 warehouse id。
  4. For interactive development, connect the repository as a Git folder in the dev workspace (Settings > Linked accounts, a GitLab project access token). People work in Git folders; only CI deploys.为了交互式开发,把仓库作为 Git 文件夹接入开发工作区(Settings > Linked accounts,使用 GitLab 项目访问令牌)。人在 Git 文件夹里工作;只有 CI 负责部署。
  5. `databricks bundle validate -t dev` from your laptop to see the resolved configuration.在你的笔记本上执行 `databricks bundle validate -t dev`,查看解析后的配置。

Scripts脚本

databricks.yml · yaml parses
# Step 2 and 18. The bundle: every Databricks resource of this workflow, declared in git.
# Declarative Automation Bundles (formerly Databricks Asset Bundles). CI deploys it; people do not
# click resources into existence in staging or production.
bundle:
  name: spend-exceptions

include:
  - resources/*.yml

variables:
  catalog:
    description: Unity Catalog catalog for this environment (contract.yml data.catalog_per_env)
  warehouse_id:
    description: Serverless SQL warehouse used by apps, tools and jobs
  agent_model:
    default: databricks-claude-sonnet-5-5
  experiment_path:
    default: /Shared/spend-exceptions/traces
  genie_space_id:
    description: Genie space over gold (step 11); created in the UI, then referenced here
  agent_url:
    description: URL of the deployed agent app in this target (set after the first deploy)
    default: ""
  pg_endpoint:
    description: Lakebase endpoint name (Lakebase console, Connect)
  pg_host:
    description: Lakebase host for this environment
  jobs_client_id:
    description: >
      Application id of the principal jobs run as (also its Postgres role name). In stg and prd this is a
      runtime principal of its own (spend-jobs-stg, spend-jobs-prd), NOT the CI deployer: the deployer can
      change code, the runtime principal can read data and call the agent, and no one identity does both.
  agent_client_id:
    description: >
      Application id of the agent app's own service principal (Apps creates it on the first deploy; read it
      with `databricks apps get agent-spend-exceptions`). Batch sends only the units this principal can read.
    default: ""

presets:
  tags:
    workload: spend-exceptions          # billing attribution: system.billing.usage custom_tags
    owner: finance-operations

targets:
  dev:                                  # deployed by each engineer from their own login, never by CI
    mode: development                   # names get a [dev <user>] prefix, schedules start paused
    default: true
    workspace:
      host: https://<dev-workspace-host>
    variables:
      catalog: fin_dev
      warehouse_id: <dev-warehouse-id>
      genie_space_id: <dev-genie-space-id>
      pg_endpoint: <dev-lakebase-endpoint>
      pg_host: <dev-lakebase-host>
      jobs_client_id: <your-own-user-name>   # dev jobs run as you; there is no run_as in dev
      # Apps keep their default permissions in dev: you deployed them, so you can use them.

  stg:
    mode: production
    workspace:
      host: https://<stg-workspace-host>
      root_path: /Workspace/Shared/.bundle/${bundle.name}/stg
    run_as:                             # the runtime principal; the CI deployer needs the Service Principal User role on it
      service_principal_name: <jobs-stg-application-id>
    variables:
      catalog: fin_stg
      warehouse_id: <stg-warehouse-id>
      genie_space_id: <stg-genie-space-id>
      pg_endpoint: <stg-lakebase-endpoint>
      pg_host: <stg-lakebase-host>
      jobs_client_id: <jobs-stg-application-id>
      agent_client_id: <stg-agent-app-client-id>
      agent_url: <stg-agent-app-url>
    resources:
      apps:
        agent:
          permissions:                  # only the jobs runtime principal may call the agent (batch, eval)
            - level: CAN_USE
              service_principal_name: ${var.jobs_client_id}

  prd:
    mode: production
    workspace:
      host: https://<prd-workspace-host>
      root_path: /Workspace/Shared/.bundle/${bundle.name}/prd
    run_as:                             # the runtime principal; the CI deployer needs the Service Principal User role on it
      service_principal_name: <jobs-prd-application-id>
    variables:
      catalog: fin_prd
      warehouse_id: <prd-warehouse-id>
      genie_space_id: <prd-genie-space-id>
      pg_endpoint: <prd-lakebase-endpoint>
      pg_host: <prd-lakebase-host>
      jobs_client_id: <jobs-prd-application-id>
      agent_client_id: <prd-agent-app-client-id>
      agent_url: <prd-agent-app-url>
    resources:
      apps:
        agent:
          permissions:                  # only the jobs runtime principal may call the agent (batch, eval)
            - level: CAN_USE
              service_principal_name: ${var.jobs_client_id}
.gitignore · read only
# Build output: copied in by CI and setup/04_dev_deploy.sh before each deploy
agent/src/
agent/contract.yml
app/contract.yml
*.orig
.databricks/
text
spend-exceptions/                     the repository root
  contract.yml                        step 1, owned by finance operations
  databricks.yml  resources/*.yml     the bundle: every Databricks resource
  .gitlab-ci.yml                      step 18
  setup/                              one-time account and workspace setup (steps 3, 4, 14)
  pipelines/                          Lakeflow pipeline sources (steps 5, 6, 8, 9)
  semantics/                          metric view and comments (step 7)
  src/                                tools, agent, evals, monitoring, ops, scale (steps 10 to 21)
  app/                                the reviewer app (step 15)
  agent/                              the vendored agent app template (step 14)
  tests/                              unit tests CI runs on every merge request
  CODEOWNERS

How to read the result如何解读结果

  • `bundle validate` prints the resolved configuration. Check that every resource name in dev starts with your `[dev <user>]` prefix: that is development mode keeping your experiments apart from everyone else's.`bundle validate` 会打印解析后的配置。检查 dev 中每个资源名是否都带有 `[dev <user>]` 前缀:这是开发模式在把你的实验与其他人的隔开。
  • In stg and prd there is no prefix and run_as is a service principal. If validate complains about run_as, production mode is doing its job: production resources must not run as a person.在 stg 和 prd 中没有前缀,run_as 是服务主体。如果 validate 对 run_as 报错,说明生产模式在尽职:生产资源不能以个人身份运行。

Troubleshooting排障

You see现象Why原因Do this处理
validate: workspace host is requiredvalidate 报:需要工作区地址The target has no host and the CLI has no default profile.target 里没有 host,CLI 也没有默认 profile。Set workspace.host per target, as in the file. CI sets DATABRICKS_HOST per GitLab environment.像文件里那样为每个 target 设置 workspace.host。CI 会按 GitLab 环境设置 DATABRICKS_HOST。
Two engineers overwrite each other's dev deployment两位工程师互相覆盖了对方的开发部署Both deployed the dev target as the same identity, for example a shared service principal.两人都以同一个身份部署了 dev target,例如共用了一个服务主体。Deploy dev from your own login: development mode prefixes every resource with your name. CI never deploys dev.用你自己的登录身份部署 dev:开发模式会给每个资源加上你的名字作为前缀。CI 从不部署 dev。

How this scales如何扩展

  • One repository per workflow keeps ownership and release cadence separate. Shared code (the Lakebase pool, the guard) moves to an internal Python package with its own version once a third workflow needs it.每个工作流一个仓库,使所有权和发布节奏彼此独立。当第三个工作流也需要共享代码(Lakebase 连接池、护栏)时,把它们移到一个有独立版本的内部 Python 包中。
  • Workspaces: start with one workspace per environment. Unity Catalog is account-level, so the same catalog names can be bound to the right workspaces as you add regions or business units.工作区:先从每个环境一个工作区开始。Unity Catalog 是账号级的,所以在增加区域或业务单元时,可以把同样的 catalog 名绑定到相应的工作区。
Architecture review: questions you will be asked架构评审:你会被问到的问题
Why not let analysts edit jobs in the UI and export them later?为什么不让分析师在界面里编辑 job,之后再导出?

Because "later" is when production and git disagree and nobody knows which is right. `databricks bundle generate` exists to import an existing resource once; after that, git is the source and the UI is read-only for production.因为“之后”恰恰是生产环境和 git 不一致、没人知道哪个才对的时候。`databricks bundle generate` 用来一次性导入已有资源;在那之后,git 是唯一来源,生产环境的界面只读。

Done when完成标准The repository exists with protected main and CODEOWNERS, and `bundle validate` passes for all three targets.仓库已建立,main 受保护且配置了 CODEOWNERS,三个 target 的 `bundle validate` 都能通过。
Not confirmed on a vendor page未在厂商页面上确认The `presets.tags` key that applies a tag to every resource is from the bundle settings reference as recalled, not a page read for this guide; confirm it with `bundle validate` output.把标签应用到所有资源上的 `presets.tags` 键来自对 bundle 设置参考的记忆,并非本指南阅读过的页面;请用 `bundle validate` 的输出确认。
03Environments and identities: OIDC federation from GitLab环境与身份:来自 GitLab 的 OIDC 联合
Builds构建内容Three catalogs; two CI service principals (staging trusts main, production trusts release); no CI access to dev at all.三个 catalog;两个 CI 服务主体(预发信任 main,生产信任 release);CI 对 dev 完全没有访问权限。

Why this step, and why here为什么要做这一步,为什么在这里

A long-lived token in a CI variable is the most common way a data platform is breached: anyone who can edit the pipeline file can print it. With workload identity federation, GitLab signs a short-lived token for each job, and Databricks exchanges it only if the token's subject matches the policy exactly. The subject names the project and the branch, so the policy is the boundary: the staging principal trusts main, the production principal trusts release (a protected branch only maintainers can merge to), and a merge-request pipeline gets no Databricks access at all. That holds even if someone edits .gitlab-ci.yml in their branch, because Databricks, not the CI file, decides.CI 变量里的长期令牌是数据平台被攻破最常见的方式:任何能编辑流水线文件的人都能把它打印出来。使用工作负载身份联合时,GitLab 为每个作业签发一个短期令牌,只有当令牌的 subject 与策略完全一致时,Databricks 才会兑换它。subject 写明了项目和分支,所以策略本身就是边界:预发服务主体信任 main,生产服务主体信任 release(只有维护者能合入的受保护分支),而合并请求流水线完全无法访问 Databricks。即使有人在自己的分支里修改了 .gitlab-ci.yml,这一点依然成立,因为做决定的是 Databricks,而不是 CI 文件。

What it does它做什么

Creates a staging and a production service principal in the account, each with a federation policy: issuer = your GitLab instance, audience = your Databricks account id, subject = project_path:<group>/<project>:ref_type:branch:ref:main (staging) or :ref:release (production). Prints each principal's application id, the non-secret DATABRICKS_CLIENT_ID for that GitLab environment. Dev has no CI principal: engineers deploy dev from their own login, in development mode. It also creates a runtime principal per environment (spend-jobs-stg, spend-jobs-prd) with no federation policy at all: jobs and the pipeline run as it (bundle run_as), so the identity that can change code is never the identity that reads finance data, and nothing outside Databricks can become the runtime principal.在账号中创建预发和生产两个服务主体,每个都带有联合策略:issuer = 你的 GitLab 实例,audience = 你的 Databricks 账号 id,subject = project_path:<group>/<project>:ref_type:branch:ref:main(预发)或 :ref:release(生产)。脚本会打印每个主体的 application id,即对应 GitLab 环境里非机密的 DATABRICKS_CLIENT_ID。dev 没有 CI 服务主体:工程师用自己的登录身份、以开发模式部署 dev。脚本还为每个环境创建一个运行时服务主体(spend-jobs-stg、spend-jobs-prd),它完全没有联合策略:job 和 pipeline 以它的身份运行(bundle run_as),所以能改代码的身份永远不是读取财务数据的身份,Databricks 之外也没有任何东西能变成这个运行时主体。

How to do it怎么做

  1. Log in to the account console with the CLI (`databricks auth login --host <accounts host> --account-id <id> --profile acct`).用 CLI 登录账号控制台(`databricks auth login --host <accounts host> --account-id <id> --profile acct`)。
  2. Run the script with PROJECT_PATH (group/project) and ACCOUNT_ID. For self-managed GitLab, set GITLAB_ISSUER to its URL.带上 PROJECT_PATH(group/project)和 ACCOUNT_ID 运行脚本。若是自建 GitLab,把 GITLAB_ISSUER 设为它的 URL。
  3. In GitLab: protect main and release (merge by maintainers only), set the merge method to fast-forward so release receives main's gated commit unchanged, and create environments staging and production with the variables the script lists. Protect production with required approvers.在 GitLab 中:保护 main 和 release(只有维护者能合入),把合并方式设为 fast-forward,使 release 原样接收 main 上通过门槛的提交;创建 staging 和 production 两个环境,并设置脚本列出的变量。为 production 设置保护和必需的审批人。
  4. Add each principal to its workspace with only the permissions its deploys need.把每个服务主体加入对应的工作区,只给它部署所需的权限。
  5. Prove the boundary: a job with `databricks current-user me` on a feature branch must fail for both principals, on main must succeed only for staging, and on release only for production.验证边界:在功能分支上运行 `databricks current-user me` 的作业,对两个主体都必须失败;在 main 上只有预发能成功;在 release 上只有生产能成功。

Scripts脚本

setup/01_envs_federation.sh · bash -n passes
#!/usr/bin/env bash
# Step 3. Environments and identities: a CI service principal for staging and one for production, each
# with a GitLab OIDC federation policy, so CI deploys with no stored secret. Dev has no CI principal:
# merge-request pipelines get no Databricks access at all, and engineers deploy dev from their own login.
#
# Run once, as an account admin, from a laptop logged in to the ACCOUNT console:
#   databricks auth login --host https://accounts.cloud.databricks.com --account-id <account-id> --profile acct
#
# Why two principals, and two branches: the subject is matched exactly against GitLab's sub claim
# (project_path:<group>/<project>:ref_type:branch:ref:<branch>). Staging trusts main; production trusts
# release, a protected branch only maintainers can merge to. A pipeline on any other ref cannot mint a
# token for either, whatever .gitlab-ci.yml says. The boundary is enforced by Databricks, not by the CI file.
set -euo pipefail

ACCOUNT_PROFILE="${ACCOUNT_PROFILE:-acct}"
GITLAB_ISSUER="${GITLAB_ISSUER:-https://gitlab.com}"       # self-managed: https://gitlab.example.com
PROJECT_PATH="${PROJECT_PATH:?set PROJECT_PATH=my-group/spend-exceptions}"
ACCOUNT_ID="${ACCOUNT_ID:?set ACCOUNT_ID to your Databricks account id (the token audience)}"

# GitLab's sub claim: project_path:<group>/<project>:ref_type:<branch|tag>:ref:<name>
declare -A SUBJECT=(
  [stg]="project_path:${PROJECT_PATH}:ref_type:branch:ref:main"
  [prd]="project_path:${PROJECT_PATH}:ref_type:branch:ref:release"
)

for env in stg prd; do
  name="spend-exceptions-ci-${env}"
  echo "== ${env}: service principal ${name}"
  sp_json=$(databricks account service-principals create --display-name "$name" --profile "$ACCOUNT_PROFILE" -o json)
  sp_id=$(printf '%s' "$sp_json" | python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])')
  app_id=$(printf '%s' "$sp_json" | python3 -c 'import json,sys; print(json.load(sys.stdin)["applicationId"])')
  echo "   numeric id ${sp_id}, application (client) id ${app_id}  -> GitLab CI variable DATABRICKS_CLIENT_ID for ${env}"

  databricks account service-principal-federation-policy create "$sp_id" --profile "$ACCOUNT_PROFILE" --json "{
    \"oidc_policy\": {
      \"issuer\": \"${GITLAB_ISSUER}\",
      \"audiences\": [\"${ACCOUNT_ID}\"],
      \"subject\": \"${SUBJECT[$env]}\"
    }
  }"
done

# Runtime principals: what jobs run as (bundle run_as) and the role they use in Lakebase. No federation
# policy, so nothing outside Databricks can become them. The CI principal deploys; the runtime principal
# reads data and calls the agent. Give each CI principal the Service Principal User role on its runtime
# principal, so the deploy may set run_as to it.
for env in stg prd; do
  name="spend-jobs-${env}"
  echo "== ${env}: runtime principal ${name}"
  databricks account service-principals create --display-name "$name" --profile "$ACCOUNT_PROFILE" -o json \
    | python3 -c 'import json,sys; d=json.load(sys.stdin); print("   application id", d["applicationId"], "-> databricks.yml jobs_client_id")'
done

cat <<'NOTE'

Next, per environment, in the workspace (not the account):
  1. Add each principal to its workspace and give it only what its bundle deploys need
     (CAN MANAGE on the apps and jobs it owns, USE CATALOG / CREATE SCHEMA on its own catalog).
  2. In GitLab: Settings > CI/CD > Variables, per environment scope (staging, production): DATABRICKS_HOST,
     DATABRICKS_CLIENT_ID, DATABRICKS_ACCOUNT_ID, CATALOG, WAREHOUSE_ID, GENIE_SPACE_ID, LAKEBASE_ENDPOINT,
     LAKEBASE_HOST. None is a secret.
  3. Settings > Repository > Protected branches: protect main and release (merge: maintainers only);
     Settings > Merge requests: fast-forward merge, so release receives main's gated commit unchanged;
     Settings > CI/CD > Protected environments: protect production and require approval.
  4. Forks. A merge request from a fork runs in the fork's project, whose project_path matches no policy.
     But a maintainer can choose "Run pipeline in the parent project" for it, and that pipeline runs the
     FORK's .gitlab-ci.yml with the parent's path, on the fork's branch name. A fork branch named main
     could then match the staging subject. Never run a fork's pipeline in the parent project without
     reading its .gitlab-ci.yml diff; better, disable it for this project.
NOTE
.gitlab-ci.yml (the part that authenticates)
variables:
  DATABRICKS_AUTH_TYPE: env-oidc        # the CLI and SDK exchange the GitLab token themselves
.databricks:
  id_tokens:
    DATABRICKS_OIDC_TOKEN:
      aud: $DATABRICKS_ACCOUNT_ID       # must equal the audience in the federation policy

How to read the result如何解读结果

  • `databricks current-user me` printing the principal's application id means the exchange worked. An error naming the subject means the token's sub claim did not match: compare the job's ref with the policy's subject, character for character. The match is exact; there are no wildcards.`databricks current-user me` 打印出服务主体的 application id,说明兑换成功。如果报错中提到 subject,说明令牌的 sub 声明与策略不匹配:逐字比较作业的分支与策略中的 subject。匹配是完全精确的,没有通配符。
  • The negative tests matter more than the positive ones. If a feature-branch job, or a main job, can authenticate as the production principal, stop and fix the policy before anything else.反向测试比正向测试更重要。如果功能分支或 main 上的作业能以生产服务主体身份认证通过,就先停下来修好策略,再做别的。

Troubleshooting排障

You see现象Why原因Do this处理
invalid audienceinvalid audienceThe aud in id_tokens differs from the policy's audiences.id_tokens 中的 aud 与策略中的 audiences 不一致。Use the Databricks account id in both places, as the vendor page recommends.按照厂商页面的建议,两处都使用 Databricks 账号 id。
The release pipeline cannot verify the gaterelease 流水线无法验证门槛release received a merge commit, so its sha differs from the gated commit on main.release 收到的是一个合并提交,因此它的 sha 与 main 上通过门槛的提交不同。Use fast-forward merges from main into release; release must point at the exact commit the gate passed.从 main 到 release 使用 fast-forward 合并;release 必须指向门槛通过的那个确切提交。
A fork's merge request deployed to staging一个 fork 的合并请求部署到了预发A maintainer chose "Run pipeline in the parent project" for it. That runs the fork's .gitlab-ci.yml under the parent's project path, on the fork's branch name; a fork branch named main matches the staging subject.有维护者为它选择了“Run pipeline in the parent project”。这会在父项目路径下、以 fork 的分支名运行 fork 的 .gitlab-ci.yml;名为 main 的 fork 分支就能匹配预发的 subject。Never run a fork's pipeline in the parent project without reading its .gitlab-ci.yml diff; better, turn the option off for this project. The federation policy cannot tell the two apart.绝不要在没读过 .gitlab-ci.yml 改动的情况下,在父项目中运行 fork 的流水线;更好的做法是为这个项目关闭该选项。联合策略无法区分这两种情况。
The CLI ignores the tokenCLI 没有使用这个令牌DATABRICKS_AUTH_TYPE is not env-oidc, or a leftover DATABRICKS_TOKEN variable takes precedence.DATABRICKS_AUTH_TYPE 不是 env-oidc,或者残留的 DATABRICKS_TOKEN 变量优先级更高。Delete every DATABRICKS_TOKEN variable from GitLab. There should be no secret left to find.从 GitLab 中删除所有 DATABRICKS_TOKEN 变量。不应再留下任何可被发现的机密。

How this scales如何扩展

  • More workflows: one principal per workflow per environment, not one per environment for everything. Blast radius stays one workflow.工作流增多时:每个工作流在每个环境各一个服务主体,而不是每个环境一个主体管所有工作流。这样影响范围始终只限于一个工作流。
Architecture review: questions you will be asked架构评审:你会被问到的问题
Why not one service principal for all environments, it is simpler?所有环境用一个服务主体不是更简单吗?

Then staging's permissions are production's, and the branch restriction cannot exist. Two principals cost two lines in the script; the separation is the control.那样的话,预发的权限就等于生产的权限,分支限制也就无从谈起。两个服务主体只多两行脚本;这种分离本身就是控制措施。

Why a separate runtime principal, when the CI principal already exists?既然已经有 CI 服务主体,为什么还要单独的运行时服务主体?

The CI principal is whoever controls main for a few minutes; the runtime principal reads every invoice, every night. If one identity did both, any merged change could exfiltrate data at deploy time. Split, a malicious deploy can still change code, but that code then runs as a principal whose grants are fixed in governance SQL, and CI needs the Service Principal User role only to set run_as.CI 服务主体代表的是在几分钟内控制 main 的人;运行时服务主体则每晚读取每一张发票。如果一个身份兼做两件事,任何合入的变更都可能在部署时把数据带走。分开之后,恶意部署仍能改代码,但代码运行时用的是一个授权固定在治理 SQL 里的主体;CI 只需要 Service Principal User 角色来设置 run_as。

Why does a merge request get no Databricks access, not even to dev?为什么合并请求连 dev 都不能访问?

Because an MR pipeline runs code from an unreviewed branch. Federation subjects match exactly, so a principal that trusted every branch would need a wildcard that does not exist. Tests run without a workspace, and each engineer deploys dev as themselves, which also keeps their experiments apart.因为合并请求流水线运行的是未经审查分支上的代码。联合策略的 subject 是精确匹配的,要让一个服务主体信任所有分支,就需要通配符,而通配符并不存在。测试无需工作区即可运行,每位工程师以自己的身份部署 dev,这也让各自的实验互不干扰。

Done when完成标准CI authenticates to staging only from main and to production only from release, with no stored secret, and the negative tests fail as they should.CI 只能从 main 认证到预发、只能从 release 认证到生产,不需要任何存储的机密,并且反向测试都如预期失败。
Not confirmed on a vendor page未在厂商页面上确认The vendor example shows an issuer with a group path; GitLab's own OIDC issuer is the instance URL, used here. Exact subject matching is as stated on the federation policy page.厂商示例中的 issuer 带有 group 路径;GitLab 自己的 OIDC issuer 是实例 URL,这里使用的就是它。subject 精确匹配的说法来自联合策略页面。
04Unity Catalog layout, grants, tags and ABAC policiesUnity Catalog 布局、授权、标签和 ABAC 策略
Builds构建内容Schemas per layer, volumes for landing, groups for engineers, reviewers, auditors, a bank-account mask, and a business-unit row filter.按层划分的 schema、用于落地的 volume、工程师/审核人员/审计人员三个用户组、银行账号掩码,以及按业务单元的行过滤。

Why this step, and why here为什么要做这一步,为什么在这里

The agent must see exactly what the person it works for may see, and nothing more. Writing that rule into agent code means writing it again in the app, the dashboard and every notebook, and one of them will be wrong. Unity Catalog applies it once, at the data: a column tagged as a bank account is masked for everyone except auditors, and a table tagged with a business unit column is filtered to the reviewer's units, for every query from every tool, including the agent's.智能体能看到的,必须恰好是它所服务的那个人有权看到的,一点不多。把这条规则写进智能体代码,就得在 App、仪表盘和每个 notebook 里再写一遍,而其中总会有一处写错。Unity Catalog 在数据层只应用一次:标记为银行账号的列,除审计人员外对所有人都做掩码;带有业务单元列标签的表,会被过滤为审核人员负责的单元。对来自任何工具的每一个查询都是如此,包括智能体的查询。

What it does它做什么

Creates the catalog with schemas landing, bronze, silver, gold, ai, tools, governance, evals and ops; volumes for ERP extracts, invoice PDFs, policy documents and artifacts; grants per group and for the agent and jobs principals; a masking function and a row-scope function in the governance schema (never exposed as tools); and two ABAC policies that attach to governed tags rather than to named tables, applied to reviewers and to the agent alike.创建 catalog 及其下的 landing、bronze、silver、gold、ai、tools、governance、evals、ops 这些 schema;用于 ERP 抽取文件、发票 PDF、政策文档和产出物的 volume;按用户组以及为智能体和 job 服务主体设置的授权;放在 governance schema 中(绝不作为工具暴露)的一个掩码函数和一个行范围函数;以及两条挂在受治理标签上、而非指定表上的 ABAC 策略,对审核人员和智能体同样适用。

How to do it怎么做

  1. Create groups fin-engineers, fin-reviewers, fin-auditors and fin-agents in the account (the agent app's principal goes in fin-agents); create governed tag keys pii and scope in Catalog Explorer.在账号中创建 fin-engineers、fin-reviewers、fin-auditors 和 fin-agents 四个用户组(智能体 App 的服务主体放进 fin-agents);在 Catalog Explorer 中创建受治理标签键 pii 和 scope。
  2. Run the file as is in dev; for stg and prd run `python src/common/apply_sql.py --file setup/02_governance.sql --catalog fin_stg --warehouse-id <id>`, which substitutes the catalog. Replace the <...-application-id> placeholders first.在 dev 中直接运行这个文件;对于 stg 和 prd,运行 `python src/common/apply_sql.py --file setup/02_governance.sql --catalog fin_stg --warehouse-id <id>`,它会替换 catalog 名。先替换好 <...-application-id> 占位符。
  3. After step 6 creates the tables, run the two commented ALTER ... SET TAGS lines. The policies apply from that moment.在第 6 步创建好表之后,运行两行被注释掉的 ALTER ... SET TAGS 语句。策略从那一刻起生效。
  4. Test as a reviewer of one unit: a SELECT on gold.open_exceptions must return only that unit, and silver.vendors.bank_account must show ****1234.以只负责一个单元的审核人员身份测试:对 gold.open_exceptions 的 SELECT 只能返回该单元的数据,silver.vendors.bank_account 必须显示为 ****1234。

Scripts脚本

setup/02_governance.sql · sqlglot databricks: 24/38 statements parsed
-- Step 4. Unity Catalog layout, grants, tags and attribute-based policies for one environment.
-- Written for fin_dev. For another environment run it through src/common/apply_sql.py --catalog fin_stg,
-- which substitutes the catalog name, so the file stays runnable as is in the SQL editor for dev.
-- Medallion schemas map to who may write: pipelines write bronze/silver/gold, the AI job writes ai,
-- the agent reads gold and ai and writes nothing here (its writes go to the Lakebase review queue).

CREATE CATALOG IF NOT EXISTS fin_dev COMMENT 'Spend exceptions: development';
USE CATALOG fin_dev;

CREATE SCHEMA IF NOT EXISTS landing COMMENT 'Volumes where ERP extracts and invoice PDFs arrive';
CREATE SCHEMA IF NOT EXISTS bronze  COMMENT 'As landed, append-only';
CREATE SCHEMA IF NOT EXISTS silver  COMMENT 'Typed, deduplicated, quality-checked';
CREATE SCHEMA IF NOT EXISTS gold    COMMENT 'Business entities and match exceptions';
CREATE SCHEMA IF NOT EXISTS ai      COMMENT 'AI Function outputs: parsed documents, extracted fields, classifications';
CREATE SCHEMA IF NOT EXISTS tools   COMMENT 'Functions agents may call. Everything here is listed as an agent tool.';
CREATE SCHEMA IF NOT EXISTS governance COMMENT 'Mask and row-filter functions used by policies. Never exposed as tools.';
CREATE SCHEMA IF NOT EXISTS evals   COMMENT 'Sealed evaluation sets and results';
CREATE SCHEMA IF NOT EXISTS ops     COMMENT 'Run metrics, audit exports';

CREATE VOLUME IF NOT EXISTS landing.erp      COMMENT 'ERP extracts: invoices, purchase_orders, receipts, vendors (JSON)';
CREATE VOLUME IF NOT EXISTS landing.invoices COMMENT 'Invoice documents (PDF) as received';
CREATE VOLUME IF NOT EXISTS landing.policy   COMMENT 'Payment and procurement policy documents';
CREATE VOLUME IF NOT EXISTS ops.artifacts    COMMENT 'Eval summaries and other run outputs read by CI and people';

-- Groups (create them in the account console): fin-engineers, fin-reviewers, fin-auditors, and fin-agents
-- (put the agent app's service principal in it, so the business-unit filter applies to the agent too).
-- Service principals: the CI principals from step 3, and each app's own principal (created with the app).
GRANT USE CATALOG ON CATALOG fin_dev TO `fin-engineers`, `fin-reviewers`, `fin-auditors`;
GRANT USE SCHEMA, SELECT ON SCHEMA gold TO `fin-reviewers`, `fin-auditors`;
GRANT USE SCHEMA, SELECT ON SCHEMA ai   TO `fin-reviewers`, `fin-auditors`;
GRANT USE SCHEMA, EXECUTE ON SCHEMA tools TO `fin-reviewers`;
GRANT USE SCHEMA, SELECT ON SCHEMA evals TO `fin-engineers`;            -- read the exam, never write it
-- Service principals are named by application (client) id in grants, not by display name.
-- The deploying principal owns what it deploys; in dev an engineer's own login deploys instead.
-- Grant the CI principal per SCHEMA, never on the catalog: privileges in Unity Catalog only add up, there is
-- no deny, so CREATE FUNCTION on the catalog would reach governance whatever a later REVOKE on it says.
-- Run these in stg and prd (apply_sql.py substitutes the catalog); replace the id with your CI principal's.
-- GRANT USE CATALOG ON CATALOG fin_dev TO `<ci-application-id>`;
-- GRANT USE SCHEMA, CREATE TABLE, CREATE MATERIALIZED VIEW, MODIFY, SELECT ON SCHEMA bronze TO `<ci-application-id>`;
-- GRANT USE SCHEMA, CREATE TABLE, CREATE MATERIALIZED VIEW, MODIFY, SELECT ON SCHEMA silver TO `<ci-application-id>`;
-- GRANT USE SCHEMA, CREATE TABLE, CREATE MATERIALIZED VIEW, MODIFY, SELECT ON SCHEMA gold   TO `<ci-application-id>`;
-- GRANT USE SCHEMA, CREATE TABLE, CREATE MATERIALIZED VIEW, MODIFY, SELECT ON SCHEMA ai     TO `<ci-application-id>`;
-- GRANT USE SCHEMA, CREATE FUNCTION ON SCHEMA tools TO `<ci-application-id>`;
-- GRANT USE SCHEMA, READ VOLUME ON SCHEMA landing TO `<ci-application-id>`;
-- No grant at all on governance: its owner is the catalog-admins group, and only that group changes it.
-- The pipeline runs as the bundle's run_as principal (the jobs runtime principal in stg and prd), so that
-- principal needs the same bronze, silver, gold and ai lines; the CI principal needs them for the first
-- deploy and for apply_sql.py.

-- The agent app's principal reads gold and ai, calls tools, and nothing else.
GRANT USE CATALOG ON CATALOG fin_dev TO `fin-agents`;
GRANT USE SCHEMA, SELECT ON SCHEMA gold TO `fin-agents`;
GRANT USE SCHEMA, SELECT ON SCHEMA ai   TO `fin-agents`;
GRANT USE SCHEMA, EXECUTE ON SCHEMA tools TO `fin-agents`;
-- The jobs principal (batch triage, export, eval) reads gold and evals, writes ops.
GRANT USE CATALOG ON CATALOG fin_dev TO `<jobs-application-id>`;
GRANT USE SCHEMA, SELECT ON SCHEMA gold TO `<jobs-application-id>`;
GRANT USE SCHEMA, SELECT ON SCHEMA evals TO `<jobs-application-id>`;
GRANT USE SCHEMA, SELECT, MODIFY, CREATE TABLE ON SCHEMA ops TO `<jobs-application-id>`;
GRANT READ VOLUME, WRITE VOLUME ON VOLUME ops.artifacts TO `<jobs-application-id>`;
-- Nobody but catalog admins may create or replace functions in governance: a replaced mask function
-- would switch a policy off for every table at once. A REVOKE cannot protect it (privileges only add up),
-- so ownership does: the schema belongs to catalog-admins, and nobody else holds any privilege on it,
-- directly or through the catalog. Check with SHOW GRANTS below; any row besides the owner is a finding.
ALTER SCHEMA governance OWNER TO `catalog-admins`;
SHOW GRANTS ON SCHEMA governance;

-- Governed tags mark what is sensitive; policies then apply to every table that carries the tag,
-- including tables that do not exist yet. Create the governed tag keys 'pii' and 'scope' in
-- Catalog Explorer > Govern > Governed Tags first.
CREATE OR REPLACE FUNCTION governance.mask_account(v STRING) RETURNS STRING
  RETURN CASE WHEN is_account_group_member('fin-auditors') THEN v ELSE concat('****', right(v, 4)) END;

-- Row scope: a reviewer (or the agent) sees rows of their business units only. reviewer_scope maps
-- principals to units; the agent's principal gets one row per unit it triages, like any reviewer.
CREATE TABLE IF NOT EXISTS gold.reviewer_scope (reviewer STRING NOT NULL, business_unit STRING NOT NULL)
  COMMENT 'Who reviews which business unit. Maintained by finance operations.';

-- Every unit that can appear in gold.open_exceptions needs at least one reviewer AND the agent's principal,
-- or its exceptions reach nobody. That includes UNASSIGNED: invoice PDFs that match no ERP invoice
-- (step 8). Route them to the accounts-payable intake team, who find or reject the invoice.
-- Step 20 alerts on any open unit with no reviewer row. Replace the principals with yours.
-- INSERT INTO gold.reviewer_scope VALUES
--   ('ap-intake-lead@example.com', 'UNASSIGNED'),
--   ('<agent-app-client-id>',      'UNASSIGNED'),
--   ('<agent-app-client-id>',      'EMEA'), ('<agent-app-client-id>', 'NA');

CREATE OR REPLACE FUNCTION governance.in_my_units(bu STRING) RETURNS BOOLEAN
  RETURN is_account_group_member('fin-auditors')
      OR EXISTS (SELECT 1 FROM gold.reviewer_scope s WHERE s.reviewer = current_user() AND s.business_unit = bu);

CREATE POLICY mask_bank_accounts
  ON SCHEMA silver
  COLUMN MASK governance.mask_account
  TO `account users`
  FOR TABLES
  MATCH COLUMNS has_tag_value('pii', 'bank_account') AS acct
  ON COLUMN acct;

CREATE POLICY business_unit_scope
  ON SCHEMA gold
  ROW FILTER governance.in_my_units
  TO `fin-reviewers`, `fin-agents`
  FOR TABLES
  MATCH COLUMNS has_tag_value('scope', 'business_unit') AS bu_col
  USING COLUMNS (bu_col);

-- Tag the columns once the pipeline has created the tables (step 6). Policies take effect immediately.
-- ALTER TABLE silver.vendors       ALTER COLUMN bank_account  SET TAGS ('pii' = 'bank_account');
-- ALTER TABLE gold.match_exceptions ALTER COLUMN business_unit SET TAGS ('scope' = 'business_unit');

SHOW GRANTS ON SCHEMA evals;

How to read the result如何解读结果

  • A reviewer who sees another unit's rows means the row filter did not attach: check that the column carries the tag `scope = business_unit` and that the user is in fin-reviewers (the policy's TO clause).如果审核人员看到了其他单元的行,说明行过滤没有挂上:检查该列是否带有标签 `scope = business_unit`,以及该用户是否属于 fin-reviewers(策略的 TO 子句)。
  • SHOW GRANTS on evals must show SELECT for engineers and no MODIFY. That is the seal on the exam from module 11, as a grant.对 evals 执行 SHOW GRANTS,应显示工程师只有 SELECT,没有 MODIFY。这就是第 11 模块中考题封存的授权形式。

Troubleshooting排障

You see现象Why原因Do this处理
CREATE POLICY fails: tag not foundCREATE POLICY 失败:找不到标签Governed tag keys must exist before a policy can match them.受治理标签键必须先存在,策略才能匹配它们。Create pii and scope under Govern > Governed Tags, then rerun.在 Govern > Governed Tags 下创建 pii 和 scope,然后重跑。
The row filter makes queries slow行过滤让查询变慢The filter function runs a subquery against reviewer_scope for every row.过滤函数对每一行都要对 reviewer_scope 执行子查询。Keep reviewer_scope small and clustered by reviewer; check the query profile. For very large tables, filter on a group membership instead of a mapping table.让 reviewer_scope 保持很小并按 reviewer 聚簇;查看查询概况。对于非常大的表,改为按用户组成员资格过滤,而不是用映射表。
The agent sees nothing智能体什么都看不到The agent's principal is in fin-agents, so the row filter applies, and it has no row in reviewer_scope.智能体的服务主体在 fin-agents 中,所以行过滤对它生效,而它在 reviewer_scope 中没有记录。Give it one reviewer_scope row per unit it triages, including UNASSIGNED for documents that match no invoice. Never add it to fin-auditors to make the problem go away.为它负责分诊的每个单元添加一条 reviewer_scope 记录,包括用于匹配不到发票的文档的 UNASSIGNED。绝不要为了省事把它加进 fin-auditors。
Someone replaced the mask function有人替换了掩码函数Policy functions lived in a schema others could write to.策略函数放在了其他人可以写入的 schema 里。Keep them in the governance schema, owned by catalog-admins, with no grant to anyone else. Never grant CREATE FUNCTION on the catalog: Unity Catalog privileges only add up, so a catalog grant reaches governance and no REVOKE on the schema can take it back. Grant CI per schema, as the file shows, and read SHOW GRANTS ON SCHEMA governance after every change.把它们放在由 catalog-admins 拥有、不对任何其他人授权的 governance schema 中。绝不要在 catalog 上授予 CREATE FUNCTION:Unity Catalog 的权限只会叠加,catalog 级授权会覆盖到 governance,schema 上的任何 REVOKE 都收不回来。像文件中那样按 schema 给 CI 授权,并在每次变更后查看 SHOW GRANTS ON SCHEMA governance。
Exceptions in UNASSIGNED, or a new unit, wait for everUNASSIGNED 或新单元中的异常一直无人处理Nobody, or not the agent, has a reviewer_scope row for that unit, so the row filter hides it from everyone who could act.没有人(或者智能体)在 reviewer_scope 中拥有该单元的记录,于是行过滤把它对所有能处理的人都隐藏了。Every unit needs a human reviewer row and an agent row; UNASSIGNED goes to accounts-payable intake. Step 20 query 6 lists units that reach nobody; alert when it returns any row.每个单元都需要一条人工审核人员记录和一条智能体记录;UNASSIGNED 交给应付账款受理团队。第 20 步的查询 6 会列出无人负责的单元;只要返回任何一行就告警。

How this scales如何扩展

  • ABAC scales with tags, not tables: a new business unit is a row in reviewer_scope, a new sensitive column is a tag. Nobody edits a policy for either.ABAC 随标签扩展,而不是随表扩展:新增业务单元只是 reviewer_scope 中的一行,新增敏感列只是一个标签。两种情况都不需要修改策略。
  • Across many workspaces, the catalog is bound to the workspaces that may use it; prod data is never visible from a dev workspace.在多个工作区之间,catalog 只绑定到可以使用它的工作区;生产数据永远不会在开发工作区中可见。
Architecture review: questions you will be asked架构评审:你会被问到的问题
Why filter in Unity Catalog when the app could filter in its own query?App 自己在查询里过滤不就行了,为什么要在 Unity Catalog 里过滤?

Because the agent, Genie, a dashboard and a notebook all read the same tables. A filter in the app protects one door. A policy on the data protects all of them, and an auditor can read it in one place.因为智能体、Genie、仪表盘和 notebook 读的都是同一批表。App 里的过滤只守住一扇门,数据上的策略守住所有的门,而且审计人员只需在一个地方就能看到它。

Done when完成标准A one-unit reviewer sees one unit, bank accounts are masked for non-auditors, and engineers cannot write to evals.只负责一个单元的审核人员只能看到这一个单元,非审计人员看到的银行账号都被掩码,工程师无法写入 evals。
Not confirmed on a vendor page未在厂商页面上确认A row filter function that queries a mapping table is a documented pattern for per-table row filters; that it behaves the same inside an ABAC policy was not confirmed on the tutorial page read.让行过滤函数查询映射表,是针对单表行过滤的文档化用法;本指南阅读的教程页面没有确认它在 ABAC 策略中是否表现相同。

2 Data: ingest, quality, semantics数据:摄取、质量、语义

An agent's answers are only as good as the tables under it. This phase turns raw ERP extracts and PDFs into one governed work list, with every bad row's fate written next to the rule that caught it, and one definition of each business number. Everything here is plain Databricks data engineering, and that is the point: the AI parts later inherit its lineage, quality metrics and permissions for free.智能体回答的质量,取决于它底下那些表的质量。这个阶段把原始 ERP 抽取文件和 PDF 变成一份受治理的工作清单:每条坏数据的去向都写在抓住它的规则旁边,每个业务数字都只有一个定义。这里全是常规的 Databricks 数据工程,而这正是关键:后面的 AI 部分会免费继承它的血缘、质量指标和权限。

05Bronze: land ERP extracts and invoice PDFs incrementallyBronze:增量落地 ERP 抽取文件和发票 PDF
Builds构建内容Five streaming tables in bronze, fed by Auto Loader from the landing volumes.bronze 中的五张流式表,由 Auto Loader 从落地 volume 读取数据。

Why this step, and why here为什么要做这一步,为什么在这里

Every number the agent states must trace back to a file that arrived on a known day. Bronze keeps each record as landed, with its source file and arrival time, and never rewrites it. Auto Loader tracks which files it has read, so a rerun reads only new files and a failed run resumes where it stopped: the cursor lesson from module 4, provided by the platform.智能体说出的每个数字,都必须能追溯到某天到达的某个文件。Bronze 按到达时的样子保存每条记录,附上来源文件和到达时间,并且从不改写。Auto Loader 会记录哪些文件已经读过,所以重跑只读新文件,失败的运行会从中断处继续:这就是第 4 模块讲的游标,现在由平台提供。

What it does它做什么

bronze.py defines bronze.invoices, purchase_orders, receipts and vendors from JSON extracts, and bronze.invoice_docs from PDFs as binary. New source columns go to _rescued_data instead of failing the run.bronze.py 从 JSON 抽取文件定义了 bronze.invoices、purchase_orders、receipts 和 vendors,并把 PDF 以二进制形式定义为 bronze.invoice_docs。源数据新增的列会进入 _rescued_data,而不会让运行失败。

How to do it怎么做

  1. Agree a landing contract with the ERP team: one folder per entity under /Volumes/<catalog>/landing/erp/, JSON lines, full or incremental extracts with an updated timestamp.与 ERP 团队约定落地规范:在 /Volumes/<catalog>/landing/erp/ 下每个实体一个目录,JSON lines 格式,全量或增量抽取都要带更新时间戳。
  2. If your ERP has a Lakeflow Connect managed connector, use it instead of file extracts; it lands the same bronze tables with less code to own.如果你的 ERP 有 Lakeflow Connect 托管连接器,就用它代替文件抽取;它落地的是同样的 bronze 表,你需要维护的代码更少。
  3. Deploy the pipeline with the bundle and run it once from the Pipelines UI to see the graph.用 bundle 部署 pipeline,并从 Pipelines 界面运行一次,查看依赖图。

Scripts脚本

pipelines/bronze.py · compiles
# Step 5. Bronze: land ERP extracts and invoice documents as they arrive, incrementally, append-only.
# A Lakeflow pipeline source file. `spark` is provided by the pipeline runtime.
# Configuration keys (resources/pipeline.yml): landing_root = /Volumes/<catalog>/landing
#
# Auto Loader keeps track of which files it has read, so a rerun reads only new files and a
# failed run resumes where it stopped. Bronze keeps every record with its source file and arrival
# time: when an auditor asks where a number came from, this is the first link of the chain.
from pyspark import pipelines as dp
from pyspark.sql import functions as F

ROOT = spark.conf.get("landing_root")  # noqa: F821 - provided by the pipeline runtime


def _erp(entity: str):
    return (
        spark.readStream.format("cloudFiles")  # noqa: F821
        .option("cloudFiles.format", "json")
        .option("cloudFiles.inferColumnTypes", "true")
        .option("cloudFiles.schemaEvolutionMode", "rescue")      # new source columns go to _rescued_data, never break the run
        .load(f"{ROOT}/erp/{entity}/")
        .withColumn("_source_file", F.col("_metadata.file_path"))
        .withColumn("_ingested_at", F.current_timestamp())
    )


@dp.table(name="bronze.invoices", comment="Invoice headers from the ERP extract, as landed.")
def invoices():
    return _erp("invoices")


@dp.table(name="bronze.purchase_orders", comment="Purchase orders from the ERP extract, as landed.")
def purchase_orders():
    return _erp("purchase_orders")


@dp.table(name="bronze.receipts", comment="Goods and service receipts from the ERP extract, as landed.")
def receipts():
    return _erp("receipts")


@dp.table(name="bronze.vendors", comment="Vendor master from the ERP extract, as landed.")
def vendors():
    return _erp("vendors")


@dp.table(name="bronze.invoice_docs", comment="Invoice PDFs as binary, one row per file.")
def invoice_docs():
    return (
        spark.readStream.format("cloudFiles")  # noqa: F821
        .option("cloudFiles.format", "binaryFile")
        .option("pathGlobFilter", "*.pdf")
        .load(f"{ROOT}/invoices/")
        .select(F.col("path"), F.col("content"), F.col("length"), F.col("modificationTime"),
                F.current_timestamp().alias("_ingested_at"))
    )
resources/pipeline.yml · yaml parses
# Steps 5, 6, 8, 9. One serverless Lakeflow pipeline: bronze -> silver -> gold, plus the AI enrichment.
resources:
  pipelines:
    spend_pipeline:
      name: spend-exceptions-pipeline
      catalog: ${var.catalog}
      schema: bronze                      # default schema; the source files publish to bronze, silver, gold, ai
      serverless: true
      continuous: false                   # triggered by the orchestrator job when files arrive
      libraries:
        - file:
            path: ../pipelines/bronze.py
        - file:
            path: ../pipelines/silver_gold.sql
        - file:
            path: ../pipelines/enrich.sql
      configuration:
        landing_root: /Volumes/${var.catalog}/landing
        tolerance_pct: "2"                # a price variance above 2% of the PO, or
        tolerance_abs: "50"               # above 50 in invoice currency, whichever is larger

How to read the result如何解读结果

  • Each bronze table's row count should equal the records in the files landed so far. A count that doubles on rerun means something bypassed Auto Loader (a manual COPY or a reset checkpoint).每张 bronze 表的行数应等于目前已落地文件中的记录数。如果重跑后行数翻倍,说明有东西绕过了 Auto Loader(手动 COPY 或重置了 checkpoint)。
  • A non-empty _rescued_data column is the ERP changing its extract without telling you. Read it weekly; it is cheaper than a broken month-end._rescued_data 列不为空,说明 ERP 在没通知你的情况下改了抽取格式。每周看一次;这比月末结账出问题便宜得多。

Troubleshooting排障

You see现象Why原因Do this处理
Pipeline fails: cannot read landing_rootpipeline 失败:无法读取 landing_rootThe configuration key is missing, or the pipeline's run-as identity has no READ VOLUME.缺少该配置键,或者 pipeline 的运行身份没有 READ VOLUME 权限。Check resources/pipeline.yml configuration and grant READ VOLUME on landing to the deploying principal.检查 resources/pipeline.yml 中的 configuration,并给部署用的服务主体授予 landing 上的 READ VOLUME。
Types change between files (amount as string, then number)不同文件之间类型变了(amount 先是字符串,后来是数字)Schema inference sees different files differently.schema 推断对不同文件得出不同结果。Cast explicitly in silver (step 6 does). Bronze stays as landed by design.在 silver 中显式转换类型(第 6 步就是这样做的)。Bronze 按设计保持原样。

How this scales如何扩展

  • Auto Loader in file-notification mode instead of directory listing when a folder holds millions of files; listing cost grows with the folder, notifications do not.当一个目录里有上百万个文件时,让 Auto Loader 使用文件通知模式而不是目录列举;列举成本随目录增长,通知模式则不会。
  • At high volume, switch the orchestrator from file-arrival to a schedule (every 15 minutes): one pipeline update per batch, not per file.在高数据量下,把编排从文件到达触发改为定时(每 15 分钟):每批一次 pipeline 更新,而不是每个文件一次。
Architecture review: questions you will be asked架构评审:你会被问到的问题
Why keep bronze at all, if silver has the clean data?既然 silver 有干净的数据,为什么还要保留 bronze?

Because silver's rules will change, and when they do you rebuild silver from bronze. Without bronze, a bug in a cast is permanent. It is also the first link of the audit trail.因为 silver 的规则会变,而规则变了就要从 bronze 重建 silver。没有 bronze,一个类型转换的 bug 就是永久性的。它也是审计链条的第一环。

Done when完成标准New files in the landing volume appear in bronze on the next pipeline update, once each, with source file and arrival time.落地 volume 中的新文件会在下一次 pipeline 更新时出现在 bronze 中,每个只出现一次,并带有来源文件和到达时间。
Not confirmed on a vendor page未在厂商页面上确认Publishing to several schemas from one pipeline by qualified name (bronze.invoices) and the `from pyspark import pipelines as dp` import are the current pipeline conventions as understood; the expectations page used `dp` without showing its import.在一个 pipeline 中按限定名(bronze.invoices)发布到多个 schema,以及 `from pyspark import pipelines as dp` 这个导入方式,是目前理解的 pipeline 惯例;期望规则页面使用了 `dp`,但没有展示它的导入语句。
06Silver and gold: expectations and the three-way matchSilver 与 gold:期望规则与三单匹配
Builds构建内容Typed, deduplicated silver tables with expectations; gold.match_exceptions with stable exception ids.带有期望规则、类型规范且去重的 silver 表;带稳定异常 id 的 gold.match_exceptions。

Why this step, and why here为什么要做这一步,为什么在这里

This is the business logic, so it must be readable by the finance team, not only by engineers. SQL with expectations does that: each rule says what it checks and what happens to a bad row. The choice is a business decision written beside the rule: an invoice with no vendor stops the update (FAIL), because a payment pipeline that silently drops an invoice is worse than one that stops; a row with no id is dropped and counted. The exception id is a hash of invoice and type, so a re-run never creates a second exception for the same problem.这是业务逻辑,所以它必须让财务团队也看得懂,而不只是工程师。带期望规则的 SQL 做到了这一点:每条规则都说明它检查什么,以及坏数据会怎样处理。这个选择是写在规则旁边的业务决定:没有供应商的发票会让更新停止(FAIL),因为悄悄丢掉一张发票的付款流水线,比停下来的更糟;没有 id 的行会被丢弃并计数。异常 id 是发票号和类型的哈希,所以重跑永远不会为同一个问题生成第二个异常。

What it does它做什么

Four silver materialized views keep the latest version of each record with explicit types and expectations, and the first arrival time of each invoice. gold.match_exceptions matches cumulatively per purchase order (a PO billed in three partial invoices is fine until the invoices together exceed it) and emits five exception types: no_po, no_receipt, price_variance, quantity_variance and duplicate_suspect, with tolerances from pipeline configuration. detected_at is the invoice's first arrival, so backlog age is real.四个 silver 物化视图以显式类型和期望规则保留每条记录的最新版本,以及每张发票的首次到达时间。gold.match_exceptions 按采购订单累计匹配(一张采购单分三张部分发票开票是正常的,直到发票合计超过它为止),输出五种异常类型:no_po、no_receipt、price_variance、quantity_variance 和 duplicate_suspect,容差取自 pipeline 配置。detected_at 是发票的首次到达时间,所以积压时长是真实的。

How to do it怎么做

  1. Review the tolerances (2% or 50, whichever is larger) with finance and set them in resources/pipeline.yml.与财务一起审核容差(2% 或 50,取较大者),并在 resources/pipeline.yml 中设置。
  2. Run the pipeline and open the Data quality tab: each expectation shows rows passed, dropped or warned.运行 pipeline,打开 Data quality 标签页:每条期望规则都会显示通过、丢弃或告警的行数。
  3. Hand-check twenty exceptions with an AP clerk before anything automated reads this table.在任何自动化程序读取这张表之前,先和一位应付账款人员手工核对二十条异常。
  4. Tag business_unit on gold.match_exceptions (step 4) so the row filter applies.在 gold.match_exceptions 的 business_unit 列上打标签(第 4 步),让行过滤生效。

Scripts脚本

pipelines/silver_gold.sql · sqlglot databricks: 5/5 statements parsed (6 ON VIOLATION clauses skipped)
-- Step 6. Silver: typed, deduplicated, quality-checked. Gold: the three-way match exceptions.
-- A Lakeflow pipeline source file (SQL). ${tolerance_pct} and ${tolerance_abs} come from the
-- pipeline configuration in resources/pipeline.yml, so finance can change a tolerance in review.
--
-- Expectations decide what happens to a bad row: warn and keep (EXPECT), drop it (DROP ROW), or
-- stop the update (FAIL UPDATE). The choice is a business decision, written next to the rule:
-- a payment pipeline that silently drops an invoice is worse than one that stops.

CREATE OR REFRESH MATERIALIZED VIEW silver.invoices (
  CONSTRAINT has_id        EXPECT (invoice_id IS NOT NULL)              ON VIOLATION DROP ROW,
  CONSTRAINT has_vendor    EXPECT (vendor_id IS NOT NULL)               ON VIOLATION FAIL UPDATE,
  CONSTRAINT positive      EXPECT (amount > 0),
  CONSTRAINT known_ccy     EXPECT (currency IN ('USD', 'EUR', 'GBP', 'CAD')),
  CONSTRAINT has_unit      EXPECT (business_unit IS NOT NULL)           ON VIOLATION FAIL UPDATE
) COMMENT 'One row per invoice, latest version from the ERP. amount is the invoice total in currency.'
AS SELECT
  CAST(invoice_id AS STRING)            AS invoice_id,
  CAST(vendor_id AS STRING)             AS vendor_id,
  CAST(po_id AS STRING)                 AS po_id,
  CAST(business_unit AS STRING)         AS business_unit,
  CAST(invoice_date AS DATE)            AS invoice_date,
  CAST(amount AS DECIMAL(18, 2))        AS amount,
  upper(CAST(currency AS STRING))       AS currency,
  CAST(line_description AS STRING)      AS line_description,
  _source_file,
  _ingested_at,
  -- first arrival, kept across later versions: the age of an exception is measured from here
  min(_ingested_at) OVER (PARTITION BY invoice_id) AS first_seen_at
FROM bronze.invoices
QUALIFY row_number() OVER (PARTITION BY invoice_id ORDER BY _ingested_at DESC) = 1;

CREATE OR REFRESH MATERIALIZED VIEW silver.purchase_orders (
  CONSTRAINT has_id   EXPECT (po_id IS NOT NULL) ON VIOLATION DROP ROW,
  CONSTRAINT positive EXPECT (amount > 0)
) COMMENT 'One row per purchase order, latest version. amount is the approved order total.'
AS SELECT CAST(po_id AS STRING) AS po_id, CAST(vendor_id AS STRING) AS vendor_id,
          CAST(business_unit AS STRING) AS business_unit, CAST(amount AS DECIMAL(18, 2)) AS amount,
          CAST(approved_by AS STRING) AS approved_by, _ingested_at
FROM bronze.purchase_orders
QUALIFY row_number() OVER (PARTITION BY po_id ORDER BY _ingested_at DESC) = 1;

CREATE OR REFRESH MATERIALIZED VIEW silver.receipts (
  CONSTRAINT has_po EXPECT (po_id IS NOT NULL) ON VIOLATION DROP ROW
) COMMENT 'Receipts against purchase orders. received_amount is the value received.'
AS SELECT CAST(receipt_id AS STRING) AS receipt_id, CAST(po_id AS STRING) AS po_id,
          CAST(received_amount AS DECIMAL(18, 2)) AS received_amount, CAST(received_date AS DATE) AS received_date
FROM bronze.receipts
QUALIFY row_number() OVER (PARTITION BY receipt_id ORDER BY _ingested_at DESC) = 1;

CREATE OR REFRESH MATERIALIZED VIEW silver.vendors (
  CONSTRAINT has_id EXPECT (vendor_id IS NOT NULL) ON VIOLATION DROP ROW
) COMMENT 'Vendor master. bank_account is masked by policy for everyone except auditors.'
AS SELECT CAST(vendor_id AS STRING) AS vendor_id, CAST(name AS STRING) AS name,
          CAST(bank_account AS STRING) AS bank_account, CAST(risk_tier AS STRING) AS risk_tier
FROM bronze.vendors
QUALIFY row_number() OVER (PARTITION BY vendor_id ORDER BY _ingested_at DESC) = 1;

-- Gold: one row per invoice and exception type. The exception id is a hash of invoice and type, so
-- a re-run never creates a second exception for the same problem. detected_at is the invoice's first
-- arrival, not the refresh time, so backlog age and monthly trends mean something.
--
-- Matching is cumulative per purchase order: a PO billed in three partial invoices is fine until the
-- invoices together exceed the PO (price) or what was received (quantity). Comparing each invoice to
-- the whole PO would flag every partial invoice as a variance.
CREATE OR REFRESH MATERIALIZED VIEW gold.match_exceptions
COMMENT 'Invoices that fail the three-way match. One row per invoice and exception type. Amounts in invoice currency.'
AS
WITH rec AS (
  SELECT po_id, sum(received_amount) AS received_amount, count(*) AS receipts
  FROM silver.receipts GROUP BY po_id
),
m AS (
  SELECT i.invoice_id, i.vendor_id, i.po_id, i.business_unit, i.invoice_date, i.currency, i.first_seen_at,
         i.amount AS invoice_amount, p.amount AS po_amount, p.po_id AS matched_po,
         coalesce(r.received_amount, 0) AS received_amount, r.receipts,
         sum(i.amount) OVER (PARTITION BY i.po_id ORDER BY i.invoice_date, i.invoice_id
                             ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS invoiced_to_date
  FROM silver.invoices i
  LEFT JOIN silver.purchase_orders p ON p.po_id = i.po_id
  LEFT JOIN rec r ON r.po_id = i.po_id
),
dups AS (
  -- One row per suspect: the later invoice (by date, then id) of a vendor/amount pair within 7 days.
  -- min_by picks a single twin, so three identical invoices still give one exception each, never two.
  SELECT b.invoice_id, min_by(a.invoice_id, a.invoice_date) AS twin_invoice_id
  FROM silver.invoices a JOIN silver.invoices b
    ON a.vendor_id = b.vendor_id AND a.amount = b.amount AND a.invoice_id <> b.invoice_id
   AND (a.invoice_date < b.invoice_date OR (a.invoice_date = b.invoice_date AND a.invoice_id < b.invoice_id))
   AND datediff(b.invoice_date, a.invoice_date) <= 7
  GROUP BY b.invoice_id
),
typed AS (
  SELECT m.*, 'no_po' AS exception_type, CAST(NULL AS STRING) AS twin_invoice_id
  FROM m WHERE m.matched_po IS NULL                    -- no PO number, or a PO the ERP does not know
  UNION ALL
  SELECT m.*, 'no_receipt', NULL FROM m WHERE m.matched_po IS NOT NULL AND m.receipts IS NULL
  UNION ALL
  SELECT m.*, 'price_variance', NULL FROM m
  WHERE m.matched_po IS NOT NULL
    AND m.invoiced_to_date - m.po_amount > greatest(${tolerance_abs}, m.po_amount * ${tolerance_pct} / 100)
  UNION ALL
  SELECT m.*, 'quantity_variance', NULL FROM m
  WHERE m.receipts IS NOT NULL
    AND m.invoiced_to_date - m.received_amount > greatest(${tolerance_abs}, m.received_amount * ${tolerance_pct} / 100)
  UNION ALL
  SELECT m.*, 'duplicate_suspect', d.twin_invoice_id FROM m JOIN dups d ON d.invoice_id = m.invoice_id
)
SELECT sha2(concat_ws('|', invoice_id, exception_type), 256) AS exception_id,
       exception_type, invoice_id, twin_invoice_id, vendor_id, po_id, business_unit, invoice_date, currency,
       invoice_amount, po_amount, received_amount, invoiced_to_date,
       round(CASE exception_type
               WHEN 'price_variance'    THEN invoiced_to_date - po_amount
               WHEN 'quantity_variance' THEN invoiced_to_date - received_amount
               ELSE NULL END, 2) AS variance,
       first_seen_at AS detected_at
FROM typed;

How to read the result如何解读结果

  • Exception counts by type are the first sanity check. Duplicate suspects at 10% of invoices means the rule is too loose (same vendor and amount within 7 days catches recurring monthly fees); at 0% on a large book it is probably broken.按类型统计的异常数是第一道合理性检查。如果重复嫌疑占发票的 10%,说明规则太宽(同一供应商、同一金额、7 天内,会把每月固定费用也抓进来);如果在大量发票上为 0%,很可能是规则坏了。
  • A FAIL UPDATE on has_vendor stops the whole update: nothing downstream sees partial data. Fix the source and rerun; do not change the rule to WARN under pressure.has_vendor 上的 FAIL UPDATE 会停止整次更新:下游不会看到不完整的数据。修正源数据后重跑;不要在压力下把规则改成 WARN。

Troubleshooting排障

You see现象Why原因Do this处理
Exception ids change between runs异常 id 在两次运行之间变了The id included a timestamp or a non-deterministic column.id 中包含了时间戳或不确定的列。Hash only invoice_id and exception_type, as the file does. Anything else breaks the link to past decisions.只对 invoice_id 和 exception_type 做哈希,就像文件里那样。加入任何其他内容都会切断与历史决定的关联。
Every partial invoice is flagged as a price variance每张部分发票都被标为价格差异Each invoice was compared with the whole PO.每张发票都被拿去和整张采购单比较。Compare invoiced-to-date per PO, as the file does; only the invoice that pushes the total over the PO is an exception.像文件中那样按采购单比较累计开票金额;只有让总额超过采购单的那张发票才算异常。
Parameter ${tolerance_pct} appears literally参数 ${tolerance_pct} 原样出现在 SQL 里The configuration key is not set on the pipeline.pipeline 上没有设置该配置键。Set it in resources/pipeline.yml configuration and redeploy.在 resources/pipeline.yml 的 configuration 中设置,然后重新部署。

How this scales如何扩展

  • Materialized views refresh incrementally where they can on serverless pipelines. When the invoice table reaches hundreds of millions of rows, add liquid clustering on (business_unit, invoice_date) and check the refresh plan in the pipeline event log.在 serverless pipeline 上,物化视图会尽可能增量刷新。当发票表达到数亿行时,在 (business_unit, invoice_date) 上加 liquid clustering,并在 pipeline 事件日志里检查刷新计划。
  • The duplicate self-join is the expensive part. Bound it by date window and vendor; it already is, keep it that way.重复检测的自连接是最贵的部分。用日期窗口和供应商来限定它;现在已经限定了,保持这样。
Architecture review: questions you will be asked架构评审:你会被问到的问题
Why detect exceptions with rules and not ask the model?为什么用规则来识别异常,而不是问模型?

A three-way match is arithmetic. Rules are exact, free, explainable to an auditor, and identical on every run. The model is spent where judgment is needed: deciding what to do about the exception, with evidence.三单匹配是算术。规则精确、免费、可以向审计人员解释,而且每次运行结果完全一样。模型的力气要花在需要判断的地方:凭证据决定如何处理这个异常。

Done when完成标准Twenty hand-checked exceptions agree with an AP clerk's judgment, and the Data quality tab shows every expectation's counts.二十条手工核对的异常与应付账款人员的判断一致,Data quality 标签页显示了每条期望规则的计数。
07The semantic layer: a metric view and real comments语义层:指标视图和真正有用的注释
Builds构建内容gold.exception_metrics: one governed definition of open exceptions, exposure and variance.gold.exception_metrics:未结异常、敞口和差异的唯一受治理定义。

Why this step, and why here为什么要做这一步,为什么在这里

"Open exposure" will be computed by the CFO's dashboard, by Genie, and by the agent's rationale. If it is defined three times it will be three numbers, and the agent will be blamed for the difference. A metric view makes the definition a governed object that all three query. Comments matter for the same reason: Genie and the agent choose columns by reading them.“未结敞口”会由 CFO 的仪表盘、Genie 和智能体的理由各算一遍。如果定义了三次,就会出现三个数字,而差异会被归咎于智能体。指标视图把这个定义变成一个受治理的对象,三者都查询它。注释重要也是出于同样的原因:Genie 和智能体是通过阅读注释来选择列的。

What it does它做什么

Creates a metric view over gold.open_exceptions with three dimensions and three measures, shows the MEASURE() query, and checks what Genie will read with DESCRIBE TABLE EXTENDED.在 gold.open_exceptions 上创建一个指标视图,包含三个维度和三个度量,展示 MEASURE() 查询,并用 DESCRIBE TABLE EXTENDED 检查 Genie 将会读到什么。

How to do it怎么做

  1. Agree each measure's definition with finance in the merge request, in plain words in the comment field.在合并请求中与财务确认每个度量的定义,并用通俗的话写进 comment 字段。
  2. Run the file in the SQL editor (it is not part of the pipeline: it reads the pipeline's tables).在 SQL 编辑器中运行这个文件(它不属于 pipeline:它读取 pipeline 的表)。
  3. Point the AI/BI dashboard and the Genie space (step 11) at the metric view, not at the raw table.让 AI/BI 仪表盘和 Genie space(第 11 步)指向指标视图,而不是原始表。

Scripts脚本

semantics/metric_view.sql · sqlglot databricks: 3/4 statements parsed
-- Step 7. The semantic layer: one definition of each business number, used by dashboards, Genie and the agent.
-- Without it, "open exposure" is computed three ways in three places and the agent's figure will not
-- match the dashboard the CFO looks at. A metric view makes the definition a governed object.

CREATE OR REPLACE VIEW fin_dev.gold.exception_metrics
WITH METRICS
LANGUAGE YAML
AS $$
version: 1.1
source: fin_dev.gold.open_exceptions
dimensions:
  - name: Business Unit
    expr: business_unit
  - name: Exception Type
    expr: exception_type
  - name: Month
    expr: DATE_TRUNC('MONTH', detected_at)
measures:
  - name: Open Exceptions
    expr: COUNT(1)
    comment: "Invoices currently failing the match or the document check"
  - name: Open Exposure
    expr: SUM(invoice_amount)
    comment: "Invoice value held by open exceptions, in invoice currency"
  - name: Net Variance
    expr: SUM(variance)
    comment: "Invoice minus PO (price) or minus received (quantity); null for other types"
$$;

-- Query a metric view with MEASURE(); the grouping decides the grain, the definition stays fixed.
SELECT `Business Unit`, `Exception Type`, MEASURE(`Open Exceptions`), MEASURE(`Open Exposure`)
FROM fin_dev.gold.exception_metrics
GROUP BY ALL
ORDER BY 4 DESC;

-- Comments are not decoration. Genie and the agent read table and column comments to choose
-- columns; a column called amt2 with no comment is a wrong answer waiting to happen.
-- Tables owned by a pipeline get their comments in the pipeline definition (the COMMENT clauses in
-- pipelines/*.sql), because the pipeline owns their schema. Check what Genie will see:
DESCRIBE TABLE EXTENDED fin_dev.gold.open_exceptions;
-- Tables you own directly take comments here:
COMMENT ON TABLE fin_dev.gold.reviewer_scope IS 'Who reviews which business unit. Used by the row filter policy.';

How to read the result如何解读结果

  • The MEASURE() query's totals must equal a hand SUM over the same filter. If they differ, a measure expression is wrong, and it is wrong everywhere at once, which is also how you fix it everywhere at once.MEASURE() 查询的合计必须等于同样过滤条件下手工 SUM 的结果。如果不一致,说明某个度量表达式错了,而且它在所有地方同时错;这也意味着修正它也能一次改好所有地方。
  • In DESCRIBE TABLE EXTENDED, every column the agent uses should have a comment that states units and meaning. An empty comment is a future wrong answer.在 DESCRIBE TABLE EXTENDED 中,智能体会用到的每一列都应该有说明单位和含义的注释。空注释就是未来的错误答案。

Troubleshooting排障

You see现象Why原因Do this处理
CREATE VIEW ... WITH METRICS failsCREATE VIEW ... WITH METRICS 失败The warehouse or runtime is too old for metric views, or the YAML is not indented.warehouse 或运行时版本太旧,不支持指标视图;或者 YAML 没有缩进。Use a current serverless SQL warehouse; validate the YAML block separately.使用当前的 serverless SQL warehouse;单独校验 YAML 块。
Currencies are summed together不同币种被加在了一起Open Exposure sums invoice_amount across currencies.Open Exposure 跨币种汇总了 invoice_amount。Either add currency as a dimension and never total across it, or convert in silver with a governed rate table. Decide before the first dashboard ships.要么把币种作为维度并且绝不跨币种汇总,要么在 silver 中用受治理的汇率表做换算。在第一个仪表盘上线前就要决定。

How this scales如何扩展

  • Metric views are the contract between data and every consumer. When a second workflow needs exposure, it queries this view; it does not copy the SQL.指标视图是数据与所有使用方之间的契约。当第二个工作流需要敞口数字时,它查询这个视图,而不是复制 SQL。
Architecture review: questions you will be asked架构评审:你会被问到的问题
Is a semantic layer over-engineering for one workflow?只有一个工作流,搞语义层是不是过度设计?

It is one file. The alternative is the first meeting where the agent's number differs from the dashboard's, which ends trust in the agent for reasons that have nothing to do with the agent.它只是一个文件。不这样做的代价是:第一次开会时,智能体给的数字和仪表盘上的不一样,于是大家对智能体失去信任,而原因跟智能体本身毫无关系。

Done when完成标准Dashboard, Genie and a hand query return the same exposure for the same filter.对于同样的过滤条件,仪表盘、Genie 和手工查询返回相同的敞口数字。
Not confirmed on a vendor page未在厂商页面上确认The vendor's example uses `fields:` in metric view YAML version 1.1 and says the editor generates the equivalent `dimensions:`; this file uses `dimensions:`.厂商示例在指标视图 YAML 1.1 版本中使用 `fields:`,并说明编辑器会生成等价的 `dimensions:`;本文件使用 `dimensions:`。

3 Document AI in the pipelinepipeline 中的文档 AI

The invoice PDF is evidence the ERP record can be checked against. AI Functions run inside the pipeline as SQL, once per document, governed and billed like the rest of the pipeline. Every model output carries a confidence score, and the rule is the same as for people: low confidence or disagreement with the system of record goes to a human, never to a silent correction.发票 PDF 是可以用来核对 ERP 记录的证据。AI Functions 以 SQL 形式在 pipeline 内运行,每份文档只处理一次,与 pipeline 的其他部分一样受治理、一样计费。每个模型输出都带有置信度分数,规则和对人的要求一样:置信度低或与记录系统不一致时,交给人处理,绝不悄悄纠正。

08Parse and extract invoice fields, then check them against the ERP解析并抽取发票字段,再与 ERP 核对
Builds构建内容ai.invoice_parsed, ai.invoice_fields with confidence and citations, gold.document_checks, and gold.open_exceptions.ai.invoice_parsed、带置信度和引用的 ai.invoice_fields、gold.document_checks,以及 gold.open_exceptions。

Why this step, and why here为什么要做这一步,为什么在这里

An ERP record can be keyed wrong; the PDF the vendor sent is the original. Parsing it with ai_parse_document and extracting fields with ai_extract turns the PDF into numbers that can be compared. These run in streaming tables on purpose: a streaming table processes each document once, while a materialized view may recompute everything, and an AI Function in a full recompute is billed again for every document it already read. On a million invoices that is the whole budget.ERP 记录可能录错;供应商寄来的 PDF 才是原件。用 ai_parse_document 解析,再用 ai_extract 抽取字段,就能把 PDF 变成可以比对的数字。这些处理特意放在流式表里:流式表对每份文档只处理一次,而物化视图可能会全部重算,一次全量重算中的 AI Function 会对已经读过的每份文档再计一次费。一百万张发票,这就是全部预算。

What it does它做什么

ai.invoice_parsed holds the parsed document per PDF. ai.invoice_fields extracts invoice id, vendor, PO number, total, currency and date with an advanced schema, confidence scores and citations. gold.document_checks keeps the latest document per invoice and sets mismatch when the totals differ, the currency differs, the amount's confidence is below 0.8, any value is missing (NULL counts as a mismatch: "could not tell" is not "agrees"), or the PDF matches no ERP invoice at all (business unit UNASSIGNED). gold.open_exceptions unions match exceptions and document mismatches into the agent's work list.ai.invoice_parsed 保存每个 PDF 的解析结果。ai.invoice_fields 使用高级 schema 抽取发票号、供应商、采购单号、总额、币种和日期,并附带置信度分数和引用。gold.document_checks 为每张发票保留最新的文档,并在以下情况把 mismatch 设为真:总额不同、币种不同、金额置信度低于 0.8、任何值缺失(NULL 视为不一致:“看不出来”不等于“一致”),或者 PDF 根本匹配不到任何 ERP 发票(业务单元记为 UNASSIGNED)。gold.open_exceptions 把匹配异常和文档不一致合并为智能体的工作清单。

How to do it怎么做

  1. Start with 200 real invoices in a dev catalog. Run the pipeline and read the extracted fields beside the PDFs.在开发 catalog 中先用 200 张真实发票。运行 pipeline,把抽取出的字段与 PDF 对照阅读。
  2. Tune the schema descriptions and the instructions option until the totals agree on at least 98% of the sample. Descriptions are prompts.调整 schema 中的描述和 instructions 选项,直到样本中至少 98% 的总额一致。描述就是提示词。
  3. Pick the confidence cut from data (the classifier_check helper in step 9 works for any score), not from a guess.根据数据选择置信度阈值(第 9 步中的 classifier_check 辅助函数适用于任何分数),而不是靠猜。
  4. For no-code iteration on the schema, Agent Bricks Information Extraction maps to the same ai_extract function.如果想无代码地迭代 schema,Agent Bricks 的 Information Extraction 对应的是同一个 ai_extract 函数。

Scripts脚本

pipelines/enrich.sql · sqlglot databricks: 5/5 statements parsed
-- Steps 8 and 9. Document AI inside the pipeline: parse every invoice PDF once, extract the fields
-- that matter, compare them with the ERP record, and classify each invoice line's spend category.
--
-- These are STREAMING tables on purpose. A streaming table processes each new row once. A
-- materialized view may recompute from scratch, and an AI Function in a full recompute is billed
-- again for every document it has already read. On a million invoices that is the whole budget.

CREATE OR REFRESH STREAMING TABLE ai.invoice_parsed
COMMENT 'ai_parse_document output for each invoice PDF, once per file.'
AS SELECT path, _ingested_at, ai_parse_document(content, map('version', '2.0')) AS parsed
FROM STREAM(bronze.invoice_docs);

CREATE OR REFRESH STREAMING TABLE ai.invoice_fields (
  CONSTRAINT extracted EXPECT (fields:error_message IS NULL)
)
COMMENT 'Fields extracted from each parsed invoice, with confidence scores and citations.'
AS SELECT path, _ingested_at,
  ai_extract(
    parsed,
    '{
      "invoice_id":   {"type": "string", "description": "The invoice number printed on the document"},
      "vendor_name":  {"type": "string"},
      "po_number":    {"type": "string", "description": "Purchase order number, if printed"},
      "total_amount": {"type": "number", "description": "Invoice total including tax"},
      "currency":     {"type": "enum", "labels": ["USD", "EUR", "GBP", "CAD"]},
      "invoice_date": {"type": "string", "description": "Invoice date as YYYY-MM-DD"}
    }',
    map('version', '2.1', 'enableConfidenceScores', 'true', 'enableCitations', 'true',
        'instructions', 'Accounts payable invoices. Amounts are totals, not line items.')
  ) AS fields
FROM STREAM(ai.invoice_parsed);

-- The document is evidence only if it agrees with the ERP. Disagreement, low extraction confidence,
-- a missing value, or a PDF that matches no ERP invoice at all becomes a doc_mismatch for a person,
-- never a silent correction. NULL is treated as a mismatch: "could not tell" is not "agrees".
-- One row per document key: if a vendor re-sends a PDF, the latest one counts.
CREATE OR REFRESH MATERIALIZED VIEW gold.document_checks
COMMENT 'Invoice document vs. ERP invoice. mismatch = true means a person must look. business_unit UNASSIGNED: the PDF matches no ERP invoice.'
AS
WITH f AS (
  SELECT path, _ingested_at,
         coalesce(fields:response.invoice_id.value::STRING, path)      AS doc_key,
         fields:response.invoice_id.value::STRING                      AS doc_invoice_id,
         fields:response.total_amount.value::DECIMAL(18, 2)            AS doc_amount,
         fields:response.total_amount.confidence_score::DOUBLE         AS amount_confidence,
         fields:response.currency.value::STRING                        AS doc_currency
  FROM ai.invoice_fields
  QUALIFY row_number() OVER (PARTITION BY coalesce(fields:response.invoice_id.value::STRING, path)
                             ORDER BY _ingested_at DESC) = 1
)
SELECT
  coalesce(i.invoice_id, f.doc_key)                 AS invoice_id,
  coalesce(i.business_unit, 'UNASSIGNED')           AS business_unit,
  f.path, f.doc_amount, f.amount_confidence, i.amount AS erp_amount,
  coalesce(i.first_seen_at, f._ingested_at)         AS detected_at,
  coalesce(
    i.invoice_id IS NULL
    OR abs(f.doc_amount - i.amount) > 0.01
    OR f.amount_confidence < 0.8
    OR f.doc_currency <> i.currency,
    true)                                           AS mismatch
FROM f
LEFT JOIN silver.invoices i ON i.invoice_id = f.doc_invoice_id;

-- Spend category per invoice, for policy routing (different policies govern travel, software, services).
CREATE OR REFRESH STREAMING TABLE ai.invoice_category
COMMENT 'ai_classify of the invoice line description into a spend category, with confidence and rationale.'
AS SELECT invoice_id, line_description, _ingested_at,
  ai_classify(
    line_description,
    '{"software": "Licences, subscriptions, cloud services",
      "professional_services": "Consulting, contractors, audit, legal",
      "travel": "Airfare, lodging, per diem, ground transport",
      "facilities": "Rent, utilities, maintenance, cleaning",
      "goods": "Physical goods, equipment, supplies"}',
    map('version', '2.1', 'enableConfidenceScores', 'true', 'enableRationales', 'true')
  ) AS category
FROM STREAM(bronze.invoices)          -- a streaming source must be append-only; silver is a materialized view
WHERE invoice_id IS NOT NULL AND line_description IS NOT NULL;

-- The agent's work list: three-way-match exceptions plus document mismatches, one schema.
CREATE OR REFRESH MATERIALIZED VIEW gold.open_exceptions
COMMENT 'Everything the agent must triage. exception_type is one of the keys in src/agent/policy.py ALLOWED. detected_at is the first arrival of the invoice or document.'
AS
SELECT exception_id, exception_type, invoice_id, twin_invoice_id, vendor_id, po_id, business_unit,
       invoice_amount, po_amount, received_amount, variance, detected_at
FROM gold.match_exceptions
UNION ALL
SELECT sha2(concat_ws('|', d.invoice_id, 'doc_mismatch'), 256), 'doc_mismatch', d.invoice_id, NULL,
       i.vendor_id, i.po_id, d.business_unit, coalesce(d.erp_amount, d.doc_amount, 0), NULL, NULL,   -- proposals.invoice_amount is NOT NULL
       round(d.doc_amount - d.erp_amount, 2), d.detected_at
FROM gold.document_checks d LEFT JOIN silver.invoices i ON i.invoice_id = d.invoice_id
WHERE d.mismatch;

How to read the result如何解读结果

  • `fields:error_message IS NULL` failing (the extracted expectation) means a document could not be read: scanned at low resolution, password protected, or not an invoice. These belong in a manual queue, not in a retry loop.`fields:error_message IS NULL`(即 extracted 期望规则)不通过,说明某份文档无法读取:扫描分辨率太低、有密码保护,或者根本不是发票。这些应该进入人工队列,而不是重试循环。
  • The mismatch rate on clean data should be low single digits. Above that, look at which field disagrees: total_amount disagreements with matching invoice ids are usually tax-inclusive versus tax-exclusive totals, a schema description problem.在干净数据上,不一致率应该在个位数的低端。超过这个水平时,看看是哪个字段不一致:发票号相同而 total_amount 不一致,通常是含税与不含税总额的问题,属于 schema 描述的问题。
  • Cost appears under the AI_FUNCTIONS product in system.billing.usage. Divide by documents processed: that is your cost per invoice for extraction, a number the business case needs.费用会出现在 system.billing.usage 的 AI_FUNCTIONS 产品下。用它除以处理的文档数,就得到每张发票的抽取成本,这是业务论证需要的数字。

Troubleshooting排障

You see现象Why原因Do this处理
The bill is far above estimate账单远超预估AI Functions ran in a materialized view and recomputed, or the pipeline was fully refreshed.AI Functions 跑在物化视图里并发生了重算,或者 pipeline 被全量刷新了。Keep AI Functions in streaming tables, and treat a full refresh of ai.* as a budgeted event that needs approval.把 AI Functions 放在流式表中,并把 ai.* 的全量刷新视为一次需要审批的预算事项。
AI Functions are not availableAI Functions 不可用Classic SQL warehouses do not support them, and the runtime must be 15.4 LTS or above.Classic SQL warehouse 不支持它们,运行时必须是 15.4 LTS 或以上。Run on serverless pipelines and serverless SQL warehouses.在 serverless pipeline 和 serverless SQL warehouse 上运行。
Join to silver finds nothing与 silver 的关联什么也找不到The extracted invoice id has a prefix or spacing the ERP does not.抽取出的发票号带有 ERP 中没有的前缀或空格。Normalize both sides (upper, strip non-alphanumerics) in the join, and say so in the column comment.在关联时对两边都做规范化(转大写、去掉非字母数字字符),并在列注释中写明。

How this scales如何扩展

  • The vendor page advises submitting the full dataset in one query rather than small batches: AI Functions parallelize and retry internally. Do not wrap them in your own batching loop.厂商页面建议把整个数据集放在一个查询里提交,而不是拆成小批:AI Functions 会在内部并行和重试。不要在外面再包一层自己的分批循环。
  • Backfills of historical invoices: run them as a separate, budgeted pipeline update, off-hours, after the sample has proven the schema.历史发票的回填:在样本验证过 schema 之后,作为单独的、有预算的 pipeline 更新,在非高峰时段运行。
Architecture review: questions you will be asked架构评审:你会被问到的问题
Why not let the agent read the PDF itself when it needs to?为什么不让智能体在需要时自己去读 PDF?

Because then each triage pays to read the document again, the result is not stored, and nobody can query "how many invoices disagree with the ERP". Extraction is data engineering: do it once, store it, govern it.因为那样每次分诊都要为再读一遍文档付费,结果不会被保存,也没人能查询“有多少张发票与 ERP 不一致”。抽取属于数据工程:做一次、存下来、纳入治理。

Done when完成标准On a 200-invoice sample, at least 98% of totals agree with the ERP, and every disagreement appears in gold.open_exceptions as doc_mismatch.在 200 张发票的样本上,至少 98% 的总额与 ERP 一致,每个不一致都以 doc_mismatch 出现在 gold.open_exceptions 中。
Not confirmed on a vendor page未在厂商页面上确认The advanced ai_extract schema is written as an object of field definitions with type, description and enum labels, following the vendor page's description; check the exact shape on the ai_extract reference before the first run. The variant paths (fields:response.total_amount.value) follow the documented return structure.高级 ai_extract schema 按厂商页面的描述,写成由字段定义(type、description、enum labels)组成的对象;首次运行前请在 ai_extract 参考页上核对确切结构。variant 路径(fields:response.total_amount.value)遵循文档中的返回结构。
09Classify spend categories, and measure the classifier per class对支出类别分类,并逐类衡量分类器
Builds构建内容ai.invoice_category with confidence and rationale, and a per-class precision and recall gate.带置信度和理由的 ai.invoice_category,以及逐类的精确率与召回率门槛。

Why this step, and why here为什么要做这一步,为什么在这里

Different policies govern travel, software and professional services, so the agent must know the category before it searches policy. ai_classify does that with labels you describe. But an overall accuracy hides the class that matters: if travel is 5% of invoices and is wrong half the time, accuracy is still 97% and every travel invoice is checked against the wrong policy. So the gate is per class, on enough labelled examples, with a confidence cut below which a person decides.差旅、软件和专业服务受不同政策约束,所以智能体在检索政策之前必须先知道类别。ai_classify 用你描述的标签来完成分类。但总体准确率会掩盖真正要紧的类别:如果差旅只占发票的 5%,却有一半分错,总体准确率仍有 97%,而每张差旅发票都会对照错误的政策检查。所以门槛是逐类的,基于足够数量的标注样本,并设一个置信度阈值,低于它就由人来决定。

What it does它做什么

The pipeline classifies each invoice line description into five categories with confidence and rationale. classifier_check.py computes per-class precision and recall against labels a person wrote, fails any class below 0.85 or with fewer than 30 labels, and finds the confidence cut that reaches 95% precision.pipeline 把每条发票行描述分到五个类别之一,并附带置信度和理由。classifier_check.py 对照人工编写的标签计算每个类别的精确率和召回率:任何类别低于 0.85 或标签少于 30 条都判为不通过,并找出能达到 95% 精确率的置信度阈值。

How to do it怎么做

  1. Have an AP clerk label 300 invoice lines into evals.category_labels, at least 30 per category.请一位应付账款人员把 300 条发票行标注到 evals.category_labels 中,每个类别至少 30 条。
  2. Run the SQL in the file's docstring and feed the rows to per_class(), gate() and confidence_cut().运行文件文档字符串中的 SQL,把结果行传给 per_class()、gate() 和 confidence_cut()。
  3. Improve label descriptions (they are the prompt) until the gate passes; then route predictions below the cut to a person.改进标签描述(它们就是提示词),直到通过门槛;然后把低于阈值的预测交给人处理。

Scripts脚本

src/evals/classifier_check.py · compiles
"""Step 9. Measure ai_classify against labels a person wrote, per class, before anything uses it.

An overall accuracy hides the class that matters. If 'travel' is 5% of invoices and the classifier
gets it wrong half the time, accuracy is still 97% and every travel invoice is checked against the
wrong policy. So the gate is per class: precision and recall each above a floor, on enough examples.

  SELECT c.invoice_id, c.category:response[0].value::string AS predicted,
         c.category:response[0].confidence_score::double AS confidence, l.label
  FROM fin_dev.ai.invoice_category c JOIN fin_dev.evals.category_labels l USING (invoice_id)
"""
from __future__ import annotations


def per_class(rows: list) -> dict:
    """rows: dicts with predicted, label. Returns {class: {precision, recall, support}}."""
    classes = sorted({r["label"] for r in rows} | {r["predicted"] for r in rows if r["predicted"]})
    out = {}
    for c in classes:
        tp = sum(1 for r in rows if r["predicted"] == c and r["label"] == c)
        fp = sum(1 for r in rows if r["predicted"] == c and r["label"] != c)
        fn = sum(1 for r in rows if r["predicted"] != c and r["label"] == c)
        out[c] = {"precision": round(tp / (tp + fp), 3) if tp + fp else 0.0,
                  "recall": round(tp / (tp + fn), 3) if tp + fn else 0.0,
                  "support": tp + fn}
    return out


def gate(stats: dict, floor: float = 0.85, min_support: int = 30) -> list:
    """Reasons the classifier may not be used. A class with too few labels is a failure, not a pass."""
    out = []
    for c, s in stats.items():
        if s["support"] < min_support:
            out.append(f"{c}: only {s['support']} labelled examples (need {min_support})")
            continue
        for k in ("precision", "recall"):
            if s[k] < floor:
                out.append(f"{c}: {k} {s[k]:.3f} below {floor}")
    return out


def confidence_cut(rows: list, target_precision: float = 0.95) -> float | None:
    """Lowest confidence at which predictions above it reach the target precision. Rows below the
    cut go to a person. None means no cut reaches the target."""
    for cut in [x / 100 for x in range(50, 100)]:
        kept = [r for r in rows if (r.get("confidence") or 0) >= cut]
        if kept and sum(1 for r in kept if r["predicted"] == r["label"]) / len(kept) >= target_precision:
            return cut
    return None
python
from evals.classifier_check import per_class, gate, confidence_cut
rows = spark.sql(QUERY).toPandas().to_dict("records")   # QUERY from the docstring
stats = per_class(rows)
print(stats)              # {'software': {'precision': 0.93, 'recall': 0.88, 'support': 64}, ...}
print(gate(stats))        # [] means usable
print(confidence_cut(rows, 0.95))   # e.g. 0.72: below this, a person decides

How to read the result如何解读结果

  • A class with high precision and low recall is being swallowed by a neighbour: look at which class its examples were predicted as, and sharpen both descriptions.精确率高而召回率低的类别正在被相邻类别“吞掉”:看看它的样本被预测成了哪个类别,然后把两个类别的描述都写得更清楚。
  • `only 4 labelled examples` is a failure, not a pass. A perfect score on four examples proves nothing.`only 4 labelled examples` 是不通过,不是通过。四个样本上的满分什么也证明不了。
  • The cut tells you the automation rate: the share of rows above it is what the agent gets without a person.阈值告诉你自动化率:高于阈值的行所占的比例,就是智能体无需人工就能拿到的部分。

Troubleshooting排障

You see现象Why原因Do this处理
One category absorbs everything ambiguous一个类别吞掉了所有模糊的样本Its description is the broadest ("goods" covers almost anything physical).它的描述最宽泛(“goods”几乎涵盖一切实物)。Narrow its description, or add an "other" label routed to a person, and re-measure; never tune labels on the evaluation sample itself.收窄它的描述,或者增加一个交给人处理的“other”标签,然后重新衡量;绝不要在评估样本本身上调标签。
Rationales cite words not in the description理由中引用了描述里没有的词The model filled in from general knowledge.模型用常识补全了内容。Treat rationales as hints for reviewers, never as evidence. The category is the output; the confidence decides who acts.把理由当作给审核人员的提示,绝不能当作证据。类别才是输出;置信度决定由谁来处理。

How this scales如何扩展

  • Relabel a fresh sample each quarter. Vendors and spend change; a classifier measured once drifts silently.每个季度重新标注一批新样本。供应商和支出结构会变;只测量过一次的分类器会悄悄漂移。
Architecture review: questions you will be asked架构评审:你会被问到的问题
Could the agent classify in its own prompt instead?能不能让智能体在自己的提示词里顺便分类?

It could, and then the category would be invisible, unmeasured and paid for on every triage. As a column it is measured once, queryable, and reused by dashboards and policy routing alike.可以,但那样类别就不可见、没有被衡量,而且每次分诊都要付费。作为一列数据,它只需衡量一次,可以查询,并被仪表盘和政策路由共同复用。

Done when完成标准Every category passes the per-class gate on at least 30 labels, and the confidence cut is written in the step's merge request.每个类别都在至少 30 条标签上通过逐类门槛,置信度阈值写在这一步的合并请求里。

4 Knowledge and tools知识与工具

The agent gets three ways to read, each governed by Unity Catalog: policy text through AI Search, numbers through Genie and the metric view, and exception facts through Unity Catalog functions. All three are reached through managed MCP endpoints, so the agent's code holds no SQL and no credentials, and every call runs under the same permissions as a person's query. Models are reached through the Unity Gateway, which is where rate limits, guardrails and usage logging live.智能体有三种读取方式,每种都受 Unity Catalog 治理:通过 AI Search 读政策文本,通过 Genie 和指标视图读数字,通过 Unity Catalog 函数读异常事实。三者都通过托管 MCP 端点访问,所以智能体代码里没有 SQL 也没有凭证,每次调用都与人的查询处于同样的权限之下。模型通过 Unity Gateway 访问,限流、护栏和用量日志都在那里。

10Index the payment policy in AI Search在 AI Search 中为付款政策建立索引
Builds构建内容ai.policy_chunks (heading path kept with each chunk) and the Delta Sync index ai.policy_index.ai.policy_chunks(每个文本块都保留标题路径)和 Delta Sync 索引 ai.policy_index。

Why this step, and why here为什么要做这一步,为什么在这里

A payment decision is defensible only if it cites the rule that permits it. Policy text changes rarely, is read constantly, and must be found by meaning ("can we pay a small overcharge") and by exact token ("section 4.2"). A managed index with hybrid search does both, follows the Delta table automatically, and is permissioned like a table. Chunking keeps the heading path with every chunk, the module 5 lesson: a paragraph cut out of its section loses what it is about.只有引用了允许它的那条规则,付款决定才站得住脚。政策文本很少变化,却经常被读取,而且既要能按意思找到(“小额多收能不能付”),也要能按精确词找到(“第 4.2 节”)。支持混合检索的托管索引两者都能做到,它会自动跟随 Delta 表,并且像表一样受权限控制。切块时为每个文本块保留标题路径,这是第 5 模块的教训:从所在章节中切出来的段落,会丢失它在讲什么。

What it does它做什么

`build` parses every policy PDF with ai_parse_document, turns its elements into chunks with a heading path, and writes ai.policy_chunks with change data feed. `index` creates the endpoint and a TRIGGERED Delta Sync index with managed embeddings on context plus text. `sync` runs after each build. `query` shows the top five hybrid results.`build` 用 ai_parse_document 解析每个政策 PDF,把其中的元素切成带标题路径的文本块,写入开启了 change data feed 的 ai.policy_chunks。`index` 创建 endpoint 以及基于上下文加文本、使用托管 embedding 的 TRIGGERED 模式 Delta Sync 索引。`sync` 在每次 build 之后运行。`query` 显示混合检索的前五条结果。

How to do it怎么做

  1. Upload the policy PDFs to /Volumes/<catalog>/landing/policy. Only approved, current versions: the index will cite whatever is there.把政策 PDF 上传到 /Volumes/<catalog>/landing/policy。只放已批准的当前版本:索引会引用那里的任何东西。
  2. `python policy_index.py build --catalog fin_dev`, then `index`, then wait for the index to be ready, then `query ... "price variance tolerance"`.依次执行 `python policy_index.py build --catalog fin_dev`、`index`,等索引就绪后,再执行 `query ... "price variance tolerance"`。
  3. Write ten policy questions with the chunk a person says answers each; check hit@3 with the parity method from the replication page.写十个政策问题,并由人标出每个问题的答案所在的文本块;用复刻页面上的一致性方法检查 hit@3。
  4. The weekly policy_refresh job (resources/jobs.yml) rebuilds and syncs.每周运行的 policy_refresh job(resources/jobs.yml)会重建并同步。

Scripts脚本

src/knowledge/policy_index.py · compiles
"""Step 10. Policy documents -> parsed elements -> chunks (Delta, change data feed) -> AI Search index.

  python policy_index.py build  --catalog fin_dev      # parse new policy files, rebuild chunks
  python policy_index.py index  --catalog fin_dev      # create the endpoint and Delta Sync index once
  python policy_index.py sync   --catalog fin_dev      # after each build (TRIGGERED pipeline)
  python policy_index.py query  --catalog fin_dev "late fee waiver"

chunk_elements() is pure and tested. It keeps a heading path with every chunk, the lesson from the
local build: "Section 5" means nothing once a paragraph is cut out of its document.
"""
from __future__ import annotations

import argparse
import json
import os

ENDPOINT = os.environ.get("AGENT_SEARCH_ENDPOINT", "spend_policy")
EMBEDDING = os.environ.get("AGENT_EMBEDDING", "databricks-qwen3-embedding-0-6b")
HEADING_TYPES = {"title", "section_header", "page_header"}
SKIP_TYPES = {"page_footer", "page_number"}


def chunk_elements(source: str, elements: list, max_chars: int = 1500) -> list:
    """elements: ai_parse_document document.elements (dicts with type, content). Returns chunk dicts."""
    chunks, path, buf = [], [], []

    def flush():
        text = "\n".join(buf).strip()
        if text:
            n = len(chunks)
            chunks.append({"chunk_id": f"{source}::{n}", "source": source, "chunk_index": n,
                           "context": " > ".join(path), "text": text,
                           "embed_text": (" > ".join(path) + "\n" + text).strip()})
        buf.clear()

    for el in elements:
        kind = (el.get("type") or "").lower()
        content = (el.get("content") or "").strip()
        if not content or kind in SKIP_TYPES:
            continue
        if kind in HEADING_TYPES:
            flush()
            path[:] = [content] if kind == "title" else (path[:1] + [content])
            continue
        if sum(len(b) for b in buf) + len(content) > max_chars:
            flush()
        buf.append(content)
    flush()
    return chunks


def build(catalog: str) -> None:  # pragma: no cover - runs on Databricks
    from pyspark.sql import SparkSession

    spark = SparkSession.builder.getOrCreate()
    parsed = spark.sql(f"""
        SELECT path, to_json(ai_parse_document(content, map('version', '2.0'))) AS doc
        FROM READ_FILES('/Volumes/{catalog}/landing/policy', format => 'binaryFile')""")
    rows = []
    for r in parsed.toLocalIterator():
        doc = json.loads(r["doc"])
        source = r["path"].split("/landing/policy/", 1)[-1]
        rows += chunk_elements(source, doc.get("document", {}).get("elements", []))
    df = spark.createDataFrame(rows, "chunk_id string, source string, chunk_index int, context string, text string, embed_text string")
    table = f"{catalog}.ai.policy_chunks"
    df.write.mode("overwrite").option("overwriteSchema", "true").saveAsTable(table)
    spark.sql(f"ALTER TABLE {table} SET TBLPROPERTIES (delta.enableChangeDataFeed = true)")
    print(f"policy chunks: {len(rows)} from {df.select('source').distinct().count()} documents")


def index(catalog: str) -> None:  # pragma: no cover
    from databricks.ai_search.client import AISearchClient

    c = AISearchClient()
    try:
        c.create_endpoint(name=ENDPOINT, endpoint_type="STANDARD")
    except Exception as e:                              # noqa: BLE001 - usually "already exists"
        print("endpoint:", str(e)[:120])
    c.create_delta_sync_index(endpoint_name=ENDPOINT, source_table_name=f"{catalog}.ai.policy_chunks",
                              index_name=f"{catalog}.ai.policy_index", pipeline_type="TRIGGERED",
                              primary_key="chunk_id", embedding_source_column="embed_text",
                              embedding_model_endpoint_name=EMBEDDING)
    print("index requested")


def sync(catalog: str) -> None:  # pragma: no cover
    from databricks.ai_search.client import AISearchClient
    AISearchClient().get_index(index_name=f"{catalog}.ai.policy_index").sync()
    print("sync started")


def query(catalog: str, text: str) -> None:  # pragma: no cover
    from databricks.ai_search.client import AISearchClient
    idx = AISearchClient().get_index(index_name=f"{catalog}.ai.policy_index")
    res = idx.similarity_search(query_text=text, columns=["chunk_id", "context", "text"], num_results=5,
                                query_type="hybrid")
    for row in res.get("result", {}).get("data_array", []):
        print(row[0], "|", row[1], "|", str(row[2])[:100])


if __name__ == "__main__":  # pragma: no cover
    ap = argparse.ArgumentParser()
    ap.add_argument("cmd", choices=["build", "index", "sync", "query"])
    ap.add_argument("text", nargs="*")
    ap.add_argument("--catalog", required=True)
    a = ap.parse_args()
    {"build": build, "index": index, "sync": sync}.get(a.cmd, lambda c: query(c, " ".join(a.text)))(a.catalog)

How to read the result如何解读结果

  • `policy chunks: 180 from 6 documents` is the shape to expect for a policy set. Very few chunks per document means headings were not detected (scanned PDFs); very many means a table of contents was chunked.`policy chunks: 180 from 6 documents` 是一套政策文档应有的规模。每份文档的块很少,说明没识别出标题(扫描版 PDF);块非常多,说明目录页也被切块了。
  • In query results, the context column should read like a breadcrumb (`Payment Policy > 4.2 Price variance`). If it is empty, the agent's citations will be unreadable to a reviewer.在查询结果中,context 列应该读起来像一条导航路径(`Payment Policy > 4.2 Price variance`)。如果是空的,智能体的引用对审核人员来说就无法阅读。

Troubleshooting排障

You see现象Why原因Do this处理
Index creation fails: change data feed required创建索引失败:需要 change data feedThe overwrite in build recreated the table without the property.build 中的覆盖写入重建了表,但没带这个属性。build sets the property after each write; if you changed it, keep the ALTER TABLE line.build 在每次写入后都会设置该属性;如果你改过代码,要保留 ALTER TABLE 那一行。
Old policy text keeps being cited旧的政策文本还在被引用A superseded PDF is still in the volume.被取代的 PDF 还留在 volume 里。Policy retirement is a publishing step: move the old file out, rebuild, sync. The index cites only what is present.政策下线是一个发布步骤:把旧文件移出去,重建,同步。索引只引用现有的内容。

How this scales如何扩展

  • Thousands of documents: still a standard endpoint. Hundreds of millions of vectors (for example all contracts): a storage-optimized endpoint, which supports Triggered sync only and costs less per vector.几千份文档:仍用 STANDARD 端点。数亿个向量(比如全部合同):用 storage-optimized 端点,它只支持 Triggered 同步,但每个向量的成本更低。
  • Many workflows share one policy index, filtered by a document-type column; do not build one index per agent.多个工作流共享一个政策索引,用文档类型列过滤;不要每个智能体各建一个索引。
Architecture review: questions you will be asked架构评审:你会被问到的问题
Why not paste the whole policy into the prompt?为什么不把整份政策直接贴进提示词?

It is paid on every call, it dilutes attention, and it cannot cite a chunk id a reviewer can open. Retrieval makes the citation a pointer, which is what makes the proposal reviewable.那样每次调用都要付费,会分散注意力,而且无法引用审核人员能打开的文本块 id。检索让引用成为一个指针,正是这一点让提议变得可以审核。

Done when完成标准Hybrid queries return the right policy chunk in the top three for at least nine of ten hand-written questions.对十个人工编写的问题,至少有九个的正确政策文本块出现在混合检索的前三条结果中。
11A Genie space over gold, benchmarked like code在 gold 上建 Genie space,并像代码一样做基准测试
Builds构建内容A Genie space on the metric view and gold tables, with instructions, sample SQL, and a benchmark that runs in CI.基于指标视图和 gold 表的 Genie space,带有说明、示例 SQL,以及在 CI 中运行的基准测试。

Why this step, and why here为什么要做这一步,为什么在这里

The agent sometimes needs numbers nobody wrote a function for ("how many duplicate suspects did this vendor have this year"). Genie turns a question into SQL over governed tables, under the asker's permissions. It is also what reviewers and managers will use directly. But Genie's quality depends on comments, instructions and sample queries, and those change, so it is benchmarked: questions with SQL an analyst agrees is correct, compared by result, not by SQL text.智能体有时需要一些没人为之写过函数的数字(“这个供应商今年有多少条重复嫌疑”)。Genie 把问题转换为针对受治理表的 SQL,并以提问者的权限执行。审核人员和经理也会直接使用它。但 Genie 的质量取决于注释、说明和示例查询,而这些会变,所以要做基准测试:问题配上分析师认可的正确 SQL,按结果比较,而不是按 SQL 文本比较。

What it does它做什么

benchmark.py asks each question through the Genie Conversation API, runs Genie's SQL and the reference SQL on the same warehouse, and compares result sets ignoring row order and number formatting. It exits non-zero below 90% accuracy, so the quality job fails when Genie regresses.benchmark.py 通过 Genie Conversation API 提出每个问题,在同一个 warehouse 上分别运行 Genie 生成的 SQL 和参考 SQL,并在忽略行顺序和数字格式的前提下比较结果集。准确率低于 90% 时以非零状态退出,这样 Genie 退化时质量检查 job 就会失败。

How to do it怎么做

  1. Create the space in the UI on gold.exception_metrics, gold.open_exceptions and silver.vendors. Add instructions (what an exception is, which currency rule applies) and three sample queries.在界面中基于 gold.exception_metrics、gold.open_exceptions 和 silver.vendors 创建 space。加上说明(什么是异常、适用哪条币种规则)和三个示例查询。
  2. Write 20 benchmark questions with a finance analyst. Four examples are in genie_benchmarks.json.与一位财务分析师一起写 20 个基准问题。genie_benchmarks.json 里有四个示例。
  3. Set genie_space_id in the bundle variables, and run the benchmark before any agent uses the space.在 bundle 变量中设置 genie_space_id,并在任何智能体使用这个 space 之前运行基准测试。
  4. The agent reaches the space through the managed MCP endpoint `/api/2.0/mcp/genie/<space_id>`.智能体通过托管 MCP 端点 `/api/2.0/mcp/genie/<space_id>` 访问这个 space。

Scripts脚本

src/genie/benchmark.py · compiles
"""Step 11. Benchmark the Genie space before any agent or person relies on it.

Each benchmark is a question plus the SQL a finance analyst agrees is correct. The script asks Genie
the question through the Conversation API, runs Genie's SQL and the reference SQL on the same
warehouse, and compares the result sets. Genie's built-in benchmarks do the same in the UI; this
version runs in CI, so a change to a table comment or an instruction cannot silently break answers.

  python benchmark.py --space-id <id> --warehouse-id <id> --file genie_benchmarks.json
"""
from __future__ import annotations

import argparse
import json
import os
import time
from decimal import Decimal


def _norm_cell(v):
    if v is None:
        return None
    try:
        return round(float(Decimal(str(v))), 2)            # 1250, "1250.00" and 1250.0 are the same answer
    except Exception:                                       # noqa: BLE001
        return str(v).strip().lower()


def same_result(a: list, b: list) -> bool:
    """Row sets equal ignoring row order, column names, and numeric formatting."""
    norm = lambda rows: sorted(tuple(_norm_cell(c) for c in r) for r in rows)  # noqa: E731
    return norm(a) == norm(b)


def score(results: list) -> dict:
    n = len(results)
    ok = sum(1 for r in results if r["match"])
    return {"questions": n, "correct": ok, "accuracy": round(ok / n, 3) if n else 0.0,
            "failed": [r["question"] for r in results if not r["match"]]}


def _run_sql(w, warehouse_id: str, sql: str) -> list:  # pragma: no cover
    res = w.statement_execution.execute_statement(statement=sql, warehouse_id=warehouse_id, wait_timeout="50s")
    return (res.result.data_array or []) if res.result else []


def ask(w, space_id: str, question: str):  # pragma: no cover
    """Genie's SQL for a question, or None if it answered in text only."""
    msg = w.genie.start_conversation_and_wait(space_id, question)
    for att in msg.attachments or []:
        q = getattr(att, "query", None)
        if q is not None and getattr(q, "query", None):
            return q.query
    return None


def main() -> None:  # pragma: no cover
    from databricks.sdk import WorkspaceClient

    ap = argparse.ArgumentParser()
    ap.add_argument("--space-id", required=True)
    ap.add_argument("--warehouse-id", required=True)
    ap.add_argument("--file", required=True)
    ap.add_argument("--min-accuracy", type=float, default=0.9)
    ap.add_argument("--catalog", default="fin_dev", help="reference SQL is written for fin_dev; substituted here")
    a = ap.parse_args()
    import sys
    sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    from common.apply_sql import for_catalog
    w = WorkspaceClient()
    results = []
    path = a.file if os.path.isabs(a.file) else os.path.join(os.path.dirname(os.path.abspath(__file__)), a.file)
    for b in json.load(open(path)):
        t0 = time.time()
        sql = ask(w, a.space_id, b["question"])
        got = _run_sql(w, a.warehouse_id, sql) if sql else []
        want = _run_sql(w, a.warehouse_id, for_catalog(b["sql"], a.catalog))
        results.append({"question": b["question"], "match": bool(sql) and same_result(got, want),
                        "seconds": round(time.time() - t0, 1), "genie_sql": sql})
        print(f"{'PASS' if results[-1]['match'] else 'FAIL'} {results[-1]['seconds']:5.1f}s  {b['question']}")
    s = score(results)
    print(json.dumps(s, indent=2))
    raise SystemExit(0 if s["accuracy"] >= a.min_accuracy else 1)


if __name__ == "__main__":  # pragma: no cover
    main()
src/genie/genie_benchmarks.json · json parses
[
  {"question": "How many open exceptions are there by business unit?",
   "sql": "SELECT business_unit, count(*) FROM fin_dev.gold.open_exceptions GROUP BY business_unit"},
  {"question": "What is the total invoice value held by duplicate suspects?",
   "sql": "SELECT sum(invoice_amount) FROM fin_dev.gold.open_exceptions WHERE exception_type = 'duplicate_suspect'"},
  {"question": "Which five vendors have the most open exceptions?",
   "sql": "SELECT vendor_id, count(*) AS n FROM fin_dev.gold.open_exceptions GROUP BY vendor_id ORDER BY n DESC LIMIT 5"},
  {"question": "What is the net price variance for each business unit?",
   "sql": "SELECT business_unit, sum(variance) FROM fin_dev.gold.open_exceptions WHERE exception_type = 'price_variance' GROUP BY business_unit"}
]

How to read the result如何解读结果

  • `FAIL 6.2s Which five vendors have the most open exceptions?` with Genie's SQL printed: compare it with the reference. Usually a missing instruction (ties, or which status counts as open), fixed in the space, not in the benchmark.出现 `FAIL 6.2s Which five vendors have the most open exceptions?` 并打印出 Genie 的 SQL 时:把它与参考 SQL 对比。通常是缺了某条说明(并列怎么处理,哪种状态算未结),要在 space 里修,而不是改基准。
  • Seconds per question matter for the agent's latency budget. A Genie call of 6 to 10 seconds is one third of a 30-second p95; prefer a UC function for questions the agent asks on every triage.每个问题耗时多少,关系到智能体的延迟预算。一次 6 到 10 秒的 Genie 调用就占了 30 秒 p95 的三分之一;对于智能体每次分诊都会问的问题,优先用 UC 函数。

Troubleshooting排障

You see现象Why原因Do this处理
Genie answers in text with no SQLGenie 只用文字回答,没有 SQLThe question was ambiguous or outside the space's tables.问题有歧义,或者超出了 space 中的表。ask() returns None and the benchmark counts it as a failure. Rephrase the benchmark only if a person would also find it ambiguous.ask() 返回 None,基准测试会把它算作失败。只有当人也觉得有歧义时,才改写基准问题。
Results match but the benchmark fails结果一样,但基准测试判为失败Column order differs.列的顺序不同。same_result ignores row order and formatting but not column order; select columns in the same order in the reference SQL.same_result 会忽略行顺序和格式,但不忽略列顺序;在参考 SQL 中按同样的顺序选择列。

How this scales如何扩展

  • One space per subject area, not one per agent. Ten agents can share the finance space; each benchmark question protects all of them.每个主题领域一个 space,而不是每个智能体一个。十个智能体可以共享财务这个 space;每个基准问题都同时保护着它们。
Architecture review: questions you will be asked架构评审:你会被问到的问题
Text-to-SQL is risky. Why give it to an agent that proposes payments?Text-to-SQL 有风险,为什么交给一个会提议付款的智能体?

It reads under Unity Catalog permissions and never writes, and the agent's figures are checked against the evidence before a proposal is queued. Genie is for context; the decision facts come from get_exception, a fixed function.它在 Unity Catalog 权限下只读、从不写入,而且智能体给出的数字在提议进入队列之前都要对照证据检查。Genie 用来提供背景;决策所依据的事实来自 get_exception 这个固定函数。

Done when完成标准At least 18 of 20 benchmark questions pass, and the benchmark runs nightly in the quality job.20 个基准问题中至少 18 个通过,并且基准测试每晚在质量检查 job 中运行。
Not confirmed on a vendor page未在厂商页面上确认The attachment shape read by ask() (attachments[].query.query) follows the Conversation API as used in community examples; check one response object before relying on it.ask() 读取的附件结构(attachments[].query.query)参照的是社区示例中的 Conversation API 用法;依赖它之前请先检查一个响应对象。
12Read tools as Unity Catalog functions把读取工具做成 Unity Catalog 函数
Builds构建内容tools.get_exception and tools.vendor_history, returning JSON with a diagnostic when nothing matches.tools.get_exception 和 tools.vendor_history,返回 JSON;匹配不到时附带诊断信息。

Why this step, and why here为什么要做这一步,为什么在这里

The facts a decision rests on must come from a fixed, reviewed query, not from a model writing SQL. A Unity Catalog SQL function is that query, permissioned like a table: the row filter applies inside it (the agent's principal is in fin-agents, which the policy covers), so the agent cannot see an exception outside its scope even if it asks for one by id. The COMMENT is the tool description the model reads, and the empty case returns found=false with a reason, the module 6 rule that stops a model reporting a zero as a fact.决策所依据的事实,必须来自一个固定的、经过审查的查询,而不是模型自己写的 SQL。Unity Catalog SQL 函数就是这样的查询,并且像表一样受权限控制:行过滤在函数内部同样生效,所以即使智能体按 id 去要,也看不到其范围之外的异常。COMMENT 就是模型读到的工具说明;空结果会返回 found=false 及原因,这是第 6 模块的规则,防止模型把零当作事实报告。

What it does它做什么

get_exception returns every fact for one exception as JSON: amounts, variance, the document check and the spend category. vendor_history returns twelve months of exceptions by type and total variance. Both are granted to reviewers and reached by the agent through the managed MCP endpoint for the tools schema.get_exception 以 JSON 返回一个异常的全部事实:金额、差异、文档核对结果和支出类别。vendor_history 返回过去十二个月按类型统计的异常数和总差异。两者都授权给审核人员,智能体通过 tools schema 的托管 MCP 端点访问它们。

How to do it怎么做

  1. Run functions.sql per environment (replace fin_dev).在每个环境运行 functions.sql(替换 fin_dev)。
  2. Run the two test SELECTs at the end: a real id returns found=true, a fake one returns found=false with a diagnostic.运行文件末尾的两条测试 SELECT:真实 id 返回 found=true,伪造的 id 返回 found=false 并附诊断信息。
  3. Grant EXECUTE on the tools schema and SELECT on gold and ai to the agent app's service principal after it exists (step 18 creates it).在智能体 App 的服务主体创建之后(第 18 步会创建它),向它授予 tools schema 的 EXECUTE,以及 gold 和 ai 的 SELECT。

Scripts脚本

src/tools/functions.sql · sqlglot databricks: 6/6 statements parsed
-- Step 12. Read tools as Unity Catalog SQL functions. The agent reaches them through the managed MCP
-- endpoint for functions, and every call runs with Unity Catalog permissions. The agent's principal is
-- in fin-agents, so the business-unit row filter from step 4 applies to it exactly as to a reviewer.
-- Written for fin_dev; CI applies it to stg and prd with src/common/apply_sql.py.
-- The COMMENTs are the tool descriptions the model reads. Write them for a model: what it returns,
-- in which units, and what an empty answer means.

CREATE OR REPLACE FUNCTION fin_dev.tools.get_exception(exception_id STRING COMMENT 'The exception_id from gold.open_exceptions')
RETURNS STRING
COMMENT 'All facts for one exception as JSON: type, invoice, PO, receipts, amounts, variance, the document check, the spend category. Returns {"found": false, "diagnostic": ...} if the id is unknown or outside your business units.'
RETURN
  SELECT coalesce(
    (SELECT to_json(named_struct(
        'found', true,
        'exception_id', e.exception_id, 'exception_type', e.exception_type,
        'invoice_id', e.invoice_id, 'twin_invoice_id', e.twin_invoice_id,
        'vendor_id', e.vendor_id, 'po_id', e.po_id, 'business_unit', e.business_unit,
        'invoice_amount', e.invoice_amount, 'po_amount', e.po_amount,
        'received_amount', e.received_amount, 'variance', e.variance,
        'doc_amount', d.doc_amount, 'doc_confidence', d.amount_confidence,
        'spend_category', c.category:response[0].value::STRING))
     FROM fin_dev.gold.open_exceptions e
     LEFT JOIN fin_dev.gold.document_checks d ON d.invoice_id = e.invoice_id
     LEFT JOIN (SELECT invoice_id, max_by(category, _ingested_at) AS category      -- the latest classification
                FROM fin_dev.ai.invoice_category GROUP BY invoice_id) c ON c.invoice_id = e.invoice_id
     WHERE e.exception_id = get_exception.exception_id
     LIMIT 1),
    to_json(named_struct('found', false, 'diagnostic',
      'no open exception with this id that you may see; it may be resolved, mistyped, or in another business unit')));

CREATE OR REPLACE FUNCTION fin_dev.tools.vendor_history(vendor_id STRING COMMENT 'Vendor id from the exception')
RETURNS STRING
COMMENT 'Twelve-month exception history for one vendor as JSON: counts by type and total variance. Use it to judge whether an exception is a pattern.'
RETURN
  SELECT to_json(named_struct(
    'vendor_id', vendor_history.vendor_id,
    'risk_tier', (SELECT max(risk_tier) FROM fin_dev.silver.vendors v WHERE v.vendor_id = vendor_history.vendor_id),
    'by_type', (SELECT map_from_entries(collect_list(struct(exception_type, n)))
                FROM (SELECT exception_type, count(*) AS n FROM fin_dev.gold.open_exceptions e
                      WHERE e.vendor_id = vendor_history.vendor_id
                        AND e.detected_at >= current_timestamp() - INTERVAL 365 DAYS
                      GROUP BY exception_type)),
    'total_variance', (SELECT round(coalesce(sum(variance), 0), 2) FROM fin_dev.gold.open_exceptions e
                       WHERE e.vendor_id = vendor_history.vendor_id)));

GRANT EXECUTE ON FUNCTION fin_dev.tools.get_exception  TO `fin-reviewers`, `fin-agents`;
GRANT EXECUTE ON FUNCTION fin_dev.tools.vendor_history TO `fin-reviewers`, `fin-agents`;

-- Try them. The second call must return found=false with a diagnostic, never an error or an empty string.
SELECT fin_dev.tools.get_exception((SELECT exception_id FROM fin_dev.gold.open_exceptions LIMIT 1));
SELECT fin_dev.tools.get_exception('no-such-id');

How to read the result如何解读结果

  • Run get_exception as two reviewers from different units with the same id. One gets the facts, the other gets found=false. That is the row filter working inside the tool.以来自不同单元的两位审核人员身份,用同一个 id 调用 get_exception。一个拿到事实,另一个得到 found=false。这就是行过滤在工具内部起作用。
  • A diagnostic that says "outside your business units" leaks nothing: it does not say whether the id exists.诊断信息说“不在你的业务单元范围内”并不会泄露任何东西:它没有透露这个 id 是否存在。

Troubleshooting排障

You see现象Why原因Do this处理
The model calls get_exception with an invoice id模型用发票号调用 get_exceptionThe parameter COMMENT does not say which id it wants.参数的 COMMENT 没有说明它需要的是哪种 id。Say "the exception_id from gold.open_exceptions, a 64-character hash" in the COMMENT; the diagnostic then tells the model what went wrong.在 COMMENT 中写明“gold.open_exceptions 中的 exception_id,一个 64 位哈希”;这样诊断信息就能告诉模型哪里出错了。
The function returns an error instead of found=false函数报错,而不是返回 found=falseA scalar subquery returned more than one row.某个标量子查询返回了多于一行。Keep LIMIT 1 and the max_by aggregation on categories; one invoice can have several category rows from re-extracts.保留 LIMIT 1 以及对类别的 max_by 聚合;由于重新抽取,一张发票可能有多条类别记录。

How this scales如何扩展

  • Tools are shared assets. A second agent that needs exception facts calls the same function; changes go through the same review, and every caller benefits.工具是共享资产。第二个需要异常事实的智能体调用同一个函数;修改走同样的审查流程,所有调用方都受益。
Architecture review: questions you will be asked架构评审:你会被问到的问题
Why is there no write tool?为什么没有写入工具?

Because a model holding a write tool is one prompt injection away from writing. The agent returns a structured proposal; code checks it and writes it to the queue. The write path has no model in it.因为持有写入工具的模型,离被提示词注入后执行写入只有一步之遥。智能体返回一个结构化提议;由代码检查后写入队列。写入路径上没有模型。

Done when完成标准Both functions return valid JSON for real and fake ids, under each reviewer's scope.两个函数对真实和伪造的 id 都返回有效 JSON,并且遵循每位审核人员的范围。
Not confirmed on a vendor page未在厂商页面上确认The vendor page lists function URLs per function (/api/2.0/mcp/functions/<catalog>/<schema>/<function>), marks these workspace MCP endpoints as legacy, and recommends the Unity Gateway MCP path for new connections. The schema-level URL in spend_agent.py is an assumption: if it is refused, list one URL per function or use the Unity Gateway path.厂商页面按函数列出 URL(/api/2.0/mcp/functions/<catalog>/<schema>/<function>),把这些工作区 MCP 端点标为旧版,并建议新连接使用 Unity Gateway MCP 路径。spend_agent.py 中的 schema 级 URL 是一个假设:如果被拒绝,就为每个函数各列一个 URL,或改用 Unity Gateway 路径。
13Models through the Unity Gateway: limits, guardrails, logs通过 Unity Gateway 访问模型:限流、护栏、日志
Builds构建内容The agent's model endpoint behind the gateway, with a per-principal rate limit, guardrail policies, usage tracking and an inference table.智能体的模型端点位于网关之后,带有按主体的限流、护栏策略、用量追踪和推理表。

Why this step, and why here为什么要做这一步,为什么在这里

Every model call in the workflow should pass one point where it is counted, limited and logged. Without it, a loop in the batch job spends a month's budget overnight and nobody can say which workload did it. The gateway also lets you change the model behind a stable name, which is how a model upgrade becomes a reviewed, evaluated change instead of a surprise.工作流中的每一次模型调用,都应该经过一个可以计数、限流和记录的点。没有它,批处理 job 里的一个循环就能在一夜之间花掉一个月的预算,而且没人说得清是哪个工作负载干的。网关还允许你在一个稳定的名字背后更换模型,这样模型升级就成为一次经过审查和评估的变更,而不是意外。

What it does它做什么

Configured in the Unity Gateway UI for the endpoint the agent uses: a rate limit for the agent's service principal and a lower one for people, guardrail policies, usage tracking, and an inference table in the ops schema. The agent's client uses the gateway (`use_ai_gateway=True`).在 Unity Gateway 界面中为智能体使用的端点进行配置:为智能体的服务主体设一个限流,为个人设一个更低的限流,加上护栏策略、用量追踪,以及 ops schema 中的推理表。智能体的客户端通过网关调用(`use_ai_gateway=True`)。

How to do it怎么做

  1. Pick the model by measurement: run the replication page's bench script against two or three candidate endpoints, at a busy hour.通过测量来选模型:在繁忙时段,用复刻页面上的基准脚本测试两到三个候选端点。
  2. Set the rate limit from the load test (step 21): the knee's throughput, not a round number.根据负载测试(第 21 步)设定限流:取拐点处的吞吐量,而不是一个整数。
  3. Enable the inference table and usage tracking; send one request and wait a few minutes before checking.开启推理表和用量追踪;发送一个请求,等几分钟再检查。
  4. Pin the model name in the bundle variable agent_model. A change is a merge request that runs the eval gate.在 bundle 变量 agent_model 中固定模型名称。任何更改都是一个会触发评估门槛的合并请求。

Scripts脚本

gateway probe
from databricks_openai import DatabricksOpenAI
c = DatabricksOpenAI()
r = c.chat.completions.create(model="databricks-claude-sonnet-5-5",
                              messages=[{"role": "user", "content": "Reply with the word ok."}], max_tokens=5)
print(r.choices[0].message.content, r.usage)      # appears in gateway usage and the inference table

How to read the result如何解读结果

  • 429 from the gateway with low traffic means a limit was set too low for batch work: the batch principal and people need different limits.流量不高却收到网关的 429,说明为批处理工作设的限额太低:批处理主体和个人需要不同的限额。
  • The inference table is your request log. Its row count per day should match the triage count times the agent's average model calls per triage; a jump in the ratio is a loop.推理表就是你的请求日志。它每天的行数应该等于分诊次数乘以每次分诊的平均模型调用次数;这个比值突然跳升,说明出现了循环。

Troubleshooting排障

You see现象Why原因Do this处理
Model endpoint retired模型端点被下线Pay-per-token models have retirement dates on the supported-models page.按 token 计费的模型在支持模型页面上有下线日期。Check the page monthly; upgrade through a merge request with the eval gate, before the date.每月查看一次该页面;在下线日期之前,通过带评估门槛的合并请求完成升级。
No rows in the inference table推理表中没有数据The client is not using the gateway, or rows are delayed.客户端没有走网关,或者数据有延迟。Keep use_ai_gateway=True in the agent's client; wait several minutes before concluding.在智能体的客户端中保持 use_ai_gateway=True;等几分钟再下结论。

How this scales如何扩展

  • Pay-per-token is shared capacity: fine for a pilot, variable under load. For a production SLO, provisioned throughput gives reserved capacity for one model; size it from the load test.按 token 计费使用的是共享容量:适合试点,负载下表现会波动。若要满足生产 SLO,预置吞吐量会为一个模型保留容量;根据负载测试确定规模。
  • AI Functions in the pipeline should use Databricks-hosted pay-per-token endpoints (the vendor recommends them for batch), not the provisioned endpoint the interactive agent depends on.pipeline 中的 AI Functions 应使用 Databricks 托管的按 token 计费端点(厂商推荐它们用于批处理),而不是交互式智能体所依赖的预置端点。
Architecture review: questions you will be asked架构评审:你会被问到的问题
Why one model and not a router across five?为什么只用一个模型,而不是在五个模型之间路由?

Every model added is another eval to run and another behaviour to explain. Add a second model only when the eval shows a cheaper one matches on a class of exceptions; then route that class, and measure it.每增加一个模型,就多一套要运行的评估、多一种要解释的行为。只有当评估表明某个更便宜的模型在某类异常上表现相当时,才增加第二个模型;然后只路由那一类,并对它进行衡量。

Done when完成标准A probe call appears in gateway usage and the inference table, and the batch principal has its own limit.一次探测调用出现在网关用量和推理表中,批处理主体有了自己的限额。
Not confirmed on a vendor page未在厂商页面上确认Rate-limit fields, guardrail policy configuration and the inference table schema are set in the UI and were not shown on the gateway page read for this guide.限流字段、护栏策略配置和推理表结构都在界面中设置,本指南阅读的网关页面没有展示这些。

5 The agent and the human in the loop智能体与人在回路

The agent reads through governed tools and proposes one structured resolution. Code, not the model, decides whether the proposal is admissible and writes it to a review queue. A person decides in a Databricks App that sees data as that person. This split is what makes the workflow auditable: every payment-affecting step has a named human, a rule, or a test behind it.智能体通过受治理的工具读取信息,并提出一个结构化的处置建议。决定提议是否可接受并把它写入审核队列的是代码,而不是模型。最终由人在一个以其本人身份查看数据的 Databricks App 中作出决定。正是这种分工让工作流可以审计:每个会影响付款的步骤背后,都有一个具名的人、一条规则或一项测试。

14Build the agent: tools via MCP, structured output, code-side checks构建智能体:通过 MCP 使用工具、结构化输出、代码侧检查

Why this step, and why here为什么要做这一步,为什么在这里

The model is good at reading evidence and writing a rationale; it is not a control. So the design gives it read tools only, asks for one structured answer, and puts the controls in code: the action must be allowed for the exception type, payment-affecting actions must cite policy, every figure in the rationale must be in the evidence, and low confidence must escalate. A failing proposal gets the reasons and one retry, then becomes an escalation with the reasons attached. That is the local answer guard, applied to a decision.模型擅长阅读证据和撰写理由,但它不是控制措施。所以这个设计只给它读取工具,要求它给出一个结构化答案,并把控制放在代码里:动作必须是该异常类型允许的,影响付款的动作必须引用政策,理由中的每个数字都必须出现在证据里,置信度低就必须升级处理。不合格的提议会收到原因并获得一次重试机会,然后变成一条附有原因的升级处理。这就是本地的答案护栏,应用到了决策上。

What it does它做什么

policy.py holds the rules (ALLOWED actions per type, NEEDS_POLICY, the confidence floor, figure grounding) and review(), which returns reasons. spend_agent.py first loads the exception's facts itself by calling get_exception from code and checking the id, because those facts route the proposal (business unit, amount, the two-person rule) and must not come from whichever tool output the model produced. It then connects to three managed MCP servers (UC functions, the policy index, Genie), runs the OpenAI Agents SDK with output_type=Resolution and a turn budget, reviews the result, retries once, and writes to the Lakebase queue in one transaction that supersedes any live proposal for the same exception. dry_run returns the result without writing, for evaluation.policy.py 存放规则(每种类型允许的动作 ALLOWED、NEEDS_POLICY、置信度下限、数字有据检查)以及返回原因列表的 review()。spend_agent.py 首先由代码自己调用 get_exception 加载该异常的事实并核对 id,因为这些事实决定提议的路由(业务单元、金额、双人复核规则),不能来自模型碰巧产出的某个工具输出。然后它连接三个托管 MCP 服务(UC 函数、政策索引、Genie),以 output_type=Resolution 和轮次预算运行 OpenAI Agents SDK,审查结果、重试一次,然后在一个事务中写入 Lakebase 队列,同时取代同一异常的任何在途提议。dry_run 会返回结果而不写入,用于评估。

How to do it怎么做

  1. Vendor the app template once: `bash setup/03_vendor_agent_template.sh <commit-sha>`. Edit its invoke and stream handlers to call triage() and return the dict as custom_outputs.一次性引入应用模板:`bash setup/03_vendor_agent_template.sh <commit-sha>`。修改它的 invoke 和 stream 处理函数,调用 triage() 并把返回的字典作为 custom_outputs 返回。
  2. Register the instructions as a prompt `<catalog>.ai.spend_agent_instructions` with alias production (the fallback text is in the file).把指令注册为提示词 `<catalog>.ai.spend_agent_instructions`,并设置别名 production(备用文本就在文件里)。
  3. Run it locally against dev (`uv run start-app` in agent/) on ten exceptions of each type, and read every trace.在本地针对 dev 运行它(在 agent/ 中执行 `uv run start-app`),每种类型各跑十个异常,并阅读每一条追踪。
  4. Run `python3 -m pytest native/databricks/tests`: the policy rules are tested without a workspace.运行 `python3 -m pytest native/databricks/tests`:政策规则无需工作区即可测试。

Scripts脚本

src/agent/policy.py · compiles
"""What the agent may propose, and the checks every proposal passes before it reaches the queue.

Pure Python. The model proposes; this module decides whether the proposal is admissible.
A proposal that fails is never written: the agent gets the reasons and one retry, then the
exception is escalated with the reasons attached (the same pattern as the local answer guard).
"""
from __future__ import annotations

import re
from dataclasses import dataclass, field

MONEY = re.compile(r"(?:\$\s?([\d,]+(?:\.\d+)?))|(?:([\d,]+(?:\.\d+)?)\s*(?:dollars|usd)\b)", re.I)
NUMBER = re.compile(r"\d[\d,]*(?:\.\d+)?")

# Which actions make sense for which exception type. A model that proposes approve_payment for a
# suspected duplicate is wrong whatever its rationale says.
ALLOWED = {
    "price_variance": {"approve_payment", "hold_payment", "request_credit_memo", "escalate"},
    "quantity_variance": {"hold_payment", "request_credit_memo", "escalate"},
    "no_receipt": {"hold_payment", "escalate"},
    "duplicate_suspect": {"hold_payment", "escalate"},
    "doc_mismatch": {"hold_payment", "escalate"},
    "no_po": {"hold_payment", "escalate"},
}
NEEDS_POLICY = {"approve_payment", "request_credit_memo"}   # must cite the policy that permits it
CONFIDENCE_FLOOR = 0.6


@dataclass
class Proposal:
    exception_id: str
    exception_type: str
    action: str
    rationale: str
    citations: list = field(default_factory=list)      # policy chunk ids or document references
    confidence: float = 0.0


def _num(s: str) -> float:
    return float(s.replace(",", ""))


def figures(text: str) -> list:
    return [_num(a or b) for a, b in MONEY.findall(text or "")]


def evidence_numbers(evidence: list) -> list:
    out = []
    for e in evidence:
        out += [_num(x) for x in NUMBER.findall(str(e))]
    return out


def grounded(value: float, ev: list) -> bool:
    """In the evidence, or the difference or sum of two evidence numbers (a variance is a difference)."""
    near = lambda a, b: abs(a - b) <= 0.005 * max(1.0, abs(b))  # noqa: E731
    if any(near(value, e) for e in ev):
        return True
    small = sorted(set(ev))[:400]
    return any(near(value, a + b) or near(value, abs(a - b)) for i, a in enumerate(small) for b in small[i:])


def review(p: Proposal, evidence: list, contract_actions: list) -> list:
    """Reasons the proposal is inadmissible. Empty list means it may be queued for a human."""
    reasons = []
    if p.action not in contract_actions:
        reasons.append(f"action '{p.action}' is not in the contract")
    allowed = ALLOWED.get(p.exception_type)
    if allowed is None:
        reasons.append(f"unknown exception type '{p.exception_type}'")
    elif p.action not in allowed:
        reasons.append(f"'{p.action}' is not allowed for {p.exception_type}; allowed: {sorted(allowed)}")
    if p.action in NEEDS_POLICY and not p.citations:
        reasons.append(f"'{p.action}' needs a policy citation")
    ev = evidence_numbers(evidence)
    bad = [v for v in figures(p.rationale) if not grounded(v, ev)]
    if bad:
        reasons.append("figures not in the evidence: " + ", ".join(f"{v:,.2f}" for v in bad))
    if not (0.0 <= p.confidence <= 1.0):
        reasons.append("confidence must be between 0 and 1")
    elif p.confidence < CONFIDENCE_FLOOR and p.action != "escalate":
        reasons.append(f"confidence {p.confidence:.2f} is below {CONFIDENCE_FLOOR}; escalate instead")
    if len((p.rationale or "").strip()) < 20:
        reasons.append("rationale too short to review")
    return reasons


def needs_second_approver(amount: float, threshold: float) -> bool:
    """contract.yml: second_approver_above. Strictly above: an invoice of exactly the threshold needs one approver."""
    return amount > threshold
src/agent/spend_agent.py · compiles
"""Step 14. The spend-exceptions agent. One entry point: triage(exception_id, dry_run).

Production path (what the bundle deploys): the vendor's OpenAI Agents SDK app template, vendored into
agent/ at a pinned commit (setup/03_vendor_agent_template.sh). Its invoke and stream handlers call
triage() and return the dict as custom_outputs.
Alternative path, Beta in October 2026: the Agent Bricks CLI (`agentbricks init --framework openai`,
`agentbricks tools add mcp`, `agentbricks deploy`), which runs the same code on Agent Runtime. Keep a
Beta tool out of the critical path until it is GA, or keep the template path as the fallback.

Division of labour, the core design decision of this file:
  the model   reads evidence through tools and proposes ONE structured resolution
  this code   checks the proposal (policy.review), retries once with the reasons, then writes it to
              the review queue, or escalates. The model never holds a write tool.
"""
from __future__ import annotations

import json
import os
import sys
import uuid

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from pydantic import BaseModel, Field  # noqa: E402

from agent.policy import ALLOWED, Proposal, review  # noqa: E402
from common.contract import load as load_contract  # noqa: E402

# The allowed actions come from contract.yml (CI copies it next to src/), so the contract and the agent
# cannot disagree about what may be proposed.
CONTRACT_ACTIONS = list(load_contract()["actions"])

CATALOG = os.environ.get("AGENT_CATALOG", "fin_dev")
MODEL = os.environ.get("AGENT_MODEL", "databricks-claude-sonnet-5-5")
GENIE_SPACE = os.environ.get("GENIE_SPACE_ID", "")
MAX_TURNS = 8
PROMPT_NAME = f"{CATALOG}.ai.spend_agent_instructions"

FALLBACK_INSTRUCTIONS = """You triage one accounts-payable exception at a time.
1. Call get_exception with the exception id. If found is false, propose escalate and say why.
2. Call vendor_history for the vendor.
3. Search the payment policy for the rule that governs this exception type and spend category.
4. Propose exactly one action. Allowed actions per type: {allowed}.
Rules: every number in your rationale must come from a tool result. Cite the policy chunk ids you
relied on. If the evidence conflicts or is missing, propose escalate with confidence below 0.6.
You never pay, hold or change anything yourself; a person approves every proposal."""


class Resolution(BaseModel):
    action: str = Field(description="One of the allowed actions for this exception type")
    rationale: str = Field(description="Two to five sentences. Every figure must come from a tool result.")
    citations: list[str] = Field(default_factory=list, description="Policy chunk ids relied on")
    confidence: float = Field(ge=0, le=1)


def instructions() -> tuple:
    """(text, version). The production alias of the registered prompt; the fallback is visible in traces."""
    try:
        import mlflow
        p = mlflow.genai.load_prompt(name_or_uri=f"prompts:/{PROMPT_NAME}@production")
        return p.template, f"{PROMPT_NAME}/v{p.version}"
    except Exception:                                    # noqa: BLE001
        return FALLBACK_INSTRUCTIONS.format(allowed=json.dumps({k: sorted(v) for k, v in ALLOWED.items()})), "fallback"


def mcp_servers(host: str, headers: dict) -> list:  # pragma: no cover
    """Managed MCP endpoints. Every call runs as the agent's identity, under Unity Catalog permissions."""
    from agents.mcp import MCPServerStreamableHttp

    urls = {
        "uc_tools": f"{host}/api/2.0/mcp/functions/{CATALOG}/tools",
        "policy_search": f"{host}/api/2.0/mcp/ai-search/{CATALOG}/ai/policy_index",
    }
    if GENIE_SPACE:
        urls["genie"] = f"{host}/api/2.0/mcp/genie/{GENIE_SPACE}"
    return [MCPServerStreamableHttp(name=n, params={"url": u, "headers": headers}, cache_tools_list=True)
            for n, u in urls.items()]


def load_fact(w, exception_id: str) -> dict:  # pragma: no cover
    """The facts that route the proposal (business unit, amount, type) come from code, not from whatever
    tool output the model happened to produce. Same function the model calls, same permissions."""
    from databricks.sdk.service.sql import StatementParameterListItem

    r = w.statement_execution.execute_statement(
        statement=f"SELECT {CATALOG}.tools.get_exception(:id)", warehouse_id=os.environ["DATABRICKS_WAREHOUSE_ID"],
        parameters=[StatementParameterListItem(name="id", value=exception_id)], wait_timeout="30s")
    rows = (r.result.data_array or []) if r.result else []
    fact = json.loads(rows[0][0]) if rows and rows[0][0] else {"found": False}
    if fact.get("found") and fact.get("exception_id") != exception_id:
        raise RuntimeError("get_exception returned a different exception id")      # never route on the wrong facts
    return fact


def write_proposal(fact: dict, r: Resolution, evidence: list, version: str, trace_id: str | None) -> str:  # pragma: no cover
    from common.pg import pool

    pid = str(uuid.uuid4())
    with pool().connection() as conn:
        # supersede any live proposal for this exception, then insert: one transaction, one live row
        conn.execute("UPDATE proposals SET status = 'superseded' WHERE exception_id = %s AND status IN ('pending', 'needs_second')",
                     (fact["exception_id"],))
        conn.execute(
            """INSERT INTO proposals (proposal_id, exception_id, exception_type, business_unit, invoice_amount, action,
                                      rationale, citations, evidence, confidence, model, prompt_version, trace_id)
               VALUES (%s, %s, %s, %s, %s, %s, %s, %s::jsonb, %s::jsonb, %s, %s, %s, %s)""",
            (pid, fact["exception_id"], fact["exception_type"], fact["business_unit"], fact["invoice_amount"],
             r.action, r.rationale, json.dumps(r.citations), json.dumps(evidence[-20:]), r.confidence,
             MODEL, version, trace_id))
    return pid


async def triage(exception_id: str, dry_run: bool = False) -> dict:  # pragma: no cover
    """dry_run: evaluate without writing to the queue (the eval in step 16 sets it). The handler returns
    this dict as the response's custom_outputs, so batch jobs and evals read the same fields."""
    import mlflow
    from agents import Agent, Runner, set_default_openai_api, set_default_openai_client
    from databricks.sdk import WorkspaceClient
    from databricks_openai import AsyncDatabricksOpenAI

    set_default_openai_client(AsyncDatabricksOpenAI(use_ai_gateway=True))
    set_default_openai_api("chat_completions")
    w = WorkspaceClient()
    headers = w.config.authenticate()                      # fresh OAuth header for this run
    text, version = instructions()
    fact = load_fact(w, exception_id)
    if not fact.get("found"):
        return {"exception_id": exception_id, "status": "escalated", "action": "escalate",
                "reasons": [fact.get("diagnostic", "exception not found")]}
    servers = mcp_servers(w.config.host.rstrip("/"), headers)
    for s in servers:
        await s.connect()
    try:
        agent = Agent(name="spend-exceptions", instructions=text, model=MODEL, mcp_servers=servers,
                      output_type=Resolution)
        evidence = [json.dumps(fact)]                       # the routed facts are evidence too
        prompt = [{"role": "user", "content": f"Triage exception {exception_id}. Facts from get_exception: {json.dumps(fact)}"}]
        for attempt in (1, 2):
            run = await Runner.run(agent, prompt, max_turns=MAX_TURNS)
            for item in run.new_items:
                if getattr(item, "type", "") == "tool_call_output_item":
                    evidence.append(str(getattr(item, "output", "")))
            res: Resolution = run.final_output
            reasons = review(Proposal(exception_id, fact["exception_type"], res.action, res.rationale,
                                      res.citations, res.confidence), evidence, CONTRACT_ACTIONS)
            out = {"exception_id": exception_id, "action": res.action, "rationale": res.rationale,
                   "citations": res.citations, "confidence": res.confidence, "evidence": evidence[-20:],
                   "attempts": attempt, "prompt_version": version}
            if not reasons:
                if dry_run:
                    return {**out, "status": "dry_run"}
                pid = write_proposal(fact, res, evidence, version, mlflow.get_last_active_trace_id())
                return {**out, "status": "queued", "proposal_id": pid}
            prompt = prompt + [{"role": "user", "content": "[harness] Your proposal was rejected: "
                                + "; ".join(reasons) + ". Fix it using only tool results, or propose escalate."}]
        esc = Resolution(action="escalate", rationale="The agent could not produce an admissible proposal: "
                         + "; ".join(reasons), citations=[], confidence=0.0)
        if dry_run:
            return {**out, "action": "escalate", "status": "dry_run", "reasons": reasons}
        pid = write_proposal(fact, esc, evidence, version, mlflow.get_last_active_trace_id())
        return {**out, "action": "escalate", "status": "escalated", "proposal_id": pid, "reasons": reasons}
    finally:
        for s in servers:
            await s.cleanup()
setup/03_vendor_agent_template.sh · bash -n passes
#!/usr/bin/env bash
# Step 14. Vendor the vendor's agent app template into agent/, once, at a pinned commit.
# Why vendor instead of cloning in CI: the template's handler must be edited to call triage(), and a
# production build must not change because someone pushed to a template repository you do not own.
# Upgrading the template is then a merge request you review, like any other dependency upgrade.
set -euo pipefail
REF="${1:?usage: 03_vendor_agent_template.sh <commit-sha-of-databricks/app-templates>}"
TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
git clone -q https://github.com/databricks/app-templates.git "$TMP/tpl"
git -C "$TMP/tpl" checkout -q "$REF"
rsync -a --delete --exclude 'src/' --exclude 'README.md' "$TMP/tpl/agent-openai-agents-sdk/" agent/
echo "$REF" > agent/TEMPLATE_REF
echo "Vendored template at $REF into agent/."
echo "Now edit the template's invoke/stream handlers to call src/agent/spend_agent.triage(exception_id, dry_run)"
echo "and return its dict as custom_outputs. Commit agent/ in one merge request titled 'vendor agent template $REF'."

How to read the result如何解读结果

  • `status: queued, attempts: 1` is the normal case. `attempts: 2` means the first proposal broke a rule and the reasons fixed it; a high rate of second attempts is a prompt problem worth fixing for latency and cost.`status: queued, attempts: 1` 是正常情况。`attempts: 2` 说明第一次提议违反了某条规则,而反馈的原因让它修正了;第二次尝试的比例很高,说明提示词有问题,值得为了延迟和成本去修。
  • `status: escalated` with reasons such as `figures not in the evidence: 312.40` is the control working. Read these first each week: each is either a missing tool output or a model habit.带有 `figures not in the evidence: 312.40` 之类原因的 `status: escalated`,说明控制在起作用。每周先看这些:每一条要么是缺了某个工具输出,要么是模型的某种习惯。
  • In the trace, the tool calls should be get_exception, vendor_history, a policy search, and at most one Genie question. More rounds than that is the turn budget being spent on wandering.在追踪中,工具调用应该是 get_exception、vendor_history、一次政策检索,以及最多一次 Genie 提问。超出这些的轮次,就是轮次预算被浪费在了漫无目的的探索上。

Troubleshooting排障

You see现象Why原因Do this处理
output_type parsing failsoutput_type 解析失败The chosen endpoint does not reliably produce structured output through chat completions.所选端点无法通过 chat completions 稳定地产生结构化输出。Pick a model that supports structured output, or parse JSON from text with a schema check; the review step still applies.选择支持结构化输出的模型,或者从文本中解析 JSON 并做 schema 检查;审查步骤依然适用。
MCP calls return 403MCP 调用返回 403The app's service principal lacks EXECUTE on the tools, SELECT on the index, or access to the Genie space.App 的服务主体缺少工具的 EXECUTE、索引的 SELECT,或 Genie space 的访问权限。Grant each to the app principal (not to your user), then redeploy.把这些权限逐一授予 App 的服务主体(而不是你自己的用户),然后重新部署。
Two proposals for one exception一个异常出现了两条提议Two triage runs raced.两次分诊运行发生了竞争。The partial unique index on live proposals rejects the second insert; the orchestrator also runs with max_concurrent_runs: 1.在途提议上的部分唯一索引会拒绝第二次插入;编排 job 也设置了 max_concurrent_runs: 1。

How this scales如何扩展

  • Each triage is independent, so the agent scales horizontally: more app compute, more concurrent requests, until the model's throughput is the limit. The load test in step 21 finds which limit you hit first.每次分诊相互独立,所以智能体可以横向扩展:更多 App 计算资源、更多并发请求,直到模型吞吐量成为瓶颈。第 21 步的负载测试会找出你最先碰到的是哪个限制。
  • New exception types: add to ALLOWED, add eval cases, then to the pipeline. Never in the reverse order.新增异常类型:先加到 ALLOWED,再加评估用例,最后加到 pipeline。顺序绝不能反过来。
Architecture review: questions you will be asked架构评审:你会被问到的问题
Why not a multi-agent supervisor with a policy agent, a data agent and a decision agent?为什么不用一个主管智能体,下面分政策智能体、数据智能体和决策智能体?

Module 12's measurement: more agents meant more model calls for the same answer. One agent with three tools is cheaper, faster and has one trace to read. Split only when a measured failure points at a boundary.第 12 模块的测量结果是:智能体越多,得到同样答案所需的模型调用就越多。一个智能体加三个工具更便宜、更快,也只需读一条追踪。只有当测量到的失败明确指向某条边界时才拆分。

What if the model is prompt-injected by text in an invoice PDF?如果发票 PDF 里的文字对模型进行了提示词注入怎么办?

It can only change the proposal, which then fails the code checks or reaches a person who sees the evidence. It cannot pay, write, or call a write tool, because none exists. Treat document text as data: the reviewer UI escapes it.它只能改变提议,而这份提议要么过不了代码检查,要么会交到一个能看到证据的人手里。它无法付款、无法写入,也无法调用写入工具,因为根本没有这种工具。把文档文本当作数据处理:审核界面会对其进行转义。

Done when完成标准Forty dev exceptions (ten per type) produce admissible proposals or explained escalations, and every trace shows the expected tool sequence.四十个开发环境中的异常(每种类型十个)产生了可接受的提议或有说明的升级处理,每条追踪都显示了预期的工具调用顺序。
Not confirmed on a vendor page未在厂商页面上确认MCPServerStreamableHttp with Databricks OAuth headers is the OpenAI Agents SDK's generic MCP client; the template or the Agent Bricks CLI may generate equivalent wiring, which you should prefer. The model name is from the supported-models list.带 Databricks OAuth 请求头的 MCPServerStreamableHttp 是 OpenAI Agents SDK 的通用 MCP 客户端;模板或 Agent Bricks CLI 可能会生成等效的连接代码,应优先使用它们。模型名称取自支持模型列表。
15The review queue and the reviewer app审核队列与审核 App

Why this step, and why here为什么要做这一步,为什么在这里

The human decision is the control an auditor will test, so it must be impossible to bypass from the browser: the reviewer sees only their units, cannot approve twice, large amounts need a second person, and a rejection must say what the right action was. That last rule is also the learning loop: a rejection without the correct action is not a label, and the next eval set can then only learn from the agent's successes. The queue is Postgres because a queue is many small concurrent updates with row locks.人的决定是审计人员会测试的控制措施,所以必须做到无法从浏览器绕过:审核人员只能看到自己的单元,不能重复批准,大额需要第二个人,拒绝时必须说明正确的动作是什么。最后这条规则同时也是学习循环:没有给出正确动作的拒绝不能成为标签,这样下一个评估集就只能从智能体的成功案例中学习。队列放在 Postgres 中,因为队列就是大量带行锁的小规模并发更新。

What it does它做什么

review_queue.sql creates proposals (one live per exception, by partial unique index) and append-only decisions (a rejection requires correct_action), and puts the payment control in the database: a trigger refuses any proposal inserted already decided, any approval without recorded approvals, any large approval without two different approvers, and any change to amount, action or unit; column-level grants let the agent and the app change status only. The trigger runs as its owner (SECURITY DEFINER) with search_path fixed and pg_temp last, every table it reads is schema-qualified, and TEMPORARY is revoked from PUBLIC, so no caller can shadow decisions with a temporary table full of fake approvals. tests/test_review_queue_pg.py runs that file on a real Postgres and attacks it. The app reads as the user with the forwarded token: only members of fin-reviewers who are not auditors may decide, and their units come from reviewer_scope. decide() repeats the rules for clear error messages, under a row lock, and refuses cross-site posts. export_decisions.py copies decisions to Delta, with a label only once a decision is final, and re-reads every unlabelled first approval until its second decision arrives.review_queue.sql 创建 proposals 表(通过部分唯一索引保证每个异常只有一条在途提议)和只追加的 decisions 表(拒绝时必须填写 correct_action),并把付款控制放进数据库:一个触发器会拒绝任何以已决定状态插入的提议、任何没有已记录批准的批准、任何没有两位不同批准人的大额批准,以及对金额、动作或单元的任何修改;列级授权只允许智能体和 App 修改状态。触发器以其所有者身份运行(SECURITY DEFINER),search_path 固定且 pg_temp 排在最后,它读取的每张表都带 schema 限定,并且对 PUBLIC 撤销了 TEMPORARY,所以任何调用者都无法用一张装满假批准的临时表来冒充 decisions。tests/test_review_queue_pg.py 在真实的 Postgres 上运行这个文件并对它发起攻击测试。App 用转发的令牌以用户身份读取:只有属于 fin-reviewers 且不是审计人员的人才能做决定,其负责的单元来自 reviewer_scope。decide() 在行锁下重复这些规则以给出清晰的错误信息,并拒绝跨站提交。export_decisions.py 把决定复制到 Delta,只有决定最终确定后才写入标签,并持续重读每一条尚无标签的首次批准,直到第二个决定到来。

How to do it怎么做

  1. Create a Lakebase project, run review_queue.sql as an admin role, and grant the app and agent principals as the file shows.创建一个 Lakebase 项目,以管理员角色运行 review_queue.sql,并按文件所示给 App 和智能体的服务主体授权。
  2. Deploy the app with the bundle, add the Lakebase database resource, and enable user authorization with the `sql` scope.用 bundle 部署 App,添加 Lakebase 数据库资源,并启用带 `sql` 范围的用户授权。
  3. Test as three people: a reviewer of unit A, a reviewer of unit B, and the same reviewer twice on an amount above the threshold.以三种身份测试:单元 A 的审核人员、单元 B 的审核人员,以及同一位审核人员对超过阈值的金额连续操作两次。
  4. Schedule export_decisions after each batch (the orchestrator job does).在每批处理之后安排 export_decisions(编排 job 已经这样做了)。

Scripts脚本

src/review/review_queue.sql · sqlglot postgres: 13/16 statements parsed
-- Step 15. The review queue in Lakebase Postgres: the only place the agent writes.
-- Why Postgres and not a Delta table: a queue is many small concurrent updates with row locks
-- ("I am reviewing this one"), which is what an OLTP database is for. Decisions are then copied
-- to Delta for audit and analytics (resources/jobs.yml, task export_decisions).
-- Run with psql against the Lakebase database as an admin role, not as the app: the owner of a table
-- can always update it, so the app must not own the decisions table it may only append to.

CREATE TABLE IF NOT EXISTS proposals (
  proposal_id     uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  exception_id    text NOT NULL,
  exception_type  text NOT NULL,
  business_unit   text NOT NULL,
  invoice_amount  numeric(18, 2) NOT NULL,
  action          text NOT NULL CHECK (action IN ('approve_payment', 'hold_payment', 'request_credit_memo', 'escalate')),
  rationale       text NOT NULL,
  citations       jsonb NOT NULL DEFAULT '[]',
  evidence        jsonb NOT NULL DEFAULT '[]',
  confidence      numeric(4, 3) NOT NULL CHECK (confidence BETWEEN 0 AND 1),
  model           text NOT NULL,
  prompt_version  text NOT NULL,
  trace_id        text,                         -- links the proposal to its MLflow trace
  status          text NOT NULL DEFAULT 'pending'
                  CHECK (status IN ('pending', 'approved', 'rejected', 'needs_second', 'superseded')),
  created_at      timestamptz NOT NULL DEFAULT now()
);
-- One live proposal per exception: a re-run supersedes the old one, it never adds a second.
-- A partial unique index, because many rejected or superseded rows for one exception are fine.
CREATE UNIQUE INDEX IF NOT EXISTS proposals_one_pending ON proposals (exception_id) WHERE status IN ('pending', 'needs_second');
CREATE INDEX IF NOT EXISTS proposals_queue ON proposals (business_unit, status, created_at);

-- Decisions are append-only. Nobody updates or deletes a decision; a correction is a new row.
CREATE TABLE IF NOT EXISTS decisions (
  decision_id   bigserial PRIMARY KEY,
  proposal_id   uuid NOT NULL REFERENCES proposals (proposal_id),
  reviewer      text NOT NULL,
  verdict       text NOT NULL CHECK (verdict IN ('approve', 'reject', 'second_approve')),
  -- A rejection must say what the right action was. Without it, a rejection is not a label, and the
  -- evaluation set (step 16) can only learn from the agent's successes.
  correct_action text CHECK (correct_action IN ('approve_payment', 'hold_payment', 'request_credit_memo', 'escalate')),
  comment       text,
  CONSTRAINT reject_has_answer CHECK (verdict <> 'reject' OR correct_action IS NOT NULL),
  decided_at    timestamptz NOT NULL DEFAULT now()
);
-- The database enforces the payment control, not only the app: whoever holds a connection, no proposal
-- becomes approved without recorded approvals, a large one needs two different approvers, and nothing
-- is inserted already decided. 25000 must equal contract.yml second_approver_above (a test checks it).
-- SECURITY DEFINER: the check reads decisions with the owner's rights, so it works for the agent (which
-- may not read decisions). Every table is schema-qualified and pg_temp is searched last, so a caller cannot
-- shadow public.decisions with a temporary table full of fake approvals (a test tries exactly that).
CREATE OR REPLACE FUNCTION guard_proposal() RETURNS trigger LANGUAGE plpgsql
SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$
DECLARE approvers int;
BEGIN
  IF TG_OP = 'INSERT' THEN
    IF NEW.status <> 'pending' THEN RAISE EXCEPTION 'a proposal is inserted as pending, not %', NEW.status; END IF;
    RETURN NEW;
  END IF;
  IF OLD.status NOT IN ('pending', 'needs_second') THEN
    RAISE EXCEPTION 'proposal is %, it can no longer change', OLD.status;
  END IF;
  IF NEW.invoice_amount <> OLD.invoice_amount OR NEW.action <> OLD.action OR NEW.business_unit <> OLD.business_unit THEN
    RAISE EXCEPTION 'only status may change on a proposal';
  END IF;
  SELECT count(DISTINCT reviewer) INTO approvers FROM public.decisions
   WHERE proposal_id = NEW.proposal_id AND verdict IN ('approve', 'second_approve');
  IF NEW.status = 'needs_second' AND (approvers < 1 OR NEW.invoice_amount <= 25000) THEN
    RAISE EXCEPTION 'needs_second requires one approval on an amount above the threshold';
  ELSIF NEW.status = 'approved' AND (approvers < 1 OR (NEW.invoice_amount > 25000 AND approvers < 2)) THEN
    RAISE EXCEPTION 'approved requires % different approvers', CASE WHEN NEW.invoice_amount > 25000 THEN 2 ELSE 1 END;
  ELSIF NEW.status = 'rejected' AND NOT EXISTS (SELECT 1 FROM public.decisions WHERE proposal_id = NEW.proposal_id AND verdict = 'reject') THEN
    RAISE EXCEPTION 'rejected requires a recorded rejection';
  END IF;
  RETURN NEW;
END $$;
DROP TRIGGER IF EXISTS proposals_guard ON proposals;
CREATE TRIGGER proposals_guard BEFORE INSERT OR UPDATE ON proposals FOR EACH ROW EXECUTE FUNCTION guard_proposal();

REVOKE ALL ON proposals, decisions FROM PUBLIC;
DO $$ BEGIN EXECUTE format('REVOKE TEMPORARY ON DATABASE %I FROM PUBLIC', current_database()); END $$;
-- Principals are Postgres roles named by client id. Column-level UPDATE: nobody can rewrite an amount.
--   agent: inserts proposals and supersedes its own pending ones
--   app:   reads, records decisions, moves status (the trigger checks every move)
--   jobs:  reads, for batch selection and the export to Delta
GRANT SELECT, INSERT ON proposals TO "<agent client id>";
GRANT UPDATE (status) ON proposals TO "<agent client id>", "<app client id>";
GRANT SELECT ON proposals TO "<app client id>", "<jobs client id>";
GRANT SELECT, INSERT ON decisions TO "<app client id>";          -- append only: no UPDATE, no DELETE
GRANT SELECT ON decisions TO "<jobs client id>";
GRANT USAGE ON SEQUENCE decisions_decision_id_seq TO "<app client id>";
tests/test_review_queue_pg.py · compiles
"""Runs src/review/review_queue.sql on a real, throwaway Postgres and attacks the payment control.

Lakebase is Postgres, so the trigger, the column grants and the append-only rule can be tested here
exactly as written. Skipped when no Postgres server binaries are installed. In a root-only container
set PG_RUN_AS to an ordinary user (Postgres refuses to run as root).
"""
from __future__ import annotations

import glob
import os
import shutil
import socket
import subprocess
import tempfile
import time
import unittest
import uuid

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SQL = os.path.join(ROOT, "src", "review", "review_queue.sql")
BIN = (sorted(glob.glob("/usr/lib/postgresql/*/bin")) or [""])[-1]
INITDB = shutil.which("initdb") or (os.path.join(BIN, "initdb") if BIN else None)


def _free_port() -> int:
    with socket.socket() as s:
        s.bind(("127.0.0.1", 0))
        return s.getsockname()[1]


def _as_owner(cmd: list) -> list:
    user = os.environ.get("PG_RUN_AS") or ("nobody" if os.geteuid() == 0 else None)
    return ["runuser", "-u", user, "--"] + cmd if user and os.geteuid() == 0 else cmd


HAVE_PG = bool(INITDB and os.path.exists(INITDB))


class RequirePostgres(unittest.TestCase):
    def test_postgres_available_when_required(self):
        """CI sets REQUIRE_PG=1, so a missing Postgres fails the pipeline instead of skipping the control tests."""
        if os.environ.get("REQUIRE_PG") == "1":
            self.assertTrue(HAVE_PG, "REQUIRE_PG=1 but no Postgres server binaries")


@unittest.skipUnless(HAVE_PG, "no Postgres server binaries")
class ReviewQueueOnPostgres(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        import psycopg
        cls.psycopg = psycopg
        cls.dir = tempfile.mkdtemp(prefix="rq-pg-")
        os.chmod(cls.dir, 0o777)
        data = os.path.join(cls.dir, "data")
        cls.port = _free_port()
        bindir = os.path.dirname(INITDB)
        subprocess.run(_as_owner([INITDB, "-D", data, "-U", "admin", "-A", "trust", "--locale=C", "-E", "UTF8"]),
                       check=True, capture_output=True)
        subprocess.run(_as_owner([os.path.join(bindir, "pg_ctl"), "-D", data, "-l", os.path.join(cls.dir, "log"),
                                  "-o", f"-p {cls.port} -k {cls.dir} -c listen_addresses=''", "-w", "start"]),
                       check=True, capture_output=True)
        cls.bindir, cls.data = bindir, data
        admin = cls.conn("admin")
        for role in ("agent", "app", "jobs"):
            admin.execute(f'CREATE ROLE "{role}" LOGIN')
        sql = open(SQL).read().replace("<agent client id>", "agent").replace("<app client id>", "app") \
                             .replace("<jobs client id>", "jobs")
        admin.execute(sql)
        admin.close()

    @classmethod
    def tearDownClass(cls):
        subprocess.run(_as_owner([os.path.join(cls.bindir, "pg_ctl"), "-D", cls.data, "-m", "immediate", "stop"]),
                       capture_output=True)
        shutil.rmtree(cls.dir, ignore_errors=True)

    @classmethod
    def conn(cls, user: str):
        return cls.psycopg.connect(host=cls.dir, port=cls.port, dbname="postgres", user=user, autocommit=True)

    def proposal(self, amount: float) -> str:
        pid = str(uuid.uuid4())
        with self.conn("agent") as c:
            c.execute("""INSERT INTO proposals (proposal_id, exception_id, exception_type, business_unit, invoice_amount,
                         action, rationale, confidence, model, prompt_version)
                         VALUES (%s, %s, 'price_variance', 'BU-7', %s, 'approve_payment', 'r', 0.9, 'm', 'v')""",
                      (pid, "ex-" + pid, amount))
        return pid

    def decide(self, pid: str, reviewer: str, verdict: str, status: str):
        with self.conn("app") as c:
            with c.transaction():
                c.execute("INSERT INTO decisions (proposal_id, reviewer, verdict, correct_action) VALUES (%s, %s, %s, %s)",
                          (pid, reviewer, verdict, "escalate" if verdict == "reject" else None))
                c.execute("UPDATE proposals SET status = %s WHERE proposal_id = %s", (status, pid))

    def status(self, pid: str) -> str:
        with self.conn("admin") as c:
            return c.execute("SELECT status FROM proposals WHERE proposal_id = %s", (pid,)).fetchone()[0]

    def test_agent_cannot_insert_a_decided_proposal(self):
        with self.conn("agent") as c, self.assertRaises(self.psycopg.errors.RaiseException):
            c.execute("""INSERT INTO proposals (exception_id, exception_type, business_unit, invoice_amount, action,
                         rationale, confidence, model, prompt_version, status)
                         VALUES ('x1', 'price_variance', 'BU-7', 10, 'approve_payment', 'r', 0.9, 'm', 'v', 'approved')""")

    def test_agent_cannot_approve_without_a_decision(self):
        pid = self.proposal(100)
        with self.conn("agent") as c, self.assertRaises(self.psycopg.errors.RaiseException):
            c.execute("UPDATE proposals SET status = 'approved' WHERE proposal_id = %s", (pid,))
        self.assertEqual(self.status(pid), "pending")

    def test_temp_table_cannot_fake_approvals(self):
        """The attack: shadow decisions with a temporary table holding two fake approvals, then approve."""
        pid = self.proposal(30000)
        with self.conn("agent") as c:
            try:
                c.execute("CREATE TEMP TABLE decisions (proposal_id uuid, reviewer text, verdict text)")
                c.execute("INSERT INTO pg_temp.decisions VALUES (%s, 'x', 'approve'), (%s, 'y', 'approve')", (pid, pid))
            except self.psycopg.errors.InsufficientPrivilege:
                pass                                                   # TEMPORARY revoked: the attack stops here
            with self.assertRaises(self.psycopg.errors.RaiseException):
                c.execute("UPDATE proposals SET status = 'approved' WHERE proposal_id = %s", (pid,))
        self.assertEqual(self.status(pid), "pending")

    def test_agent_can_supersede_its_own_pending_proposal(self):
        pid = self.proposal(100)
        with self.conn("agent") as c:
            c.execute("UPDATE proposals SET status = 'superseded' WHERE proposal_id = %s", (pid,))
        self.assertEqual(self.status(pid), "superseded")

    def test_nobody_can_rewrite_the_amount(self):
        pid = self.proposal(30000)
        with self.conn("app") as c, self.assertRaises(self.psycopg.errors.InsufficientPrivilege):
            c.execute("UPDATE proposals SET invoice_amount = 100 WHERE proposal_id = %s", (pid,))

    def test_small_amount_one_approver(self):
        pid = self.proposal(900)
        self.decide(pid, "ann", "approve", "approved")
        self.assertEqual(self.status(pid), "approved")

    def test_large_amount_needs_two_different_approvers(self):
        pid = self.proposal(30000)
        with self.assertRaises(self.psycopg.errors.RaiseException):
            self.decide(pid, "ann", "approve", "approved")            # one approver, straight to approved
        self.decide(pid, "ann", "approve", "needs_second")
        with self.assertRaises(self.psycopg.errors.RaiseException):
            self.decide(pid, "ann", "second_approve", "approved")     # same person twice
        self.assertEqual(self.status(pid), "needs_second")            # the failed attempt rolled back
        self.decide(pid, "bob", "second_approve", "approved")
        self.assertEqual(self.status(pid), "approved")

    def test_closed_proposal_cannot_change(self):
        pid = self.proposal(900)
        self.decide(pid, "ann", "reject", "rejected")
        with self.assertRaises(self.psycopg.errors.RaiseException):
            self.decide(pid, "bob", "approve", "approved")

    def test_decisions_are_append_only(self):
        pid = self.proposal(900)
        self.decide(pid, "ann", "approve", "approved")
        with self.conn("app") as c, self.assertRaises(self.psycopg.errors.InsufficientPrivilege):
            c.execute("UPDATE decisions SET reviewer = 'someone else' WHERE proposal_id = %s", (pid,))

    def test_one_live_proposal_per_exception(self):
        pid = self.proposal(900)
        with self.conn("admin") as c:
            ex = c.execute("SELECT exception_id FROM proposals WHERE proposal_id = %s", (pid,)).fetchone()[0]
        with self.conn("agent") as c, self.assertRaises(self.psycopg.errors.UniqueViolation):
            c.execute("""INSERT INTO proposals (exception_id, exception_type, business_unit, invoice_amount, action,
                         rationale, confidence, model, prompt_version) VALUES (%s, 'price_variance', 'BU-7', 900,
                         'hold_payment', 'r', 0.9, 'm', 'v')""", (ex,))


if __name__ == "__main__":
    unittest.main(verbosity=2)
app/review_logic.py · compiles
"""Decision rules for the reviewer app. Pure Python, tested by tests/test_native.py.

The rules a payment control needs, enforced in code the reviewer cannot bypass from the browser:
  - a reviewer decides only proposals in their business units
  - above the two-person threshold, approval needs a second, different approver
  - nobody approves a proposal twice, and nobody decides a proposal that is not live
"""
from __future__ import annotations

import html
from urllib.parse import urlparse

LIVE = {"pending", "needs_second"}


ACTIONS = ("approve_payment", "hold_payment", "request_credit_memo", "escalate")


def decide(proposal: dict, reviewer: str, verdict: str, my_units: set, prior_approvers: list,
           two_person_threshold: float, correct_action: str | None = None) -> tuple:
    """Returns (new_status, decision_verdict) or raises PermissionError / ValueError with the reason.
    A rejection must name the action that should have been proposed: that is the label the eval set needs."""
    if verdict not in ("approve", "reject"):
        raise ValueError(f"unknown verdict {verdict!r}")
    if proposal["business_unit"] not in my_units:
        raise PermissionError("this proposal belongs to a business unit you do not review")
    if proposal["status"] not in LIVE:
        raise ValueError(f"proposal is {proposal['status']}, not open for decision")
    if verdict == "reject":
        if correct_action not in ACTIONS:
            raise ValueError("a rejection must say which action is correct")
        if correct_action == proposal.get("action"):
            raise ValueError("the correct action equals the proposed one; approve it instead")
        return "rejected", "reject"
    if reviewer in prior_approvers:
        raise PermissionError("you already approved this proposal; a second approver must be someone else")
    big = float(proposal["invoice_amount"]) > two_person_threshold      # contract: second_approver_above
    if big and proposal["status"] == "pending":
        return "needs_second", "approve"
    if proposal["status"] == "needs_second":
        return "approved", "second_approve"
    return "approved", "approve"


def row_html(p: dict) -> str:
    """One queue row. Everything model-written is escaped: a rationale is untrusted text."""
    e = lambda v: html.escape(str(v if v is not None else ""))  # noqa: E731
    cites = ", ".join(e(c) for c in (p.get("citations") or []))
    return (f"<tr><td>{e(p['exception_type'])}</td><td>{e(p['business_unit'])}</td>"
            f"<td class=num>{float(p['invoice_amount']):,.2f}</td><td><b>{e(p['action'])}</b>"
            f"<div class=why>{e(p['rationale'])}</div><div class=cite>{cites}</div></td>"
            f"<td>{float(p['confidence']):.2f}</td><td>{e(p['status'])}</td>"
            f"<td><form method=post action='/decide/{e(p['proposal_id'])}'>"
            f"<button name=verdict value=approve>Approve</button>"
            f"<select name=correct_action><option value=''>if rejecting, correct action</option>"
            + "".join(f"<option>{a}</option>" for a in ACTIONS) +
            f"</select><button name=verdict value=reject>Reject</button></form></td></tr>")


def same_origin(origin: str | None, referer: str | None, host: str | None, forwarded_host: str | None,
                extra_hosts: str = "") -> bool:
    """A decision must come from this app's own page (CSRF). Browsers send Origin on form posts.
    Behind the Apps proxy the Host header may be the internal address, so the public name can arrive
    in X-Forwarded-Host instead; accept either, plus APP_HOSTS (comma-separated) if set. No Origin and
    no Referer is refused: a form post from a real browser carries one of them."""
    source = origin or referer or ""
    netloc = urlparse(source).netloc.lower()
    if not netloc:
        return False
    allowed = {h.strip().lower() for h in [host or "", *(forwarded_host or "").split(","), *extra_hosts.split(",")]
               if h.strip()}
    return netloc in allowed
app/app.py · compiles
"""Step 15. The reviewer app: a Databricks App where people approve or reject the agent's proposals.

Two identities, on purpose:
  the user (on-behalf-of, x-forwarded-access-token): reads Unity Catalog data AS THE REVIEWER, so the
      business-unit row filter and the bank-account mask from step 4 apply to what they see
  the app's service principal: reads and writes the Lakebase review queue, which has no UC policies,
      so this code filters the queue to the units the user's own UC query returned
Enable user authorization with the `sql` scope on the app (UI: User authorization > Add scope).
"""
from __future__ import annotations

import json
import os

import yaml

from databricks import sql
from databricks.sdk import WorkspaceClient
from databricks.sdk.core import Config
from fastapi import FastAPI, Form, HTTPException, Request
from fastapi.responses import HTMLResponse, RedirectResponse

from review_logic import decide, row_html, same_origin
from pg import pool

CATALOG = os.environ["AGENT_CATALOG"]                  # rendered per environment by CI; no dev default
WAREHOUSE_ID = os.environ["DATABRICKS_WAREHOUSE_ID"]
# The two-person threshold comes from the contract CI copies next to this file, so the app, the agent
# and the database trigger (checked by a test) use one number.
_here = os.path.dirname(os.path.abspath(__file__))
_contract = next((p for p in (os.path.join(_here, "contract.yml"), os.path.join(_here, "..", "contract.yml"))
                 if os.path.exists(p)), os.path.join(_here, "contract.yml"))   # deployed copy, else repo root
with open(_contract) as _f:
    TWO_PERSON = float(yaml.safe_load(_f)["human_in_the_loop"]["second_approver_above"])
cfg = Config()
app = FastAPI()


def user_token(req: Request) -> str:
    tok = req.headers.get("x-forwarded-access-token")
    if not tok:
        raise HTTPException(401, "user authorization is not enabled for this app")
    return tok


def whoami(tok: str) -> str:
    return WorkspaceClient(host=cfg.host, token=tok, auth_type="pat").current_user.me().user_name


def my_units(tok: str) -> set:
    """Business units the reviewer decides, asked AS the reviewer. Only members of fin-reviewers who are not
    auditors decide: auditors see everything by policy, and seeing is not deciding (segregation of duties)."""
    with sql.connect(server_hostname=cfg.host.replace("https://", ""), http_path=f"/sql/1.0/warehouses/{WAREHOUSE_ID}",
                     access_token=tok) as conn, conn.cursor() as cur:
        cur.execute("SELECT is_account_group_member('fin-reviewers') AND NOT is_account_group_member('fin-auditors')")
        if not cur.fetchone()[0]:
            return set()
        cur.execute(f"SELECT business_unit FROM {CATALOG}.gold.reviewer_scope WHERE reviewer = current_user()")
        return {r[0] for r in cur.fetchall()}


def origin_ok(req: Request) -> bool:
    h = req.headers
    return same_origin(h.get("origin"), h.get("referer"), h.get("host"), h.get("x-forwarded-host"),
                       os.environ.get("APP_HOSTS", ""))


@app.get("/", response_class=HTMLResponse)
def queue(req: Request):
    tok = user_token(req)
    units = my_units(tok)
    with pool().connection() as conn:
        cur = conn.execute(
            """SELECT proposal_id, exception_type, business_unit, invoice_amount, action, rationale, citations,
                      confidence, status FROM proposals
               WHERE status IN ('pending', 'needs_second') AND business_unit = ANY(%s)
               ORDER BY invoice_amount DESC LIMIT 200""", (list(units),))
        cols = [d.name for d in cur.description]
        rows = [dict(zip(cols, r)) for r in cur.fetchall()]
    body = "".join(row_html(r) for r in rows) or "<tr><td colspan=7>Nothing to review in your business units.</td></tr>"
    return f"""<!doctype html><meta charset=utf-8><title>Spend exceptions review</title>
<style>body{{font:14px system-ui;margin:24px}}table{{border-collapse:collapse;width:100%}}td,th{{border-bottom:1px solid #ddd;
padding:8px;vertical-align:top;text-align:left}}.num{{text-align:right}}.why{{color:#444;max-width:60ch}}.cite{{font:12px monospace;color:#777}}</style>
<h1>Proposals to review</h1><p>{len(rows)} open in {len(units)} business units.</p>
<table><tr><th>Type</th><th>Unit</th><th>Amount</th><th>Proposal</th><th>Conf.</th><th>Status</th><th></th></tr>{body}</table>"""


@app.post("/decide/{proposal_id}")
def decide_route(proposal_id: str, req: Request, verdict: str = Form(...), correct_action: str = Form("")):
    if not origin_ok(req):
        raise HTTPException(403, "cross-site request refused")
    tok = user_token(req)
    reviewer, units = whoami(tok), my_units(tok)
    with pool().connection() as conn:
        row = conn.execute("SELECT proposal_id, business_unit, invoice_amount, status, action FROM proposals "
                           "WHERE proposal_id = %s FOR UPDATE", (proposal_id,)).fetchone()   # lock: two reviewers, one decision
        if not row:
            raise HTTPException(404, "no such proposal")
        p = dict(zip(("proposal_id", "business_unit", "invoice_amount", "status", "action"), row))
        prior = [r[0] for r in conn.execute("SELECT reviewer FROM decisions WHERE proposal_id = %s AND verdict LIKE '%%approve'",
                                            (proposal_id,)).fetchall()]
        try:
            status, dverdict = decide(p, reviewer, verdict, units, prior, TWO_PERSON, correct_action or None)
        except PermissionError as e:
            raise HTTPException(403, str(e))
        except ValueError as e:
            raise HTTPException(409, str(e))
        conn.execute("INSERT INTO decisions (proposal_id, reviewer, verdict, correct_action) VALUES (%s, %s, %s, %s)",
                     (proposal_id, reviewer, dverdict, correct_action or None))
        conn.execute("UPDATE proposals SET status = %s WHERE proposal_id = %s", (status, proposal_id))
    print(json.dumps({"event": "decision", "proposal_id": proposal_id, "reviewer": reviewer, "status": status}))
    return RedirectResponse("/", status_code=303)
app/app.yaml · yaml parses
# Step 15. Runtime configuration for the reviewer app. DATABRICKS_APP_PORT is substituted by the platform.
# Values that differ per environment (AGENT_CATALOG, ENDPOINT_NAME, PGHOST) are written in by CI with
# src/common/render_env.py before each deploy; the committed values are for dev.
command: ['uvicorn', 'app:app', '--host', '0.0.0.0', '--port', '$DATABRICKS_APP_PORT']
env:
  - name: AGENT_CATALOG
    value: fin_dev
  - name: DATABRICKS_WAREHOUSE_ID
    valueFrom: sql_warehouse            # the sql_warehouse resource declared in resources/apps.yml
  # Lakebase: ENDPOINT_NAME and PGHOST from the console's Connect dialog. PGUSER defaults to the app's own
  # client id (the Postgres role name of its service principal); a Lakebase app resource can set PG* instead.
  - name: ENDPOINT_NAME
    value: projects/spend-exceptions/branches/dev/endpoints/primary
  - name: PGHOST
    value: <dev-lakebase-host>
src/review/export_decisions.py · compiles
"""Step 15 and 16. Copy decisions from the Lakebase queue to Delta, for audit and for the next eval set.

Runs after each batch (resources/jobs.yml). Incremental by decision_id, idempotent by MERGE, so a
rerun after a failure neither skips nor duplicates. The label for each case is the action a person
confirmed: the proposed action when approved, the reviewer's correct_action when rejected.

  python export_decisions.py --catalog fin_prd
"""
from __future__ import annotations

import argparse
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


LOOKBACK = 1000   # ids from a bigserial can commit out of order under concurrent writers; re-read a window


def label(proposed_action: str, verdict: str, correct_action: str | None, proposal_status: str) -> str | None:
    """The confirmed action, or None while the proposal is not final. A first approval of a two-person
    proposal is not a label: the second approver may still reject it."""
    if verdict == "reject":
        return correct_action
    if verdict in ("approve", "second_approve") and proposal_status == "approved":
        return proposed_action
    return None


def main(argv: list) -> None:  # pragma: no cover
    from pyspark.sql import SparkSession

    from common.pg import pool

    ap = argparse.ArgumentParser()
    ap.add_argument("--catalog", required=True)
    from common.pg import add_args, apply_args
    add_args(ap)
    a = ap.parse_args(argv)
    apply_args(a)
    spark = SparkSession.builder.getOrCreate()
    target = f"{a.catalog}.ops.decisions_history"
    spark.sql(f"""CREATE TABLE IF NOT EXISTS {target} (decision_id BIGINT, proposal_id STRING, exception_id STRING,
                  exception_type STRING, business_unit STRING, proposed_action STRING, verdict STRING, action STRING,
                  reviewer STRING, model STRING, prompt_version STRING, trace_id STRING, decided_at TIMESTAMP)""")
    last = spark.sql(f"SELECT coalesce(max(decision_id), 0) AS m FROM {target}").collect()[0]["m"]
    # First approvals of two-person proposals were exported without a label. Re-read them however old they
    # are, or a second approval that lands after the look-back window never reaches the eval set.
    unlabelled = [r["decision_id"] for r in spark.sql(
        f"SELECT decision_id FROM {target} WHERE action IS NULL AND decided_at > current_timestamp() - INTERVAL 90 DAYS"
    ).collect()]
    with pool().connection() as conn:
        rows = conn.execute(
            """SELECT d.decision_id, p.proposal_id::text, p.exception_id, p.exception_type, p.business_unit, p.action,
                      d.verdict, d.correct_action, d.reviewer, p.model, p.prompt_version, p.trace_id, d.decided_at, p.status
               FROM decisions d JOIN proposals p USING (proposal_id)
               WHERE d.decision_id > %s OR d.decision_id = ANY(%s) ORDER BY d.decision_id""",
            (max(0, last - LOOKBACK), unlabelled)).fetchall()
    out = [(r[0], r[1], r[2], r[3], r[4], r[5], r[6], label(r[5], r[6], r[7], r[13]), r[8], r[9], r[10], r[11], r[12])
           for r in rows]
    if not out:
        print("no new decisions")
        return
    df = spark.createDataFrame(out, spark.table(target).schema)
    df.createOrReplaceTempView("new_decisions")
    # Matched rows are updated too: a first approval's label fills in once the second approver decides.
    spark.sql(f"""MERGE INTO {target} t USING new_decisions s ON t.decision_id = s.decision_id
                  WHEN MATCHED AND t.action IS NULL AND s.action IS NOT NULL THEN UPDATE SET t.action = s.action
                  WHEN NOT MATCHED THEN INSERT *""")
    print(f"exported {len(out)} decisions after id {last}")


if __name__ == "__main__":  # pragma: no cover
    main(sys.argv[1:])
resources/apps.yml · yaml parses
# Steps 14, 15, 18. Two Databricks Apps, each with its own service principal and only the resources it uses.
#   agent     the spend-exceptions agent, from the vendor's OpenAI Agents SDK app template (agent/ folder),
#             with src/ copied in by CI. Name starts with "agent-" so it is listed among workspace agents.
#   reviewer  the human-in-the-loop UI (app/ folder). User authorization (scope: sql) is enabled on it in
#             the Apps UI or with `databricks apps update` and user_api_scopes; see step 15.
# Confirmed resource shapes: experiment (CAN_EDIT) and serving_endpoint (CAN_QUERY). Check sql_warehouse,
# genie_space and the Lakebase database blocks against the Apps resources page before the first deploy.
resources:
  apps:
    agent:
      name: agent-spend-exceptions
      description: Proposes resolutions for invoice match exceptions. Never pays or holds anything itself.
      source_code_path: ../agent
      resources:
        - name: experiment
          experiment:
            experiment_id: ${resources.experiments.traces.id}
            permission: CAN_EDIT
        - name: model
          serving_endpoint:
            name: ${var.agent_model}
            permission: CAN_QUERY
        - name: sql_warehouse
          sql_warehouse:
            id: ${var.warehouse_id}
            permission: CAN_USE
        - name: genie
          genie_space:
            space_id: ${var.genie_space_id}
            permission: CAN_RUN
      # permissions: set per target in databricks.yml (stg, prd), because in dev the caller is you, a user.

    reviewer:
      name: spend-exceptions-review
      description: Reviewers approve or reject the agent's proposals for their business units.
      source_code_path: ../app
      resources:
        - name: sql_warehouse
          sql_warehouse:
            id: ${var.warehouse_id}
            permission: CAN_USE
        # Lakebase database: add as the vendor's resources page shows (key "postgres",
        # permission CAN_CONNECT_AND_CREATE); the platform then sets PG* variables for the app.
        # Until then, CI writes ENDPOINT_NAME and PGHOST into app.yaml and PGUSER defaults to the app's client id.
      permissions:
        - level: CAN_USE
          group_name: fin-reviewers

  experiments:
    traces:
      name: ${var.experiment_path}

How to read the result如何解读结果

  • Reviewer B seeing an empty queue while A sees ten items is the design working: B's UC query returned no units for A's rows.审核人员 B 看到空队列而 A 看到十条,说明设计在起作用:B 的 UC 查询没有返回 A 那些行所属的单元。
  • `403 you already approved this proposal` on the second click is the two-person rule. If it does not appear, check that the first approval left the proposal in needs_second.第二次点击时出现 `403 you already approved this proposal`,就是双人复核规则在起作用。如果没出现,检查第一次批准后提议是否处于 needs_second 状态。
  • In ops.decisions_history, the action column is the label the next eval set uses. Rejections with a correct action are the most valuable rows in the whole system.在 ops.decisions_history 中,action 列就是下一个评估集要用的标签。带有正确动作的拒绝,是整个系统中最有价值的数据行。

Troubleshooting排障

You see现象Why原因Do this处理
401: user authorization is not enabled401:未启用用户授权The app has no user scopes, so no x-forwarded-access-token header.App 没有配置用户范围,所以没有 x-forwarded-access-token 请求头。Add the `sql` scope under User authorization, then restart the app.在 User authorization 下添加 `sql` 范围,然后重启 App。
The reviewer sees all units审核人员看到了所有单元The units query ran as the app's principal instead of the user's token.单元查询是以 App 的服务主体身份运行的,而不是用户的令牌。my_units() must use access_token=the forwarded token. Never fall back to the app identity when the header is missing; the code returns 401.my_units() 必须使用 access_token=转发的令牌。缺少请求头时绝不能退回到 App 身份;代码会返回 401。
An auditor can approve审计人员可以批准Auditors see every unit by policy, and the app took units from what the user can see.按策略,审计人员能看到所有单元,而 App 是根据用户能看到的内容来确定单元的。Seeing is not deciding: the app requires fin-reviewers and not fin-auditors, and reads units from reviewer_scope.能看到不等于能决定:App 要求属于 fin-reviewers 且不属于 fin-auditors,并从 reviewer_scope 读取单元。
Every decision fails: cross-site request refused每个决定都失败:cross-site request refusedBehind the Apps proxy the Host header can be an internal address, so it never equals the browser's Origin.在 Apps 代理之后,Host 请求头可能是内部地址,因此永远不等于浏览器的 Origin。same_origin() also accepts X-Forwarded-Host and the APP_HOSTS variable. Set APP_HOSTS to the app's public host name if neither header carries it; never remove the check.same_origin() 也接受 X-Forwarded-Host 和 APP_HOSTS 变量。如果两个请求头都不带公网主机名,就把 APP_HOSTS 设为 App 的公网主机名;绝不要删除这项检查。
Decisions table can be updateddecisions 表可以被更新The app role owns the table.App 角色拥有这张表。Recreate it as an admin role and grant the app SELECT and INSERT only, as review_queue.sql does.以管理员角色重建它,并像 review_queue.sql 那样只授予 App SELECT 和 INSERT 权限。

How this scales如何扩展

  • Hundreds of reviewers: the queue query is indexed on (business_unit, status, created_at); Lakebase autoscaling handles the connection load. The app itself scales by compute size.数百位审核人员:队列查询在 (business_unit, status, created_at) 上有索引;Lakebase 自动扩缩容负责处理连接负载。App 本身通过计算规格扩展。
  • Reviewer throughput becomes the real limit long before compute does. Measure decisions per reviewer-hour; that number, not model latency, sets how many exceptions a day the workflow clears.早在计算资源成为瓶颈之前,审核人员的处理速度就会成为真正的限制。测量每位审核人员每小时的决定数;决定工作流每天能处理多少异常的是这个数字,而不是模型延迟。
Architecture review: questions you will be asked架构评审:你会被问到的问题
Why a custom app and not the Agent Bricks review UI or a dashboard?为什么要自己做 App,而不用 Agent Bricks 的审核界面或仪表盘?

The decision needs rules a generic UI does not have: units from Unity Catalog, the two-person rule, a required correction on reject, an append-only log. Those are payment controls. Use the MLflow labeling tools for SME feedback on traces (step 17), which is a different job.这个决定需要通用界面没有的规则:来自 Unity Catalog 的单元范围、双人复核、拒绝时必须给出纠正、只追加的日志。这些都是付款控制措施。MLflow 的标注工具用于专家对追踪的反馈(第 17 步),那是另一项工作。

Done when完成标准The three-person test behaves as described, decisions cannot be edited, and decisions_history fills after each batch.三人测试的表现与描述一致,决定无法被编辑,每批处理后 decisions_history 都会写入数据。
Not confirmed on a vendor page未在厂商页面上确认The Lakebase app resource block and the genie_space and sql_warehouse resource shapes in apps.yml follow the documented resource types; the exact YAML keys should be checked against the Apps resources page. Header names other than x-forwarded-access-token were not read for this guide, so the app asks the API who the user is.apps.yml 中 Lakebase App 资源块以及 genie_space 和 sql_warehouse 的资源结构遵循文档中的资源类型;确切的 YAML 键需要对照 Apps 资源页面核对。本指南没有查阅除 x-forwarded-access-token 之外的请求头名称,所以 App 是通过 API 询问用户身份的。

6 Quality: the release gate and production monitoring质量:发布门槛与生产监控

Two loops, measured differently. Before release, a sealed evaluation set of past human decisions decides whether a change ships. After release, scorers on sampled live traces and the reviewers' own decisions say whether it still works. Both feed the contract's numbers, and neither is a demo.两个循环,用不同的方式衡量。发布之前,由过往人工决定组成的封存评估集决定一项改动能否上线。发布之后,对抽样的线上追踪运行的 scorer,加上审核人员自己的决定,告诉你它是否依然有效。两者都对应契约中的数字,没有一个是演示。

16The evaluation set and the release gate评估集与发布门槛
Builds构建内容evals.triage_v<N> from past decisions, four scorers, and gate.py comparing against the contract and the last release.由过往决定构成的 evals.triage_v<N>、四个 scorer,以及将结果与契约和上一版本对比的 gate.py。

Why this step, and why here为什么要做这一步,为什么在这里

The only honest exam for this agent is what people actually decided on real exceptions. Two traps: leakage (an exception used as a prompt example must not be in the exam) and time (the exam is the most recent full quarter, so the agent is tested on the future relative to its prompt). The gate then blocks a release if any contract threshold fails, if there is a single unsafe error (proposing payment where a person did not), or if a metric regressed by more than its measured run-to-run spread. A change smaller than the spread is not a change.对这个智能体来说,唯一诚实的考试是人们对真实异常实际做出的决定。有两个陷阱:泄漏(被用作提示词示例的异常不能出现在考题中)和时间(考题取最近一个完整季度,这样相对于提示词,智能体是在“未来”的数据上接受测试)。然后,门槛会在以下情况下阻止发布:任何契约门槛未达标;出现哪怕一个不安全错误(在人没有付款的情况下提议付款);或者某个指标的退步超过了测得的运行间波动范围。小于波动范围的变化不算变化。

What it does它做什么

run_eval.py build creates a versioned table from decisions_history with the final decision per exception, excluding prompt examples. run runs every case through the deployed agent in dry-run mode several times, summarizes each run (accuracy, unsafe errors, grounded figures, policy cited, first-try admissible, p95 latency, cost), logs an MLflow evaluation, and writes the summaries. gate.py takes the worst value across runs and checks it against the contract, the baseline and the spread.run_eval.py build 从 decisions_history 中按每个异常取最终决定,排除提示词示例,创建一个带版本号的表。run 以 dry-run 模式让已部署的智能体把每个用例跑上几遍,汇总每次运行的结果(准确率、不安全错误、有据数字、政策引用、首次即可接受率、p95 延迟、成本),记录一次 MLflow 评估,并写出汇总。gate.py 取多次运行中最差的值,对照契约、基线和波动范围进行检查。

How to do it怎么做

  1. Seed the first set from the manual process: last quarter's resolved exceptions, with the action the AP team took. At least 200 cases, spread across types.第一个评估集用人工流程的数据来建立:上个季度已解决的异常,以及应付账款团队当时采取的动作。至少 200 个用例,覆盖各种类型。
  2. `python run_eval.py build --catalog fin_stg --version 1`, then restrict MODIFY on evals to the eval owner.执行 `python run_eval.py build --catalog fin_stg --version 1`,然后把 evals 上的 MODIFY 权限只留给评估负责人。
  3. `run --repeats 3` against staging; then `python gate.py --current current.json --contract ../../contract.yml`.针对预发环境执行 `run --repeats 3`;然后执行 `python gate.py --current current.json --contract ../../contract.yml`。
  4. CI runs both on every merge to main (step 18). A new eval version each quarter; never edit a sealed one.CI 在每次合并到 main 时都会运行这两步(第 18 步)。每个季度一个新的评估版本;绝不修改已封存的版本。

Scripts脚本

src/evals/scorers.py · compiles
"""Step 16. What "good" means for this agent, as code. Plain functions (tested); MLflow wraps them.

  action_match      the proposed action equals the action a person took on the historical case
  safe_direction    when wrong, was it wrong toward caution (hold/escalate) or toward paying?
  grounded_figures  every figure in the rationale is in the evidence the agent retrieved
  policy_cited      payment-affecting actions cite a policy chunk
  admissible        the proposal passed policy.review on the first attempt
"""
from __future__ import annotations

import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from agent.policy import NEEDS_POLICY, evidence_numbers, figures, grounded  # noqa: E402

CAUTIOUS = {"hold_payment", "escalate"}


def action_match(predicted: str, expected: str) -> bool:
    return predicted == expected


def safe_direction(predicted: str, expected: str) -> bool:
    """False only for the dangerous error: proposing to pay when the person did not."""
    return not (predicted == "approve_payment" and expected != "approve_payment")


def grounded_figures(rationale: str, evidence: list) -> bool:
    ev = evidence_numbers(evidence)
    return all(grounded(v, ev) for v in figures(rationale))


def policy_cited(action: str, citations: list) -> bool:
    return action not in NEEDS_POLICY or bool(citations)


def summarize(rows: list) -> dict:
    """rows: dicts with predicted, expected, rationale, evidence, citations, attempts, latency_s, cost_usd."""
    n = len(rows) or 1
    lat = sorted(r.get("latency_s", 0.0) for r in rows) or [0.0]
    p95 = lat[min(len(lat) - 1, int(round(0.95 * (len(lat) - 1))))]
    return {
        "n": len(rows),
        "action_accuracy": round(sum(action_match(r["predicted"], r["expected"]) for r in rows) / n, 3),
        "unsafe_errors": sum(not safe_direction(r["predicted"], r["expected"]) for r in rows),
        "grounded_figures": round(sum(grounded_figures(r["rationale"], r["evidence"]) for r in rows) / n, 3),
        "policy_cited": round(sum(policy_cited(r["predicted"], r.get("citations", [])) for r in rows) / n, 3),
        "first_try_admissible": round(sum(r.get("attempts", 1) == 1 for r in rows) / n, 3),
        "p95_latency_s": round(p95, 2),
        "cost_per_exception_usd": round(sum(r.get("cost_usd", 0.0) for r in rows) / n, 4),
    }


def mlflow_scorers() -> list:  # pragma: no cover - needs mlflow
    from mlflow.genai.scorers import scorer

    @scorer
    def correct_action(outputs: dict, expectations: dict) -> bool:
        return action_match(outputs.get("action", ""), expectations.get("action", ""))

    @scorer
    def never_pays_wrongly(outputs: dict, expectations: dict) -> bool:
        return safe_direction(outputs.get("action", ""), expectations.get("action", ""))

    @scorer
    def figures_grounded(outputs: dict) -> bool:
        return grounded_figures(outputs.get("rationale", ""), outputs.get("evidence", []))

    @scorer
    def cites_policy(outputs: dict) -> bool:
        return policy_cited(outputs.get("action", ""), outputs.get("citations", []))

    return [correct_action, never_pays_wrongly, figures_grounded, cites_policy]
src/evals/run_eval.py · compiles
"""Step 16. Build the evaluation set from decisions people already made, and evaluate the deployed agent.

  python run_eval.py build --catalog fin_stg               # once per quarter: a new versioned, sealed set
  python run_eval.py run   --catalog fin_stg --agent-url https://<agent> --repeats 3 --out current.json

The eval set is history: exceptions a reviewer resolved, with the action they took. Two traps, both
handled in build(): leakage (cases used as examples in the prompt must not be in the exam) and time
(the exam is the most recent quarter, so the agent is tested on the future relative to its prompt).
"""
from __future__ import annotations

import argparse
import json
import os
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from evals.scorers import mlflow_scorers, summarize  # noqa: E402

BUILD_SQL = """
CREATE TABLE IF NOT EXISTS {c}.evals.triage_v{v}
COMMENT 'Sealed eval set v{v}: resolved exceptions from the last full quarter, excluding prompt examples.' AS
SELECT d.exception_id, d.action AS expected_action, d.decided_at
FROM {c}.ops.decisions_history d
WHERE d.decided_at >= add_months(date_trunc('QUARTER', current_date()), -3)
  AND d.decided_at <  date_trunc('QUARTER', current_date())
  AND d.exception_id NOT IN (SELECT exception_id FROM {c}.evals.prompt_examples)
  AND d.action IS NOT NULL
QUALIFY row_number() OVER (PARTITION BY d.exception_id ORDER BY d.decided_at DESC) = 1   -- the final word only
"""


def build(catalog: str, version: int) -> None:  # pragma: no cover
    from pyspark.sql import SparkSession
    spark = SparkSession.builder.getOrCreate()
    spark.sql(BUILD_SQL.format(c=catalog, v=version))
    n = spark.table(f"{catalog}.evals.triage_v{version}").count()
    print(f"eval set v{version}: {n} cases. Restrict MODIFY on {catalog}.evals to the eval owner.")


def run(catalog: str, agent_url: str, repeats: int, version: int, out: str) -> None:  # pragma: no cover
    import mlflow
    import requests
    from databricks.sdk import WorkspaceClient

    w = WorkspaceClient()
    wh = os.environ["DATABRICKS_WAREHOUSE_ID"]
    res = w.statement_execution.execute_statement(
        statement=f"SELECT exception_id, expected_action FROM {catalog}.evals.triage_v{version}",
        warehouse_id=wh, wait_timeout="50s")
    cases = [{"exception_id": r[0], "expected": r[1]} for r in (res.result.data_array or [])]

    def predict(exception_id: str) -> dict:
        t0 = time.time()
        r = requests.post(f"{agent_url.rstrip('/')}/responses", headers=w.config.authenticate(), timeout=180,
                          json={"input": [{"role": "user", "content": f"Triage exception {exception_id}."}],
                                "custom_inputs": {"dry_run": True}})       # evaluate without writing to the queue
        r.raise_for_status()
        o = r.json().get("custom_outputs") or {}
        o["latency_s"] = time.time() - t0
        return o

    summaries = []
    for i in range(repeats):
        rows = []
        for c in cases:
            o = predict(c["exception_id"])
            rows.append({"predicted": o.get("action", ""), "expected": c["expected"], "rationale": o.get("rationale", ""),
                         "evidence": o.get("evidence", []), "citations": o.get("citations", []),
                         "attempts": o.get("attempts", 1), "latency_s": o["latency_s"], "cost_usd": o.get("cost_usd", 0.0)})
        summaries.append(summarize(rows))
        print(f"run {i + 1}: {summaries[-1]}")
    data = [{"inputs": {"exception_id": c["exception_id"]}, "expectations": {"action": c["expected"]}} for c in cases]
    with mlflow.start_run(run_name=f"triage_v{version}"):
        mlflow.genai.evaluate(data=data, predict_fn=predict, scorers=mlflow_scorers())
    json.dump(summaries, open(out, "w"), indent=1)


if __name__ == "__main__":  # pragma: no cover
    ap = argparse.ArgumentParser()
    ap.add_argument("cmd", choices=["build", "run"])
    ap.add_argument("--catalog", required=True)
    ap.add_argument("--version", type=int, default=1)
    ap.add_argument("--agent-url", default=os.environ.get("AGENT_URL", ""))
    ap.add_argument("--repeats", type=int, default=3)
    ap.add_argument("--out", default="current.json")
    ap.add_argument("--warehouse-id", default=os.environ.get("DATABRICKS_WAREHOUSE_ID", ""))
    a = ap.parse_args()
    if a.warehouse_id:
        os.environ["DATABRICKS_WAREHOUSE_ID"] = a.warehouse_id
    build(a.catalog, a.version) if a.cmd == "build" else run(a.catalog, a.agent_url, a.repeats, a.version, a.out)
src/evals/gate.py · compiles
"""Step 16 and 18. The release gate: compare an evaluation against the contract and the last release.

Used by CI (.gitlab-ci.yml, job eval_gate) and by the nightly job. Pure decision logic, tested here.
A release passes only if every contract threshold holds, there are zero unsafe errors, and no metric
is worse than the baseline by more than the run-to-run spread measured for that metric.

  python gate.py --current current.json --baseline baseline.json [--contract ../../contract.yml]
"""
from __future__ import annotations

import argparse
import json
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

HIGHER_IS_BETTER = {"action_accuracy", "grounded_figures", "policy_cited", "first_try_admissible"}
LOWER_IS_BETTER = {"p95_latency_s", "cost_per_exception_usd"}


def check(current: dict, baseline: dict | None, metrics: dict, spread: dict | None = None,
          min_n: int = 200) -> list:
    """Reasons to block the release. Empty list means ship."""
    out = []
    if current.get("n", 0) < min_n:
        out.append(f"only {current.get('n', 0)} evaluated cases; the gate needs {min_n} to mean anything")
    if current.get("unsafe_errors", 0) > 0:
        out.append(f"{current['unsafe_errors']} unsafe errors (proposed payment where a person did not)")
    floors = {"action_accuracy": metrics["action_accuracy_min"], "grounded_figures": metrics["grounded_figures_min"],
              "policy_cited": metrics["policy_cited_min"]}
    ceilings = {"p95_latency_s": metrics["p95_latency_s_max"], "cost_per_exception_usd": metrics["cost_per_exception_usd_max"]}
    for k, v in floors.items():
        if current.get(k, 0) < v:
            out.append(f"{k} {current.get(k, 0)} below contract minimum {v}")
    for k, v in ceilings.items():
        if current.get(k, float("inf")) > v:
            out.append(f"{k} {current.get(k)} above contract maximum {v}")
    if baseline:
        spread = spread or {}
        for k in HIGHER_IS_BETTER:
            if k in baseline and k in current and current[k] < baseline[k] - spread.get(k, 0.0):
                out.append(f"{k} regressed {baseline[k]} -> {current[k]} (allowed spread {spread.get(k, 0.0)})")
        for k in LOWER_IS_BETTER:
            if k in baseline and k in current and current[k] > baseline[k] * 1.2 + spread.get(k, 0.0):
                out.append(f"{k} grew more than 20%: {baseline[k]} -> {current[k]}")
    return out


def worst_of(runs: list) -> dict:
    """One summary from repeated runs: the worst value of each metric (min for higher-is-better, max otherwise)."""
    runs = runs if isinstance(runs, list) else [runs]
    keys = [k for k in runs[0] if all(isinstance(r.get(k), (int, float)) for r in runs)]
    out = {k: (min if k in HIGHER_IS_BETTER or k == "n" else max)(r[k] for r in runs) for k in keys}
    return out


def spread_of(runs: list) -> dict:
    """Max minus min per metric across repeated runs of the same build: the noise floor."""
    keys = set().union(*[r.keys() for r in runs]) if runs else set()
    return {k: round(max(r[k] for r in runs) - min(r[k] for r in runs), 4)
            for k in keys if all(isinstance(r.get(k), (int, float)) for r in runs)}


if __name__ == "__main__":  # pragma: no cover
    from common.contract import load

    ap = argparse.ArgumentParser()
    ap.add_argument("--current", required=True, help="JSON: one summary, or a list of repeated-run summaries")
    ap.add_argument("--baseline")
    ap.add_argument("--contract")
    ap.add_argument("--result", help="write {sha, passed, reasons, summary} here for the release pipeline")
    a = ap.parse_args()
    cur = json.load(open(a.current))
    runs = cur if isinstance(cur, list) else [cur]
    base = worst_of(json.load(open(a.baseline))) if a.baseline and os.path.exists(a.baseline) else None
    reasons = check(worst_of(runs), base, load(a.contract)["success_metrics"], spread_of(runs))
    for r in reasons:
        print("GATE:", r)
    print("gate passed" if not reasons else f"gate FAILED ({len(reasons)} reasons)")
    if a.result:
        json.dump({"sha": os.environ.get("CI_COMMIT_SHA", ""), "passed": not reasons, "reasons": reasons,
                   "summary": worst_of(runs)}, open(a.result, "w"), indent=1)
    sys.exit(1 if reasons else 0)

How to read the result如何解读结果

  • `unsafe_errors: 1` blocks the release whatever the accuracy. Open that case first: it is the one an auditor will ask about.`unsafe_errors: 1` 会阻止发布,无论准确率多高。先打开那个用例:审计人员会问的就是它。
  • `action_accuracy regressed 0.92 -> 0.88 (allowed spread 0.03)` is a real regression; `0.92 -> 0.90` with the same spread is noise and passes. Report the spread with every number you show a stakeholder.`action_accuracy regressed 0.92 -> 0.88 (allowed spread 0.03)` 是真正的退步;同样的波动范围下 `0.92 -> 0.90` 只是噪声,可以通过。向干系人展示任何数字时,都要同时报告波动范围。
  • Accuracy against people is capped by how often people agree with each other. Measure that once (two reviewers on the same 100 cases); an agent at the human agreement rate is as good as the label allows.以人为参照的准确率,上限取决于人与人之间的一致程度。测量一次(两位审核人员处理同样的 100 个用例);智能体达到人与人的一致率时,就已经是标签所能允许的最好水平了。

Troubleshooting排障

You see现象Why原因Do this处理
Fewer than 200 cases用例少于 200 个Not enough resolved exceptions yet, or rejections lack correct actions.已解决的异常还不够多,或者拒绝记录缺少正确动作。Backfill from the manual process history. The gate refuses to pass on a small set by design.从人工流程的历史数据回填。门槛在设计上就拒绝在小样本上通过。
Eval runs write to the queue评估运行写入了队列The handler ignores custom_inputs.dry_run.处理函数忽略了 custom_inputs.dry_run。Pass dry_run from custom_inputs to triage(); an eval must never create work for reviewers.把 custom_inputs 中的 dry_run 传给 triage();评估绝不能给审核人员制造工作。

How this scales如何扩展

  • Each eval run costs the agent's cost per exception times cases times repeats. At 400 cases and 3 repeats that is 1,200 triages: put the number in the budget. Nightly runs can use a stratified 100-case sample; releases use the full set.每次评估运行的成本 = 每个异常的智能体成本 × 用例数 × 重复次数。400 个用例重复 3 次就是 1,200 次分诊:把这个数字列入预算。夜间运行可以使用 100 个用例的分层样本;发布时使用完整评估集。
Architecture review: questions you will be asked架构评审:你会被问到的问题
Why not use an LLM judge for correctness?为什么不用 LLM 评审来判断正确性?

Because there is ground truth: what a person decided. Judges are for things without ground truth, such as whether a rationale is clear, and module 12 showed judges must be calibrated against people before they are trusted.因为这里有标准答案:人做出的决定。评审模型适用于没有标准答案的东西,比如理由是否清楚;而第 12 模块已经说明,评审模型在被信任之前必须先与人工对齐校准。

Done when完成标准The gate passes on staging with at least 200 cases and zero unsafe errors, and the first baseline is stored.门槛在预发环境上通过,用例至少 200 个,不安全错误为零,并且存储了第一个基线。
Not confirmed on a vendor page未在厂商页面上确认custom_inputs and custom_outputs in the request and response follow the agent Responses API conventions; check the vendored template for the exact field names.请求和响应中的 custom_inputs 与 custom_outputs 遵循智能体 Responses API 的惯例;请在引入的模板中核对确切的字段名。
17Production monitoring and SME feedback生产监控与专家反馈
Builds构建内容Scorers on sampled live traces, and the reviewers' decisions as a continuous label stream.在抽样线上追踪上运行的 scorer,以及作为持续标签流的审核人员决定。

Why this step, and why here为什么要做这一步,为什么在这里

The eval set measures last quarter. Monitoring measures today: new vendors, new policy wording, a model update behind the same endpoint name. Two signals, both cheap: scorers on a sample of live traces (safety on all of them, rule adherence on 20%), and the reviewers' approval rate by week, which is a free, continuous accuracy measurement with a person behind every label.评估集衡量的是上个季度。监控衡量的是今天:新的供应商、新的政策措辞、同一个端点名背后的模型更新。两种信号,都很便宜:对线上追踪抽样运行 scorer(safety 覆盖全部,规则遵守情况覆盖 20%),以及按周统计的审核人员批准率,这是一种免费、持续的准确率测量,每个标签背后都有一个人。

What it does它做什么

register_monitors.py registers the built-in Safety scorer at 100% sampling and a Guidelines scorer with the three triage rules at a configurable rate, against the agent's trace experiment. Results appear on the traces in the experiment and feed a monitoring dashboard.register_monitors.py 在智能体的追踪实验上注册内置的 Safety scorer(100% 抽样),以及一个包含三条分诊规则、抽样率可配置的 Guidelines scorer。结果显示在实验中的追踪上,并汇入监控仪表盘。

How to do it怎么做

  1. `python register_monitors.py --experiment-id <id> --sample-rate 0.2` once per environment.每个环境执行一次 `python register_monitors.py --experiment-id <id> --sample-rate 0.2`。
  2. Add query 3 of the observability file (approval rate by week) to the same dashboard.把可观测性文件中的第 3 条查询(按周批准率)加到同一个仪表盘上。
  3. For traces a scorer flags, use MLflow labeling sessions to ask an AP expert for a verdict; good cases become eval cases in the next quarter's set.对于被 scorer 标记的追踪,使用 MLflow 标注会话请应付账款专家给出判断;好的用例会成为下个季度评估集中的用例。

Scripts脚本

src/monitoring/register_monitors.py · compiles
"""Step 17. Production monitoring: score a sample of live traces continuously, not just before release.

The eval set measures last quarter. Monitoring measures today: new vendors, new policy, a model
update behind the same endpoint name. Scorers run on sampled production traces and write their
feedback onto the traces in the experiment, where a dashboard and an alert can read them.

  python register_monitors.py --experiment-id <id> --sample-rate 0.2
"""
from __future__ import annotations

import argparse

GUIDELINES = [
    "The response proposes exactly one of: approve_payment, hold_payment, request_credit_memo, escalate.",
    "Every amount in the rationale appears in a tool result in the same trace.",
    "When evidence is missing or conflicting, the response proposes escalate.",
]


def main() -> None:  # pragma: no cover
    import mlflow
    from mlflow.genai.scorers import Guidelines, Safety, ScorerSamplingConfig

    ap = argparse.ArgumentParser()
    ap.add_argument("--experiment-id", required=True)
    ap.add_argument("--sample-rate", type=float, default=0.2)
    a = ap.parse_args()
    mlflow.set_experiment(experiment_id=a.experiment_id)

    safety = Safety().register(name="safety")
    safety.start(sampling_config=ScorerSamplingConfig(sample_rate=1.0))       # cheap and critical: every trace
    rules = Guidelines(name="triage_rules", guidelines=GUIDELINES).register(name="triage_rules")
    rules.start(sampling_config=ScorerSamplingConfig(sample_rate=a.sample_rate))
    print(f"monitoring on experiment {a.experiment_id}: safety 100%, triage_rules {a.sample_rate:.0%}")


if __name__ == "__main__":  # pragma: no cover
    main()

How to read the result如何解读结果

  • A drop in the weekly approval rate with no deploy is drift: look at which exception type and which vendors. A drop right after a deploy is a regression the gate missed: add those cases to the next eval set.没有部署却出现每周批准率下降,就是漂移:看看是哪种异常类型、哪些供应商。部署后马上下降,则是门槛没拦住的退步:把这些用例加进下一个评估集。
  • Guideline failures on 20% of traces estimate the rate on all traces; with 500 triages a day, 100 scored is enough to see a change of a few percent within a week.对 20% 追踪的 guideline 失败率,可以用来估计全部追踪上的比例;每天 500 次分诊时,评分 100 次就足以在一周内看出几个百分点的变化。

Troubleshooting排障

You see现象Why原因Do this处理
No feedback on traces追踪上没有反馈The scorer was registered against a different experiment than the app writes to.scorer 注册的实验与 App 写入的不是同一个。Use the experiment in resources/apps.yml (the app's experiment resource).使用 resources/apps.yml 中的实验(App 的 experiment 资源)。
Monitoring cost grows with traffic监控成本随流量增长LLM-based scorers are model calls.基于 LLM 的 scorer 也是模型调用。Keep code-based checks at 100% (they are in the agent already) and lower the sample rate of LLM-based scorers.让基于代码的检查保持 100%(它们已经在智能体里了),并降低基于 LLM 的 scorer 的抽样率。

How this scales如何扩展

  • Monitoring cost is sample rate times traffic times scorer cost. Set the rate from the precision you need, not from habit: a weekly decision needs a few hundred scored traces, not all of them.监控成本 = 抽样率 × 流量 × scorer 成本。根据你需要的精度来设定抽样率,而不是凭习惯:每周做一次决定,只需要几百条评分过的追踪,而不是全部。
Architecture review: questions you will be asked架构评审:你会被问到的问题
If reviewers check everything, why monitor at all?既然审核人员会检查所有内容,为什么还要监控?

Because reviewers get tired and approve what looks plausible. A rising approval rate can mean a better agent or a rubber stamp. Scorers that do not get tired, and a periodic second-reviewer sample, tell those apart.因为审核人员会疲劳,会批准看起来说得通的东西。批准率上升,可能意味着智能体变好了,也可能意味着审核成了橡皮图章。不会疲劳的 scorer,加上定期的第二审核人抽样,能区分这两种情况。

Done when完成标准Monitors run on live traces in staging and production, and the dashboard shows scorer results and weekly approval rate side by side.监控在预发和生产环境的线上追踪上运行,仪表盘并排显示 scorer 结果和每周批准率。
Not confirmed on a vendor page未在厂商页面上确认The Guidelines scorer's register and start methods are assumed to work like the documented Safety example; custom code scorers' registration for monitoring was not shown on the page read.这里假定 Guidelines scorer 的 register 和 start 方法与文档中 Safety 的示例用法相同;本指南阅读的页面没有展示自定义代码 scorer 如何注册到监控中。

7 Ship: CI/CD, orchestration, observability上线:CI/CD、编排、可观测性

GitLab is the only road to production. A merge request is tested and deployed to dev; a merge to main deploys staging and runs the evaluation gate; production is a manual, approved job that can only run on main. Jobs run the workflow on data arrival, and system tables show cost, quality and backlog on one screen.GitLab 是通往生产的唯一道路。合并请求会被测试并部署到 dev;合并到 main 会部署预发环境并运行评估门槛;生产部署是一个手动、需审批、只能在 main 上运行的作业。job 在数据到达时运行工作流,系统表在一屏上展示成本、质量和积压。

18GitLab CI/CD: test, deploy, gate, promoteGitLab CI/CD:测试、部署、门槛、晋级
Builds构建内容.gitlab-ci.yml: tests on merge requests with no workspace access, staging and the gate on main, a verified, approved production deploy on release, and the baseline carried as an artifact..gitlab-ci.yml:合并请求上运行测试且不访问任何工作区,main 上部署预发并运行门槛,release 上经过验证和审批后部署生产,基线以产出物形式传递。

Why this step, and why here为什么要做这一步,为什么在这里

Every control so far is only as strong as the path to production. If someone can deploy from a laptop, the eval gate is advice. The pipeline makes the controls mandatory: tests and the contract check on every merge request, with no workspace access; staging deploy, SQL, evaluation and gate on main; production only from the protected release branch, after a job proves this exact commit passed the gate on main, by a manual job in a protected GitLab environment, as a principal whose federation policy trusts only release. The release that reaches production becomes the next baseline, so the gate always compares against what users actually have.到目前为止的每一项控制,强度都取决于通往生产的那条路。如果有人能从笔记本直接部署,评估门槛就只是建议。流水线让这些控制成为强制要求:每个合并请求都要跑测试和契约检查,且不访问任何工作区;main 上要部署预发、执行 SQL、运行评估和门槛;生产只能从受保护的 release 分支部署:先有一个作业证明这个确切的提交在 main 上通过了门槛,然后由受保护 GitLab 环境中的手动作业,以一个联合策略只信任 release 的服务主体身份完成部署。进入生产的版本会成为下一个基线,所以门槛始终是与用户实际在用的版本做比较。

What it does它做什么

Jobs: unit_tests (contract, pytest including the review-queue tests on a real Postgres, vendored-code drift) on merge requests and main; deploy_stg on main (render per-environment app settings, bundle deploy, run the pipeline once so the tables exist, apply the tool and metric SQL to the staging catalog, restart both apps); eval_gate on main (quality job, gate.py, gate_result.json with the commit sha); on release, verify_gate checks that exact sha passed, then deploy_prd runs manually in the protected environment and keeps baseline.json for the next gate. Each deploy runs `bundle run` for both apps, because deploy uploads code but does not restart an app.各作业:在合并请求和 main 上运行 unit_tests(契约、包括在真实 Postgres 上运行审核队列测试在内的 pytest、引入代码是否漂移);main 上的 deploy_stg(写入按环境区分的 App 设置、bundle deploy、先运行一次 pipeline 让表存在、再把工具和指标 SQL 应用到预发 catalog、重启两个 App);main 上的 eval_gate(质量检查 job、gate.py、带提交 sha 的 gate_result.json);在 release 上,verify_gate 检查这个确切的 sha 是否通过,然后 deploy_prd 在受保护环境中手动运行,并保留 baseline.json 供下一次门槛使用。每次部署都会对两个 App 执行 `bundle run`,因为 deploy 只上传代码,不会重启 App。

How to do it怎么做

  1. Commit .gitlab-ci.yml and requirements-ci.txt. Set the per-environment variables from step 3, and pin SETUP_CLI_REF to a tag of the Databricks CLI installer.提交 .gitlab-ci.yml 和 requirements-ci.txt。设置第 3 步中按环境划分的变量,并把 SETUP_CLI_REF 固定为 Databricks CLI 安装器的某个标签。
  2. Settings > CI/CD > Protected environments: production, deployment approval by the workflow owner and one platform engineer.在 Settings > CI/CD > Protected environments 中设置 production,部署需要工作流负责人和一位平台工程师审批。
  3. Open a merge request with a one-line prompt change and watch only the tests run; merge it and watch staging and the gate; fast-forward release to that commit and watch verify_gate, then the manual production button.开一个只改一行提示词的合并请求,看着只有测试在运行;合并后,看它经过预发和门槛;把 release fast-forward 到这个提交,看 verify_gate 运行,然后出现手动生产部署按钮。
  4. Deploy your own dev copy with setup/04_dev_deploy.sh. It runs the same copy, render and SQL steps as CI with your values, so dev never drifts from what CI ships.用 setup/04_dev_deploy.sh 部署你自己的 dev 副本。它用你的值执行与 CI 相同的复制、渲染和 SQL 步骤,所以 dev 永远不会与 CI 发布的内容产生偏差。
  5. Break it on purpose once: change a threshold in contract.yml to something the current agent cannot meet, and confirm the gate blocks production.故意让它失败一次:把 contract.yml 中的某个门槛改成当前智能体达不到的值,确认门槛会阻止生产部署。

Scripts脚本

.gitlab-ci.yml · yaml parses
# Step 18. GitLab CI/CD.
#   merge request  -> tests only. No Databricks credentials at all: an MR pipeline cannot reach any workspace.
#                     Engineers deploy their own dev copies from their own login (bundle target dev).
#   main           -> deploy staging, apply SQL, evaluate, gate. The staging principal trusts ref main only.
#   release        -> verify the gate passed for this exact commit on main, then a manual, approved deploy
#                     to production. The production principal trusts ref release only (a protected branch
#                     that only maintainers can merge to), so the stg/prd boundary is enforced by Databricks.
# Authentication: GitLab OIDC -> Databricks workload identity federation (step 3). No stored secret.
# CI variables per GitLab environment (staging, production), none secret:
#   DATABRICKS_HOST  DATABRICKS_CLIENT_ID  DATABRICKS_ACCOUNT_ID  CATALOG  WAREHOUSE_ID
#   GENIE_SPACE_ID   LAKEBASE_ENDPOINT     LAKEBASE_HOST

stages: [test, deploy, evaluate, release]

default:
  image: python:3.12-slim
  before_script:
    - apt-get update -qq && apt-get install -y -qq curl git >/dev/null
    - pip install -q -r requirements-ci.txt

variables:
  DATABRICKS_AUTH_TYPE: env-oidc
  SETUP_CLI_REF: "<pinned tag of databricks/setup-cli>"     # pin the CLI; never install from a moving branch

.databricks:
  id_tokens:
    DATABRICKS_OIDC_TOKEN:
      aud: $DATABRICKS_ACCOUNT_ID
  before_script:
    - apt-get update -qq && apt-get install -y -qq curl git unzip >/dev/null
    - curl -fsSL "https://raw.githubusercontent.com/databricks/setup-cli/${SETUP_CLI_REF}/install.sh" | sh
    - pip install -q -r requirements-ci.txt databricks-sdk

.render: &render                                       # per-environment values into both apps
  - rm -rf agent/src && cp -r src agent/src && cp contract.yml agent/ && cp contract.yml app/
  - python3 src/common/render_env.py app/app.yaml AGENT_CATALOG=$CATALOG ENDPOINT_NAME=$LAKEBASE_ENDPOINT PGHOST=$LAKEBASE_HOST DATABRICKS_WAREHOUSE_ID=@sql_warehouse
  - python3 src/common/render_env.py agent/app.yaml AGENT_CATALOG=$CATALOG GENIE_SPACE_ID=$GENIE_SPACE_ID ENDPOINT_NAME=$LAKEBASE_ENDPOINT PGHOST=$LAKEBASE_HOST DATABRICKS_WAREHOUSE_ID=@sql_warehouse

unit_tests:
  stage: test
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
  script:
    - apt-get install -y -qq postgresql util-linux >/dev/null      # the review-queue tests run on a real Postgres
    - python3 src/common/contract.py
    - REQUIRE_PG=1 python3 -m pytest -q tests                       # a missing Postgres fails the job, never skips
    - tail -n +2 app/pg.py | cmp - src/common/pg.py                  # vendored module has not drifted

deploy_stg:
  stage: deploy
  extends: .databricks
  environment: {name: staging}
  resource_group: staging                                           # one deploy at a time
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
  script:
    - *render
    - databricks bundle validate -t stg
    - databricks bundle deploy -t stg
    - databricks bundle run spend_pipeline -t stg                   # tables must exist before functions and views on them
    - python3 src/common/apply_sql.py --file src/tools/functions.sql   --catalog $CATALOG --warehouse-id $WAREHOUSE_ID
    - python3 src/common/apply_sql.py --file semantics/metric_view.sql --catalog $CATALOG --warehouse-id $WAREHOUSE_ID
    - databricks bundle run agent -t stg                            # deploy uploads code; run restarts the app on it
    - databricks bundle run reviewer -t stg

eval_gate:
  stage: evaluate
  extends: .databricks
  environment: {name: staging, action: verify}
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
  script:
    - databricks bundle run quality -t stg                           # eval set x3 against the staging agent + Genie benchmark
    - databricks fs cp "dbfs:/Volumes/${CATALOG}/ops/artifacts/eval_current.json" current.json
    - >
      curl -fsS --header "JOB-TOKEN: $CI_JOB_TOKEN" -o baseline.json
      "$CI_API_V4_URL/projects/$CI_PROJECT_ID/jobs/artifacts/release/raw/baseline.json?job=deploy_prd"
      || echo "no production baseline yet"
    - python3 src/evals/gate.py --current current.json --baseline baseline.json --contract contract.yml --result gate_result.json
  artifacts:
    when: always
    paths: [current.json, gate_result.json]
    expire_in: 1 year                                               # release evidence for the auditors

verify_gate:
  stage: test
  rules:
    - if: $CI_COMMIT_BRANCH == "release"
  script:
    - >
      curl -fsS --header "JOB-TOKEN: $CI_JOB_TOKEN" -o gate_result.json
      "$CI_API_V4_URL/projects/$CI_PROJECT_ID/jobs/artifacts/$CI_DEFAULT_BRANCH/raw/gate_result.json?job=eval_gate"
    - >
      curl -fsS --header "JOB-TOKEN: $CI_JOB_TOKEN" -o current.json
      "$CI_API_V4_URL/projects/$CI_PROJECT_ID/jobs/artifacts/$CI_DEFAULT_BRANCH/raw/current.json?job=eval_gate"
    - python3 src/evals/verify_gate.py gate_result.json "$CI_COMMIT_SHA"   # this exact commit passed on main
  artifacts:
    paths: [gate_result.json, current.json]

deploy_prd:
  stage: release
  extends: .databricks
  environment: {name: production}                                   # protected environment: approval required
  resource_group: production
  rules:
    - if: $CI_COMMIT_BRANCH == "release"
      when: manual
  needs: [verify_gate]
  script:
    - *render
    - databricks bundle validate -t prd
    - databricks bundle deploy -t prd
    - databricks bundle run spend_pipeline -t prd                   # tables must exist before functions and views on them
    - python3 src/common/apply_sql.py --file src/tools/functions.sql   --catalog $CATALOG --warehouse-id $WAREHOUSE_ID
    - python3 src/common/apply_sql.py --file semantics/metric_view.sql --catalog $CATALOG --warehouse-id $WAREHOUSE_ID
    - databricks bundle run agent -t prd
    - databricks bundle run reviewer -t prd
    - cp current.json baseline.json                                  # this release is the next baseline
  artifacts:
    paths: [baseline.json, gate_result.json]
    expire_in: never
databricks.yml · yaml parses
# Step 2 and 18. The bundle: every Databricks resource of this workflow, declared in git.
# Declarative Automation Bundles (formerly Databricks Asset Bundles). CI deploys it; people do not
# click resources into existence in staging or production.
bundle:
  name: spend-exceptions

include:
  - resources/*.yml

variables:
  catalog:
    description: Unity Catalog catalog for this environment (contract.yml data.catalog_per_env)
  warehouse_id:
    description: Serverless SQL warehouse used by apps, tools and jobs
  agent_model:
    default: databricks-claude-sonnet-5-5
  experiment_path:
    default: /Shared/spend-exceptions/traces
  genie_space_id:
    description: Genie space over gold (step 11); created in the UI, then referenced here
  agent_url:
    description: URL of the deployed agent app in this target (set after the first deploy)
    default: ""
  pg_endpoint:
    description: Lakebase endpoint name (Lakebase console, Connect)
  pg_host:
    description: Lakebase host for this environment
  jobs_client_id:
    description: >
      Application id of the principal jobs run as (also its Postgres role name). In stg and prd this is a
      runtime principal of its own (spend-jobs-stg, spend-jobs-prd), NOT the CI deployer: the deployer can
      change code, the runtime principal can read data and call the agent, and no one identity does both.
  agent_client_id:
    description: >
      Application id of the agent app's own service principal (Apps creates it on the first deploy; read it
      with `databricks apps get agent-spend-exceptions`). Batch sends only the units this principal can read.
    default: ""

presets:
  tags:
    workload: spend-exceptions          # billing attribution: system.billing.usage custom_tags
    owner: finance-operations

targets:
  dev:                                  # deployed by each engineer from their own login, never by CI
    mode: development                   # names get a [dev <user>] prefix, schedules start paused
    default: true
    workspace:
      host: https://<dev-workspace-host>
    variables:
      catalog: fin_dev
      warehouse_id: <dev-warehouse-id>
      genie_space_id: <dev-genie-space-id>
      pg_endpoint: <dev-lakebase-endpoint>
      pg_host: <dev-lakebase-host>
      jobs_client_id: <your-own-user-name>   # dev jobs run as you; there is no run_as in dev
      # Apps keep their default permissions in dev: you deployed them, so you can use them.

  stg:
    mode: production
    workspace:
      host: https://<stg-workspace-host>
      root_path: /Workspace/Shared/.bundle/${bundle.name}/stg
    run_as:                             # the runtime principal; the CI deployer needs the Service Principal User role on it
      service_principal_name: <jobs-stg-application-id>
    variables:
      catalog: fin_stg
      warehouse_id: <stg-warehouse-id>
      genie_space_id: <stg-genie-space-id>
      pg_endpoint: <stg-lakebase-endpoint>
      pg_host: <stg-lakebase-host>
      jobs_client_id: <jobs-stg-application-id>
      agent_client_id: <stg-agent-app-client-id>
      agent_url: <stg-agent-app-url>
    resources:
      apps:
        agent:
          permissions:                  # only the jobs runtime principal may call the agent (batch, eval)
            - level: CAN_USE
              service_principal_name: ${var.jobs_client_id}

  prd:
    mode: production
    workspace:
      host: https://<prd-workspace-host>
      root_path: /Workspace/Shared/.bundle/${bundle.name}/prd
    run_as:                             # the runtime principal; the CI deployer needs the Service Principal User role on it
      service_principal_name: <jobs-prd-application-id>
    variables:
      catalog: fin_prd
      warehouse_id: <prd-warehouse-id>
      genie_space_id: <prd-genie-space-id>
      pg_endpoint: <prd-lakebase-endpoint>
      pg_host: <prd-lakebase-host>
      jobs_client_id: <jobs-prd-application-id>
      agent_client_id: <prd-agent-app-client-id>
      agent_url: <prd-agent-app-url>
    resources:
      apps:
        agent:
          permissions:                  # only the jobs runtime principal may call the agent (batch, eval)
            - level: CAN_USE
              service_principal_name: ${var.jobs_client_id}
src/evals/gate.py · compiles
"""Step 16 and 18. The release gate: compare an evaluation against the contract and the last release.

Used by CI (.gitlab-ci.yml, job eval_gate) and by the nightly job. Pure decision logic, tested here.
A release passes only if every contract threshold holds, there are zero unsafe errors, and no metric
is worse than the baseline by more than the run-to-run spread measured for that metric.

  python gate.py --current current.json --baseline baseline.json [--contract ../../contract.yml]
"""
from __future__ import annotations

import argparse
import json
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

HIGHER_IS_BETTER = {"action_accuracy", "grounded_figures", "policy_cited", "first_try_admissible"}
LOWER_IS_BETTER = {"p95_latency_s", "cost_per_exception_usd"}


def check(current: dict, baseline: dict | None, metrics: dict, spread: dict | None = None,
          min_n: int = 200) -> list:
    """Reasons to block the release. Empty list means ship."""
    out = []
    if current.get("n", 0) < min_n:
        out.append(f"only {current.get('n', 0)} evaluated cases; the gate needs {min_n} to mean anything")
    if current.get("unsafe_errors", 0) > 0:
        out.append(f"{current['unsafe_errors']} unsafe errors (proposed payment where a person did not)")
    floors = {"action_accuracy": metrics["action_accuracy_min"], "grounded_figures": metrics["grounded_figures_min"],
              "policy_cited": metrics["policy_cited_min"]}
    ceilings = {"p95_latency_s": metrics["p95_latency_s_max"], "cost_per_exception_usd": metrics["cost_per_exception_usd_max"]}
    for k, v in floors.items():
        if current.get(k, 0) < v:
            out.append(f"{k} {current.get(k, 0)} below contract minimum {v}")
    for k, v in ceilings.items():
        if current.get(k, float("inf")) > v:
            out.append(f"{k} {current.get(k)} above contract maximum {v}")
    if baseline:
        spread = spread or {}
        for k in HIGHER_IS_BETTER:
            if k in baseline and k in current and current[k] < baseline[k] - spread.get(k, 0.0):
                out.append(f"{k} regressed {baseline[k]} -> {current[k]} (allowed spread {spread.get(k, 0.0)})")
        for k in LOWER_IS_BETTER:
            if k in baseline and k in current and current[k] > baseline[k] * 1.2 + spread.get(k, 0.0):
                out.append(f"{k} grew more than 20%: {baseline[k]} -> {current[k]}")
    return out


def worst_of(runs: list) -> dict:
    """One summary from repeated runs: the worst value of each metric (min for higher-is-better, max otherwise)."""
    runs = runs if isinstance(runs, list) else [runs]
    keys = [k for k in runs[0] if all(isinstance(r.get(k), (int, float)) for r in runs)]
    out = {k: (min if k in HIGHER_IS_BETTER or k == "n" else max)(r[k] for r in runs) for k in keys}
    return out


def spread_of(runs: list) -> dict:
    """Max minus min per metric across repeated runs of the same build: the noise floor."""
    keys = set().union(*[r.keys() for r in runs]) if runs else set()
    return {k: round(max(r[k] for r in runs) - min(r[k] for r in runs), 4)
            for k in keys if all(isinstance(r.get(k), (int, float)) for r in runs)}


if __name__ == "__main__":  # pragma: no cover
    from common.contract import load

    ap = argparse.ArgumentParser()
    ap.add_argument("--current", required=True, help="JSON: one summary, or a list of repeated-run summaries")
    ap.add_argument("--baseline")
    ap.add_argument("--contract")
    ap.add_argument("--result", help="write {sha, passed, reasons, summary} here for the release pipeline")
    a = ap.parse_args()
    cur = json.load(open(a.current))
    runs = cur if isinstance(cur, list) else [cur]
    base = worst_of(json.load(open(a.baseline))) if a.baseline and os.path.exists(a.baseline) else None
    reasons = check(worst_of(runs), base, load(a.contract)["success_metrics"], spread_of(runs))
    for r in reasons:
        print("GATE:", r)
    print("gate passed" if not reasons else f"gate FAILED ({len(reasons)} reasons)")
    if a.result:
        json.dump({"sha": os.environ.get("CI_COMMIT_SHA", ""), "passed": not reasons, "reasons": reasons,
                   "summary": worst_of(runs)}, open(a.result, "w"), indent=1)
    sys.exit(1 if reasons else 0)
src/evals/verify_gate.py · compiles
"""Step 18. The release pipeline's first job: prove this exact commit passed the gate on main.

  python verify_gate.py gate_result.json $CI_COMMIT_SHA

The release branch is protected and only receives commits from main, but "it was on main" is not "it
passed". gate.py on main writes {sha, passed, reasons}; this check refuses to release anything else,
including a newer commit of main that has not been gated yet. check() is pure and tested.
"""
from __future__ import annotations

import json
import sys


def check(result: dict, sha: str) -> list:
    out = []
    if not sha:
        out.append("no commit sha given")
    if result.get("sha") != sha:
        out.append(f"the gate result is for {str(result.get('sha'))[:12]}, not {sha[:12]}: gate this commit on main first")
    if result.get("passed") is not True:
        out.append("the gate did not pass: " + "; ".join(result.get("reasons") or ["no reasons recorded"]))
    return out


if __name__ == "__main__":  # pragma: no cover
    problems = check(json.load(open(sys.argv[1])), sys.argv[2] if len(sys.argv) > 2 else "")
    for p in problems:
        print("RELEASE BLOCKED:", p)
    print("gate verified for this commit" if not problems else "release refused")
    sys.exit(1 if problems else 0)
src/common/render_env.py · compiles
"""Write per-environment values into an app's app.yaml before deploy (CI runs it; the repo keeps dev values).

  python render_env.py app/app.yaml AGENT_CATALOG=fin_stg PGHOST=$LAKEBASE_HOST DATABRICKS_WAREHOUSE_ID=@sql_warehouse

KEY=value sets a literal; KEY=@name sets valueFrom: name (an app resource). Existing entries with the same
name are replaced, others are kept. merge_env() is pure and tested. The rewritten file loses comments,
which is fine: it is a build output in the CI workspace, never committed.
"""
from __future__ import annotations

import sys


def merge_env(doc: dict, pairs: list) -> dict:
    env = list(doc.get("env") or [])
    for pair in pairs:
        if "=" not in pair:
            raise ValueError(f"expected KEY=value or KEY=@resource, got {pair!r}")
        key, val = pair.split("=", 1)
        if not val or val.startswith("<"):
            raise ValueError(f"{key} has no value (placeholder {val!r}); set the CI variable for this environment")
        entry = {"name": key, "valueFrom": val[1:]} if val.startswith("@") else {"name": key, "value": val}
        env = [e for e in env if e.get("name") != key] + [entry]
    return {**doc, "env": env}


if __name__ == "__main__":  # pragma: no cover
    import yaml
    path, pairs = sys.argv[1], sys.argv[2:]
    doc = yaml.safe_load(open(path)) or {}
    out = merge_env(doc, pairs)
    yaml.safe_dump(out, open(path, "w"), sort_keys=False)
    print(f"{path}: " + ", ".join(e["name"] for e in out["env"]))
src/common/apply_sql.py · compiles
"""Run a SQL file against one environment: substitute the catalog, split into statements, execute each.

The SQL files are written for fin_dev so they run as they are in the SQL editor. CI and the per-environment
setup run them through this script, which replaces the catalog name, so stg and prd never read dev tables
by accident.

  python apply_sql.py --file src/tools/functions.sql --catalog fin_stg --warehouse-id <id>

split_statements() and for_catalog() are pure and tested.
"""
from __future__ import annotations

import argparse
import re

DEV_CATALOG = "fin_dev"


def for_catalog(sql: str, catalog: str) -> str:
    if not re.fullmatch(r"[a-z][a-z0-9_]*", catalog):
        raise ValueError(f"not a catalog name: {catalog!r}")
    return re.sub(rf"\b{DEV_CATALOG}\b", catalog, sql)


def split_statements(sql: str) -> list:
    """Split on semicolons outside quotes, backticks, $$ blocks and -- comments. Drops comment-only pieces."""
    out, buf, i, n = [], [], 0, len(sql)
    quote = None                      # "'", '"', '`' or '$$'
    while i < n:
        c = sql[i]
        if quote:
            if quote == "$$" and sql.startswith("$$", i):
                buf.append("$$"); i += 2; quote = None; continue
            buf.append(c)
            if quote != "$$" and c == quote:
                quote = None
            i += 1
            continue
        if sql.startswith("--", i):
            j = sql.find("\n", i)
            j = n if j < 0 else j
            buf.append(sql[i:j]); i = j; continue
        if sql.startswith("$$", i):
            quote = "$$"; buf.append("$$"); i += 2; continue
        if c in ("'", '"', "`"):
            quote = c
        if c == ";":
            out.append("".join(buf)); buf = []; i += 1; continue
        buf.append(c); i += 1
    out.append("".join(buf))
    keep = []
    for s in out:
        body = "\n".join(l for l in s.splitlines() if not l.strip().startswith("--")).strip()
        if body:
            keep.append(s.strip())
    return keep


def main() -> None:  # pragma: no cover
    from databricks.sdk import WorkspaceClient

    ap = argparse.ArgumentParser()
    ap.add_argument("--file", required=True)
    ap.add_argument("--catalog", required=True)
    ap.add_argument("--warehouse-id", required=True)
    a = ap.parse_args()
    w = WorkspaceClient()
    stmts = split_statements(for_catalog(open(a.file).read(), a.catalog))
    for k, st in enumerate(stmts, 1):
        r = w.statement_execution.execute_statement(statement=st, warehouse_id=a.warehouse_id, wait_timeout="50s")
        state = r.status.state.value if r.status and r.status.state else "?"
        print(f"{k:3}/{len(stmts)} {state:10} {st.splitlines()[0][:90]}")
        if state not in ("SUCCEEDED",):
            msg = r.status.error.message if r.status and r.status.error else ""
            raise SystemExit(f"statement {k} failed: {msg}")


if __name__ == "__main__":  # pragma: no cover
    main()
setup/04_dev_deploy.sh · bash -n passes
#!/usr/bin/env bash
# Step 18. Deploy your own dev copy, from your own login, the way CI deploys stg and prd.
# CI copies src/ and contract.yml into both apps and writes per-environment values into their app.yaml
# files; a plain `bundle deploy -t dev` without that ships apps that cannot import their code.
# This script does the same steps, with your dev values, so dev and CI cannot drift.
#
#   databricks auth login --host https://<dev-workspace-host>
#   export LAKEBASE_ENDPOINT=projects/spend-exceptions/branches/dev/endpoints/primary LAKEBASE_HOST=<host>
#   export GENIE_SPACE_ID=<dev-genie-space-id>
#   ./setup/04_dev_deploy.sh
set -euo pipefail
cd "$(dirname "$0")/.."
: "${LAKEBASE_ENDPOINT:?}" "${LAKEBASE_HOST:?}" "${GENIE_SPACE_ID:?}"
CATALOG="${CATALOG:-fin_dev}"
WAREHOUSE_ID="${WAREHOUSE_ID:?set WAREHOUSE_ID to your dev warehouse}"
[ -f agent/app.yaml ] || { echo "agent/ is not vendored yet: run setup/03_vendor_agent_template.sh"; exit 1; }

python3 src/common/contract.py
rm -rf agent/src && cp -r src agent/src && cp contract.yml agent/ && cp contract.yml app/
# render_env.py edits app.yaml in place; keep the committed files clean for git
cp app/app.yaml app/app.yaml.orig && cp agent/app.yaml agent/app.yaml.orig
trap 'mv app/app.yaml.orig app/app.yaml; mv agent/app.yaml.orig agent/app.yaml' EXIT
python3 src/common/render_env.py app/app.yaml AGENT_CATALOG="$CATALOG" ENDPOINT_NAME="$LAKEBASE_ENDPOINT" \
  PGHOST="$LAKEBASE_HOST" DATABRICKS_WAREHOUSE_ID=@sql_warehouse
python3 src/common/render_env.py agent/app.yaml AGENT_CATALOG="$CATALOG" GENIE_SPACE_ID="$GENIE_SPACE_ID" \
  ENDPOINT_NAME="$LAKEBASE_ENDPOINT" PGHOST="$LAKEBASE_HOST" DATABRICKS_WAREHOUSE_ID=@sql_warehouse

databricks bundle validate -t dev
databricks bundle deploy -t dev
databricks bundle run spend_pipeline -t dev
python3 src/common/apply_sql.py --file src/tools/functions.sql   --catalog "$CATALOG" --warehouse-id "$WAREHOUSE_ID"
python3 src/common/apply_sql.py --file semantics/metric_view.sql --catalog "$CATALOG" --warehouse-id "$WAREHOUSE_ID"
databricks bundle run agent -t dev
databricks bundle run reviewer -t dev
echo "dev deployed. Copies under agent/src, agent/contract.yml and app/contract.yml are build output; do not commit them."
requirements-ci.txt · read only
pytest
pyyaml
psycopg[binary]

How to read the result如何解读结果

  • `gate FAILED (2 reasons)` with the reasons listed is the pipeline protecting production. The job log is the evidence an auditor wants: which release, which numbers, who approved.`gate FAILED (2 reasons)` 并列出原因,说明流水线在保护生产环境。作业日志就是审计人员需要的证据:哪个版本、哪些数字、谁批准的。
  • `RELEASE BLOCKED: the gate result is for 3f2a..., not 9c1d...` means release points at a commit the gate has not passed, usually a newer main commit. Release the gated commit or wait for main's gate.`RELEASE BLOCKED: the gate result is for 3f2a..., not 9c1d...` 说明 release 指向了一个尚未通过门槛的提交,通常是 main 上更新的提交。发布已通过门槛的那个提交,或者等 main 的门槛跑完。
  • deploy_prd waiting for approval after verify_gate is green is the normal state. Approvers should open gate_result.json and current.json (job artifacts) before clicking.verify_gate 通过后 deploy_prd 等待审批,是正常状态。审批人在点击之前应该打开 gate_result.json 和 current.json(作业产出物)看一看。

Troubleshooting排障

You see现象Why原因Do this处理
deploy succeeded but the app runs old codedeploy 成功了,但 App 运行的还是旧代码bundle deploy uploads code and updates resources but does not restart the app process.bundle deploy 会上传代码并更新资源,但不会重启 App 进程。Keep the `bundle run agent` and `bundle run reviewer` lines after every deploy.在每次 deploy 之后都保留 `bundle run agent` 和 `bundle run reviewer` 这两行。
render_env fails: has no value (placeholder)render_env 失败:没有值(占位符)A per-environment CI variable is unset, so the app would have deployed with a dev value.某个按环境区分的 CI 变量未设置,于是 App 会带着 dev 的值部署。Set it for that GitLab environment. Failing the deploy is the point: prd must never read fin_dev.为那个 GitLab 环境设置它。让部署失败正是目的:prd 绝不能读取 fin_dev。
The gate passes with no baseline在没有基线的情况下门槛通过了First release: there is nothing to regress from.首次发布:没有可以与之比较的版本。Expected once. The contract thresholds still apply; deploy_prd keeps that release's current.json as baseline.json, the first baseline.这只会发生一次。契约门槛仍然有效;deploy_prd 会把这次发布的 current.json 保存为 baseline.json,即第一个基线。
First deploy: functions.sql fails, table not found首次部署:functions.sql 失败,找不到表The tools and the metric view read gold tables, which exist only after the pipeline's first update.工具和指标视图读取 gold 表,而这些表要等 pipeline 第一次更新后才存在。Keep `bundle run spend_pipeline` between deploy and apply_sql. On later deploys it is an incremental refresh.在 deploy 和 apply_sql 之间保留 `bundle run spend_pipeline`。之后的部署中它只是一次增量刷新。

How this scales如何扩展

  • More workflows: a shared GitLab CI component (include: component) for the authenticate-deploy-gate pattern; each workflow repository supplies its contract and targets.工作流增多时:为“认证-部署-门槛”模式建一个共享的 GitLab CI 组件(include: component);每个工作流仓库只需提供自己的契约和 target。
  • More regions: one prd target per region, deployed in sequence from the same pipeline, the second only after the first's monitors are green.区域增多时:每个区域一个 prd target,在同一条流水线中依次部署,第二个区域要等第一个区域的监控正常之后才部署。
Architecture review: questions you will be asked架构评审:你会被问到的问题
Why a manual production step, when continuous deployment is best practice?持续部署才是最佳实践,为什么生产还要手动?

For a workflow that proposes payments, a named approver is a control your auditors will ask for. The manual step costs a click after an automated gate; it can become automatic later for change types the contract allows, such as prompt wording below a risk threshold.对于一个会提议付款的工作流,具名的审批人是审计人员会要求的控制措施。这个手动步骤只是在自动门槛之后多点一下;之后对于契约允许的变更类型(例如低于风险阈值的提示词措辞调整),可以改成自动。

Done when完成标准A merge request runs tests only, main reaches staging and the gate, production deploys only from release after verify_gate and an approval, and a deliberately failing gate blocks it.合并请求只运行测试,main 能部署到预发并经过门槛,生产只能从 release 在 verify_gate 通过并经审批后部署,并且一个故意失败的门槛会阻止它。
Not confirmed on a vendor page未在厂商页面上确认The Python SDK's env-oidc support (used by apply_sql.py in CI) is assumed from the documented env-oidc auth type; gate.py and verify_gate.py read only local files. Downloading another job's artifacts with CI_JOB_TOKEN is a GitLab feature for the same project. Protected-environment approvals depend on your GitLab tier.Python SDK 对 env-oidc 的支持(CI 中的 apply_sql.py 会用到)是根据文档中的 env-oidc 认证类型推断的;gate.py 和 verify_gate.py 只读取本地文件。用 CI_JOB_TOKEN 下载另一个作业的产出物,是 GitLab 针对同一项目提供的功能。受保护环境的审批功能取决于你的 GitLab 版本等级。
19Orchestrate with Lakeflow Jobs用 Lakeflow Jobs 编排
Builds构建内容The orchestrator (file arrival: pipeline, batch triage, export), the weekly policy refresh, and the nightly quality job.编排 job(文件到达触发:pipeline、批量分诊、导出)、每周的政策刷新,以及每晚的质量检查 job。

Why this step, and why here为什么要做这一步,为什么在这里

The workflow runs when data arrives, not when someone remembers. The orchestrator chains the pipeline, the batch triage against the deployed agent, and the export of decisions, with one run at a time so two runs never triage the same exceptions. The batch calls the same agent endpoint the evaluation measured: one code path, so what was tested is what runs. A per-run limit bounds cost and blast radius: a bad deploy can only spend one batch.工作流在数据到达时运行,而不是在有人想起来的时候。编排 job 把 pipeline、针对已部署智能体的批量分诊、决定导出串联起来,并且一次只允许一个运行,这样两个运行永远不会分诊同一批异常。批处理调用的是评估所衡量的同一个智能体端点:只有一条代码路径,所以测试过的就是实际运行的。每次运行的数量上限限定了成本和影响范围:一次错误的部署最多只会浪费一批。

What it does它做什么

resources/jobs.yml defines spend_orchestrator (file-arrival trigger on the ERP landing folder; tasks refresh_pipeline, batch_triage, export_decisions; max_concurrent_runs 1; failure email), policy_refresh (Mondays) and quality (nightly eval and Genie benchmark). batch_triage.py selects exceptions with no live proposal, plus pending proposals whose invoice amount has since changed (made on old facts, so the agent supersedes them); a decided exception is never triaged again, which would invite a second approval of a payment, and a decided one whose amount changed is printed for a person. It sends only units in the agent principal's reviewer_scope, so an exception the agent cannot read is not escalated as not found every run for ever. It calls the agent with bounded concurrency and jittered backoff on 429, 5xx and network errors, records a failed call as one error instead of ending the batch, and fails the task above 5% errors.resources/jobs.yml 定义了 spend_orchestrator(在 ERP 落地目录上按文件到达触发;任务包括 refresh_pipeline、batch_triage、export_decisions;max_concurrent_runs 为 1;失败时发邮件)、policy_refresh(每周一)和 quality(每晚的评估和 Genie 基准测试)。batch_triage.py 选出没有在途提议的异常,以及发票金额已变化的待处理提议(它们基于旧事实做出,所以智能体会取代它们);已决定的异常绝不会再次分诊,否则可能导致同一笔付款被第二次批准,而已决定但金额变化的异常会打印出来交给人处理。它只发送智能体服务主体在 reviewer_scope 中拥有的单元,这样智能体读不到的异常不会每次运行都以“找不到”被升级、永无止境。它以有限并发调用智能体,在遇到 429、5xx 和网络错误时带抖动地退避重试,把一次失败的调用记为一个错误而不是让整批终止,错误率超过 5% 时让任务失败。

How to do it怎么做

  1. After the first deploy, set agent_url, agent_client_id (`databricks apps get agent-spend-exceptions`), pg_endpoint, pg_host and jobs_client_id (the runtime principal from step 3, not the CI principal) per target.首次部署后,为每个 target 设置 agent_url、agent_client_id(`databricks apps get agent-spend-exceptions`)、pg_endpoint、pg_host 和 jobs_client_id(第 3 步的运行时服务主体,不是 CI 服务主体)。
  2. Drop one test extract into the landing folder in dev and watch the orchestrator run end to end.在 dev 的落地目录中放一个测试抽取文件,观察编排 job 从头到尾运行一遍。
  3. Start with --concurrency 4 and --limit 100; raise both from the load test, not by feel.从 --concurrency 4 和 --limit 100 开始;根据负载测试提高这两个值,而不是凭感觉。

Scripts脚本

resources/jobs.yml · yaml parses
# Steps 10, 11, 16, 19. Jobs. File arrival starts the main flow; the rest run on a schedule.
resources:
  jobs:
    spend_orchestrator:
      name: spend-exceptions-orchestrator
      max_concurrent_runs: 1              # two overlapping runs would triage the same exceptions twice
      trigger:
        file_arrival:
          url: /Volumes/${var.catalog}/landing/erp/
      environments:
        - environment_key: default
          spec:
            environment_version: "2"
            dependencies: [databricks-sdk, aiohttp, "psycopg[binary,pool]"]
      tasks:
        - task_key: refresh_pipeline
          pipeline_task:
            pipeline_id: ${resources.pipelines.spend_pipeline.id}
        - task_key: batch_triage
          depends_on: [{task_key: refresh_pipeline}]
          environment_key: default
          spark_python_task:
            python_file: ../src/agent/batch_triage.py
            parameters: ["--catalog", "${var.catalog}", "--agent-url", "${var.agent_url}", "--limit", "500",
                         "--agent-principal", "${var.agent_client_id}",
                         "--warehouse-id", "${var.warehouse_id}", "--pg-endpoint", "${var.pg_endpoint}",
                         "--pg-host", "${var.pg_host}", "--pg-user", "${var.jobs_client_id}"]
        - task_key: export_decisions
          depends_on: [{task_key: batch_triage}]
          environment_key: default
          spark_python_task:
            python_file: ../src/review/export_decisions.py
            parameters: ["--catalog", "${var.catalog}", "--pg-endpoint", "${var.pg_endpoint}",
                         "--pg-host", "${var.pg_host}", "--pg-user", "${var.jobs_client_id}"]
      email_notifications:
        on_failure: [finance-ops-oncall@example.com]

    policy_refresh:
      name: spend-exceptions-policy-refresh
      schedule:
        quartz_cron_expression: "0 0 5 ? * MON"   # Mondays 05:00; policy changes are rare and reviewed
        timezone_id: UTC
      environments:
        - environment_key: default
          spec:
            environment_version: "2"
            dependencies: [databricks-ai-search]
      tasks:
        - task_key: build
          environment_key: default
          spark_python_task:
            python_file: ../src/knowledge/policy_index.py
            parameters: ["build", "--catalog", "${var.catalog}"]
        - task_key: sync
          depends_on: [{task_key: build}]
          environment_key: default
          spark_python_task:
            python_file: ../src/knowledge/policy_index.py
            parameters: ["sync", "--catalog", "${var.catalog}"]

    quality:
      name: spend-exceptions-quality
      schedule:
        quartz_cron_expression: "0 30 2 * * ?"    # nightly: the eval set against the deployed agent, then Genie
        timezone_id: UTC
      environments:
        - environment_key: default
          spec:
            environment_version: "2"
            dependencies: ["mlflow[databricks]", databricks-sdk, requests, pyyaml]
      tasks:
        - task_key: eval
          environment_key: default
          spark_python_task:
            python_file: ../src/evals/run_eval.py
            parameters: ["run", "--catalog", "${var.catalog}", "--agent-url", "${var.agent_url}", "--repeats", "3",
                         "--warehouse-id", "${var.warehouse_id}",
                         "--out", "/Volumes/${var.catalog}/ops/artifacts/eval_current.json"]
        - task_key: genie_benchmark
          environment_key: default
          spark_python_task:
            python_file: ../src/genie/benchmark.py
            parameters: ["--space-id", "${var.genie_space_id}", "--warehouse-id", "${var.warehouse_id}",
                         "--file", "genie_benchmarks.json", "--catalog", "${var.catalog}"]   # file resolved next to benchmark.py
src/agent/batch_triage.py · compiles
"""Step 19. The scheduled path: send every new exception to the DEPLOYED agent, with bounded concurrency.

One code path for interactive and batch use: the job calls the same agent endpoint reviewers' tools
call, so what was evaluated is what runs. The job never imports the agent in-process.

  python batch_triage.py --catalog fin_prd --agent-url https://<agent-url> --agent-principal <agent-client-id> --concurrency 8

select_new(), changed_after_decision() and backoff() are pure and tested.
"""
from __future__ import annotations

import argparse
import asyncio
import os
import random
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


def select_new(open_rows: list, live: dict, limit: int, units: set | None = None) -> list:
    """Which exceptions to send to the agent, oldest first (input order), at most `limit`.

    open_rows  (exception_id, invoice_amount, business_unit) from gold.open_exceptions, oldest first
    live       {exception_id: (invoice_amount, status)} for every proposal not superseded
    units      business units the agent's principal can read; None means no filter

    Sent: no live proposal, or a PENDING proposal whose amount no longer matches the invoice (the invoice
    was corrected, so the proposal was made on old facts; the agent supersedes it).
    Not sent: a decided proposal (approved, rejected). Re-proposing an approved payment invites a second
    approval; a changed amount after a decision is an incident for a person, listed by changed_after_decision().
    Not sent: units the agent cannot read. Its get_exception call would return found=false and escalate,
    every run, for ever. Step 20 query 6 alerts on those units instead.
    The limit is a cost and blast-radius control: a bad deploy can only spend one batch."""
    out = []
    for eid, amount, unit in open_rows:
        if units is not None and unit not in units:
            continue
        if eid in live:
            amt, status = live[eid]
            if status not in ("pending", "needs_second") or round(float(amt), 2) == round(float(amount), 2):
                continue
        out.append(eid)
    return out[:limit]


def changed_after_decision(open_rows: list, live: dict) -> list:
    """Decided exceptions whose invoice amount changed afterwards. A person must look; the job prints them."""
    return [eid for eid, amount, _ in open_rows
            if eid in live and live[eid][1] not in ("pending", "needs_second")
            and round(float(live[eid][0]), 2) != round(float(amount), 2)]


def backoff(attempt: int, base: float = 1.0, cap: float = 30.0, jitter: float = 0.25) -> float:
    """Exponential backoff with jitter for 429 and 5xx. Jitter stops eight workers retrying in lockstep."""
    d = min(cap, base * (2 ** attempt))
    return round(d * (1 - jitter + 2 * jitter * random.random()), 3)


def summarize(results: list) -> dict:
    out = {"total": len(results)}
    for r in results:
        out[r.get("status", "error")] = out.get(r.get("status", "error"), 0) + 1
    return out


async def _one(session, url: str, headers: dict, exception_id: str, sem: asyncio.Semaphore) -> dict:  # pragma: no cover
    import aiohttp
    async with sem:
        for attempt in range(5):
            try:
                async with session.post(f"{url.rstrip('/')}/responses", headers=headers,
                                        timeout=aiohttp.ClientTimeout(total=180),
                                        json={"input": [{"role": "user", "content": f"Triage exception {exception_id}."}]}) as r:
                    if r.status in (429, 500, 502, 503, 504):
                        await asyncio.sleep(backoff(attempt))
                        continue
                    if r.status != 200:
                        return {"exception_id": exception_id, "status": "error", "http": r.status}
                    body = await r.json()
                    return {"exception_id": exception_id, **((body.get("custom_outputs") or {}) or {"status": "queued"})}
            except (aiohttp.ClientError, asyncio.TimeoutError) as e:      # one bad call must not end the batch
                if attempt == 4:
                    return {"exception_id": exception_id, "status": "error", "http": type(e).__name__}
                await asyncio.sleep(backoff(attempt))
        return {"exception_id": exception_id, "status": "error", "http": "retries exhausted"}


async def run(catalog: str, agent_url: str, concurrency: int, limit: int, agent_principal: str | None) -> dict:  # pragma: no cover
    import aiohttp
    from databricks.sdk import WorkspaceClient
    from databricks.sdk.service.sql import StatementParameterListItem

    from common.pg import pool

    w = WorkspaceClient()
    wh = os.environ["DATABRICKS_WAREHOUSE_ID"]
    res = w.statement_execution.execute_statement(
        statement=f"SELECT exception_id, invoice_amount, business_unit FROM {catalog}.gold.open_exceptions ORDER BY detected_at",
        warehouse_id=wh, wait_timeout="50s")
    open_rows = [tuple(r) for r in (res.result.data_array or [])] if res.result else []
    units = None
    if agent_principal:                                   # the units the AGENT can read, not the job
        s = w.statement_execution.execute_statement(
            statement=f"SELECT business_unit FROM {catalog}.gold.reviewer_scope WHERE reviewer = :p",
            parameters=[StatementParameterListItem(name="p", value=agent_principal)], warehouse_id=wh, wait_timeout="50s")
        units = {r[0] for r in (s.result.data_array or [])} if s.result else set()
    with pool().connection() as conn:
        live = {r[0]: (r[1], r[2]) for r in conn.execute(
            "SELECT exception_id, invoice_amount, status FROM proposals WHERE status <> 'superseded'")}
    todo = select_new(open_rows, live, limit, units)
    for eid in changed_after_decision(open_rows, live):
        print("CHANGED AFTER DECISION, needs a person:", eid)
    headers = w.config.authenticate()                     # job service principal, OAuth (M2M)
    sem = asyncio.Semaphore(concurrency)
    t0 = time.time()
    async with aiohttp.ClientSession() as s:
        results = await asyncio.gather(*[_one(s, agent_url, headers, e, sem) for e in todo], return_exceptions=True)
    results = [r if isinstance(r, dict) else {"status": "error", "http": type(r).__name__} for r in results]
    out = summarize(results)
    out["seconds"] = round(time.time() - t0, 1)
    print(out)
    return out


if __name__ == "__main__":  # pragma: no cover
    ap = argparse.ArgumentParser()
    ap.add_argument("--catalog", required=True)
    ap.add_argument("--agent-url", required=True)
    ap.add_argument("--concurrency", type=int, default=8)
    ap.add_argument("--limit", type=int, default=500)
    ap.add_argument("--agent-principal", help="the agent app's client id; only its units are sent")
    from common.pg import add_args, apply_args
    add_args(ap)
    a = ap.parse_args()
    apply_args(a)
    s = asyncio.run(run(a.catalog, a.agent_url, a.concurrency, a.limit, a.agent_principal))
    raise SystemExit(1 if s.get("error", 0) > max(5, s["total"] // 20) else 0)   # >5% errors fails the task

How to read the result如何解读结果

  • `{'total': 100, 'queued': 91, 'escalated': 7, 'error': 2, 'seconds': 412.3}`: 91% handled, 7% sent to people with reasons, 2% errors (retried and still failed). 412 seconds for 100 at concurrency 4 means about 16 seconds per triage.`{'total': 100, 'queued': 91, 'escalated': 7, 'error': 2, 'seconds': 412.3}`:91% 已处理,7% 附带原因交给了人,2% 出错(重试后仍失败)。并发 4 时处理 100 个用了 412 秒,意味着每次分诊约 16 秒。
  • A run that skips because another is in progress is max_concurrent_runs doing its job; if it happens every time, the batch takes longer than the arrival interval and needs more concurrency.某次运行因为另一次正在进行而被跳过,说明 max_concurrent_runs 在尽职;如果每次都这样,说明一批处理的耗时超过了数据到达的间隔,需要提高并发。

Troubleshooting排障

You see现象Why原因Do this处理
batch_triage: 401 from the agentbatch_triage:智能体返回 401The job's principal has no CAN_USE on the agent app, or the token expired mid-run.job 的服务主体对智能体 App 没有 CAN_USE 权限,或者令牌在运行中途过期了。The stg and prd targets grant CAN_USE on the agent to jobs_client_id; check it names the runtime principal. In dev the caller is you, the app's owner. For runs longer than about an hour, refresh headers per request.stg 和 prd 的 target 会向 jobs_client_id 授予智能体的 CAN_USE;检查它指向的是运行时服务主体。在 dev 中调用者是你,也就是 App 的所有者。对于超过约一小时的运行,每个请求都刷新一次请求头。
The same exceptions escalate as not found every run同一批异常每次运行都以“找不到”被升级Without --agent-principal the batch sends units the agent's row filter hides.没有 --agent-principal 时,批处理会发送被智能体行过滤隐藏的单元。Set agent_client_id so the job passes it, and add the missing reviewer_scope rows; step 20 query 6 lists them.设置 agent_client_id 让 job 传入它,并补上缺失的 reviewer_scope 记录;第 20 步的查询 6 会列出它们。
The job fails on errors above 5%错误率超过 5% 时 job 失败The agent or a dependency is unhealthy.智能体或某个依赖不健康。That is the intent: a failing batch pages someone instead of filling the queue with escalations. Check the agent app logs and the gateway first.这正是设计意图:失败的批处理会通知到人,而不是让队列里塞满升级处理。先检查智能体 App 的日志和网关。

How this scales如何扩展

  • Volume grows: raise concurrency to the knee from step 21, then shard by business unit (one task per unit in a for-each task) so one slow unit does not hold the rest.数据量增长时:把并发提高到第 21 步测得的拐点,然后按业务单元分片(在 for-each 任务中每个单元一个任务),这样一个慢单元不会拖住其他单元。
  • Near-real-time needs: replace file arrival with a continuous pipeline and a queue-driven triage; the agent and the controls do not change.需要近实时处理时:把文件到达触发换成持续运行的 pipeline 和由队列驱动的分诊;智能体和控制措施都不需要改。
Architecture review: questions you will be asked架构评审:你会被问到的问题
Why not run the agent inside the job, in-process, to save the HTTP hop?为什么不在 job 里直接以进程内方式运行智能体,省掉一次 HTTP 调用?

Then the batch and the evaluated app could differ in dependencies, prompts and identity. The hop costs milliseconds against a 16-second triage; one code path is worth far more.那样的话,批处理和被评估的 App 可能在依赖、提示词和身份上出现差异。相对于一次 16 秒的分诊,这次调用只多几毫秒;而只有一条代码路径的价值要大得多。

Done when完成标准A file landing in dev produces queued proposals and exported decisions with no human starting anything.在 dev 中落地一个文件,无需任何人启动,就能产生排队中的提议和导出的决定。
Not confirmed on a vendor page未在厂商页面上确认The job trigger.file_arrival block shape is from the Jobs API as recalled; check it in `bundle validate`.job 的 trigger.file_arrival 块结构来自对 Jobs API 的记忆;请在 `bundle validate` 中核对。
20Observability: cost, quality, backlog, data quality可观测性:成本、质量、积压、数据质量
Builds构建内容Six queries over system tables, decisions, routing and the pipeline event log, on one dashboard, with alerts.基于系统表、决定记录、路由和 pipeline 事件日志的六条查询,放在一个仪表盘上,并配置告警。

Why this step, and why here为什么要做这一步,为什么在这里

The owner of this workflow needs five numbers every morning: what it cost, what it cost per exception, how often people agreed with it, how old the oldest undecided exception is, and how much bad data the pipeline caught. A sixth check guards the routing: any business unit with open exceptions but no human reviewer, or out of the agent's scope, is work that reaches nobody. Every resource carries the workload tag from the bundle, so cost is attributable to this workflow and not lost in a shared workspace bill.这个工作流的负责人每天早上需要五个数字:花了多少钱、每个异常花多少钱、人们同意它的频率、最老的待决异常有多久,以及 pipeline 拦下了多少坏数据。第六项检查守住路由:任何有待处理异常、却没有人工审核人员或不在智能体范围内的业务单元,都是无人接手的工作。每个资源都带有 bundle 中的 workload 标签,所以成本能归属到这个工作流,而不会淹没在共享工作区的账单里。

What it does它做什么

observability.sql: daily DBUs by product for workload=spend-exceptions; DBUs per exception triaged; weekly approval rate and rejected payment proposals; backlog age by business unit; expectation results from the pipeline event log; units that reach nobody (query 6, alert on any row).observability.sql:workload=spend-exceptions 每天按产品统计的 DBU;每次异常分诊的 DBU;每周批准率和被拒绝的付款提议;按业务单元统计的积压时长;pipeline 事件日志中的期望规则结果;无人负责的单元(查询 6,返回任何一行就告警)。

How to do it怎么做

  1. Run each query once in prd and fix names (catalog, any product names your account reports differently).在 prd 中把每条查询运行一次,并修正名称(catalog,以及你的账号中名称不同的产品)。
  2. Build one AI/BI dashboard from the five queries; share it with the workflow owner.用这五条查询建一个 AI/BI 仪表盘;分享给工作流负责人。
  3. Alerts: backlog oldest_days above the SLO, rejected_payments above zero in a week, dbus_per_exception up 30% week on week.告警:积压 oldest_days 超过 SLO;一周内 rejected_payments 大于零;dbus_per_exception 环比上升 30%。
  4. Set a budget policy and a budget alert for the workload tag in the account console.在账号控制台中为该 workload 标签设置预算策略和预算告警。

Scripts脚本

src/ops/observability.sql · sqlglot databricks: 6/6 statements parsed
-- Step 20. Observability: the five numbers the owner of this workflow reads every morning.
-- Every resource in the bundle carries the tag workload = spend-exceptions (databricks.yml presets),
-- so cost is attributable to this workflow and not lost in a shared workspace bill.

-- 1. Cost per day by product, for this workload only.
SELECT usage_date, billing_origin_product, round(sum(usage_quantity), 2) AS dbus
FROM system.billing.usage
WHERE custom_tags['workload'] = 'spend-exceptions'
  AND usage_date >= current_date() - INTERVAL 30 DAYS
GROUP BY ALL ORDER BY usage_date DESC, dbus DESC;

-- 2. Unit economics: DBUs per exception triaged. A rising line with flat volume is a prompt, a model
--    or a loop problem; read the traces before raising the budget. (Convert DBUs to currency with
--    system.billing.list_prices for your SKU.)
WITH spend AS (
  SELECT usage_date AS d, sum(usage_quantity) AS dbus FROM system.billing.usage
  WHERE custom_tags['workload'] = 'spend-exceptions' GROUP BY 1),
work AS (
  SELECT date(decided_at) AS d, count(DISTINCT exception_id) AS triaged FROM fin_prd.ops.decisions_history GROUP BY 1)
SELECT w.d, w.triaged, round(s.dbus, 2) AS dbus, round(s.dbus / nullif(w.triaged, 0), 4) AS dbus_per_exception
FROM work w LEFT JOIN spend s USING (d) ORDER BY w.d DESC LIMIT 30;

-- 3. Quality as people see it: approval rate and the actions reviewers corrected, by week.
SELECT date_trunc('WEEK', decided_at) AS week,
       round(avg(CASE WHEN verdict IN ('approve', 'second_approve') THEN 1 ELSE 0 END), 3) AS approval_rate,
       count_if(verdict = 'reject') AS rejected,
       count_if(verdict = 'reject' AND proposed_action = 'approve_payment') AS rejected_payments
FROM fin_prd.ops.decisions_history GROUP BY 1 ORDER BY 1 DESC;

-- 4. Backlog: how old is the oldest exception with no decision? The SLO is contract.yml service_levels.backlog_max_days.
SELECT business_unit, count(*) AS open, max(datediff(current_date(), detected_at)) AS oldest_days
FROM fin_prd.gold.open_exceptions e
WHERE NOT EXISTS (SELECT 1 FROM fin_prd.ops.decisions_history d WHERE d.exception_id = e.exception_id)
GROUP BY business_unit ORDER BY oldest_days DESC;

-- 5. Data quality: rows the pipeline expectations dropped or flagged in the last day, from the event log.
--    event_log() takes the pipeline's table; any of its tables works.
SELECT timestamp, details:flow_progress.data_quality.expectations AS expectations
FROM event_log(TABLE(fin_prd.silver.invoices))
WHERE event_type = 'flow_progress' AND details:flow_progress.data_quality IS NOT NULL
  AND timestamp >= current_timestamp() - INTERVAL 1 DAY
ORDER BY timestamp DESC;

-- 6. Routing: business units with open exceptions but no human reviewer, or not in the agent's scope.
--    Run as an auditor (the row filter shows auditors every unit). Any row here is work that reaches nobody;
--    alert on count > 0. Replace <agent-app-client-id>.
SELECT e.business_unit, count(*) AS open,
       NOT EXISTS (SELECT 1 FROM fin_prd.gold.reviewer_scope s
                   WHERE s.business_unit = e.business_unit AND s.reviewer <> '<agent-app-client-id>') AS no_reviewer,
       NOT EXISTS (SELECT 1 FROM fin_prd.gold.reviewer_scope s
                   WHERE s.business_unit = e.business_unit AND s.reviewer = '<agent-app-client-id>')  AS agent_cannot_see
FROM fin_prd.gold.open_exceptions e
GROUP BY e.business_unit
HAVING no_reviewer OR agent_cannot_see;

How to read the result如何解读结果

  • rejected_payments above zero means a person caught the agent proposing a payment they would not make. Each one is a candidate unsafe-error case for the next eval set.rejected_payments 大于零,说明有人拦下了智能体提议的一笔他们不会付的款。每一条都是下一个评估集中不安全错误用例的候选。
  • DBUs per exception is the unit economics. Compare it with the cost of a person's time per exception from step 1; that ratio is the business case, measured, not projected.每个异常的 DBU 就是单位经济性。把它与第 1 步中每个异常所需的人工时间成本对比;这个比值就是业务论证,而且是实测的,不是预测的。

Troubleshooting排障

You see现象Why原因Do this处理
Cost query returns nothing成本查询没有返回结果Tags were not applied (presets missing) or system tables are not enabled.标签没有应用上(缺少 presets),或者系统表没有启用。Check one job's tags in the UI; ask an account admin to enable system.billing and grant SELECT.在界面中检查某个 job 的标签;请账号管理员启用 system.billing 并授予 SELECT。
event_log query failsevent_log 查询失败The function needs the pipeline's table or id and owner-level access.该函数需要 pipeline 的表或 id,以及所有者级别的访问权限。Run it as the pipeline owner, or publish the event log to a table in the pipeline settings.以 pipeline 所有者身份运行,或者在 pipeline 设置中把事件日志发布到一张表。

How this scales如何扩展

  • At enterprise scale every workflow publishes the same five numbers under its own tag. A portfolio dashboard is then a GROUP BY workload, which is how a platform team shows value across twenty agents.在企业规模下,每个工作流都在自己的标签下发布同样的五个数字。这样一来,组合层面的仪表盘就只是一个按 workload 的 GROUP BY,平台团队正是这样展示二十个智能体的整体价值的。
Architecture review: questions you will be asked架构评审:你会被问到的问题
Approval rate is a vanity metric, isn't it?批准率不就是个虚荣指标吗?

Alone, yes. Paired with rejected payment proposals (which must be zero) and a monthly second-reviewer sample (do people agree with each other?), it becomes a measured accuracy with a person behind every label.单独看,是的。但配上被拒绝的付款提议(必须为零)和每月一次的第二审核人抽样(人与人之间是否一致?),它就成了一个以人为每个标签背书的实测准确率。

Done when完成标准One dashboard shows the five numbers for production, with three alerts and a budget alert.一个仪表盘展示了生产环境的五个数字,并配置了三个告警和一个预算告警。
Not confirmed on a vendor page未在厂商页面上确认custom_tags on system.billing.usage and the event_log() table-valued function are standard system features; the exact JSON path of expectation metrics in the event log was not on the expectations page read.system.billing.usage 上的 custom_tags 和 event_log() 表值函数都是标准系统功能;事件日志中期望规则指标的确切 JSON 路径不在本指南阅读的期望规则页面上。

8 Scale and operate扩展与运维

Scaling an agent workflow is finding which limit you hit first and raising that one: model throughput, app concurrency, reviewer hours, cost per exception, or the evidence needed for more autonomy. Operating it is knowing how to roll back each layer independently in minutes.扩展一个智能体工作流,就是找出你最先碰到的那个限制,然后提升它:模型吞吐量、App 并发、审核人员工时、每个异常的成本,或者获得更高自主权所需的证据。运维它,就是知道如何在几分钟内独立回滚每一层。

21Load test, find the knee, then scale the limit you hit做负载测试,找到拐点,再扩展你碰到的那个限制
Builds构建内容load_test.py against staging with dry-run requests; a table of limits and levers per layer.以 dry-run 请求针对预发环境运行的 load_test.py;一张按层列出限制与杠杆的表。

Why this step, and why here为什么要做这一步,为什么在这里

"Will it scale" has no answer until you know where it breaks. The load test steps concurrency up and records p50 and p95 latency, error rate and throughput at each step. The first step that breaks the contract's p95 or exceeds 1% errors is the knee. Production concurrency stays below it, and the levers in the table raise it, one layer at a time, with a measurement after each.在知道它会在哪里崩溃之前,“它能不能扩展”这个问题没有答案。负载测试逐步提高并发,记录每一步的 p50 和 p95 延迟、错误率和吞吐量。第一个突破契约 p95 或错误率超过 1% 的步骤就是拐点。生产并发保持在拐点之下,而表中的杠杆用来一层一层地提高拐点,每调一次就测量一次。

What it does它做什么

Runs four dry-run requests per worker at each concurrency level, prints a stats line per level, and names the knee. Pure helpers (percentile, step_stats, knee) are tested here.在每个并发级别上,每个工作线程发送四个 dry-run 请求,每个级别打印一行统计,并指出拐点所在。纯函数辅助工具(percentile、step_stats、knee)在这里经过测试。

How to do it怎么做

  1. Export 200 exception ids from staging into ids.txt.从预发环境导出 200 个异常 id 到 ids.txt。
  2. `python load_test.py --agent-url <staging agent> --ids ids.txt --levels 1,2,4,8,16,32`.执行 `python load_test.py --agent-url <staging agent> --ids ids.txt --levels 1,2,4,8,16,32`。
  3. Read the gateway usage and app metrics for the same window to see which layer saturated.查看同一时间窗口内的网关用量和 App 指标,确定是哪一层饱和了。
  4. Set batch concurrency and gateway limits below the knee; repeat after any model, prompt or compute change.把批处理并发和网关限额设在拐点之下;任何模型、提示词或计算资源变更之后都要重新测一遍。

Scripts脚本

src/scale/load_test.py · compiles
"""Step 21. Find the knee: the concurrency at which latency or errors stop being acceptable.

Run against STAGING with dry_run requests. Steps concurrency up (1, 2, 4, 8, 16, 32) and prints
p50/p95 latency, error rate and throughput per step. The first step whose p95 exceeds the contract or
whose error rate exceeds 1% is the knee; production concurrency stays below it, and the scaling levers
in the page raise it.

  python load_test.py --agent-url https://<staging-agent> --ids ids.txt --levels 1,2,4,8,16
"""
from __future__ import annotations

import argparse
import asyncio
import time


def percentile(values: list, p: float) -> float:
    if not values:
        return 0.0
    v = sorted(values)
    k = (len(v) - 1) * p
    lo, hi = int(k), min(int(k) + 1, len(v) - 1)
    return round(v[lo] + (v[hi] - v[lo]) * (k - lo), 3)


def step_stats(latencies: list, errors: int, wall_s: float) -> dict:
    n = len(latencies) + errors
    return {"requests": n, "p50_s": percentile(latencies, 0.5), "p95_s": percentile(latencies, 0.95),
            "error_rate": round(errors / n, 4) if n else 0.0, "rps": round(n / wall_s, 3) if wall_s else 0.0}


def knee(steps: list, p95_max: float, error_max: float = 0.01):
    """First concurrency level that breaks the contract, or None if none did."""
    for s in steps:
        if s["p95_s"] > p95_max or s["error_rate"] > error_max:
            return s["concurrency"]
    return None


async def _level(url: str, headers: dict, ids: list, c: int) -> dict:  # pragma: no cover
    import aiohttp
    sem, lat, err = asyncio.Semaphore(c), [], 0

    async def one(session, eid):
        nonlocal err
        async with sem:
            t0 = time.perf_counter()
            try:
                async with session.post(f"{url.rstrip('/')}/responses", headers=headers, timeout=180,
                                        json={"input": [{"role": "user", "content": f"Triage exception {eid}."}],
                                              "custom_inputs": {"dry_run": True}}) as r:
                    await r.read()
                    if r.status == 200:
                        lat.append(time.perf_counter() - t0)
                    else:
                        err += 1
            except Exception:                                  # noqa: BLE001
                err += 1

    t0 = time.perf_counter()
    async with aiohttp.ClientSession() as s:
        await asyncio.gather(*[one(s, e) for e in ids[: c * 4]])     # four requests per worker per level
    return {"concurrency": c, **step_stats(lat, err, time.perf_counter() - t0)}


def main() -> None:  # pragma: no cover
    from databricks.sdk import WorkspaceClient

    ap = argparse.ArgumentParser()
    ap.add_argument("--agent-url", required=True)
    ap.add_argument("--ids", required=True)
    ap.add_argument("--levels", default="1,2,4,8,16")
    ap.add_argument("--p95-max", type=float, default=30.0)
    a = ap.parse_args()
    ids = [l.strip() for l in open(a.ids) if l.strip()]
    headers = WorkspaceClient().config.authenticate()
    steps = []
    for c in [int(x) for x in a.levels.split(",")]:
        steps.append(asyncio.run(_level(a.agent_url, headers, ids, c)))
        print(steps[-1])
    print("knee at concurrency:", knee(steps, a.p95_max))


if __name__ == "__main__":  # pragma: no cover
    main()
text
layer            first limit you hit                        lever
model            429s or p95 growth at the gateway          provisioned throughput; a cheaper model for one class (eval first)
agent app        p95 grows while model latency is flat      larger app compute; fewer tool rounds (prompt); cache vendor_history per run
tools / Genie    Genie seconds dominate the trace           UC function for questions asked every time; warehouse sizing
AI Search        query latency at high QPS                  standard endpoint QPS; storage-optimized for very large corpora
pipeline         update time beyond the arrival interval    scheduled batches instead of per-file; liquid clustering; serverless
AI Functions     cost per document                          streaming tables only; backfills as budgeted runs
Lakebase         connections or lock waits                  autoscaling; short transactions; pool size per app
reviewers        backlog age grows with healthy compute     raise autonomy for one low-risk class, with evidence (step 22)
cost             DBUs per exception rising                  read traces: rounds, prompt size; model choice per class

How to read the result如何解读结果

  • `{'concurrency': 8, 'p50_s': 14.1, 'p95_s': 31.4, 'error_rate': 0.0, 'rps': 0.51}` then `knee at concurrency: 8`: eight parallel triages break the 30-second p95. Run at 4 to 6 in production and raise the limit that saturated.`{'concurrency': 8, 'p50_s': 14.1, 'p95_s': 31.4, 'error_rate': 0.0, 'rps': 0.51}`,接着 `knee at concurrency: 8`:八个并行分诊会突破 30 秒的 p95。生产中以 4 到 6 的并发运行,并提升饱和的那个限制。
  • Throughput times hours tells you capacity: 0.5 triages a second is 1,800 an hour. If the business produces 3,000 exceptions a day, the agent is not the bottleneck; reviewers are.吞吐量乘以小时数就是容量:每秒 0.5 次分诊就是每小时 1,800 次。如果业务每天产生 3,000 个异常,瓶颈不是智能体,而是审核人员。

Troubleshooting排障

You see现象Why原因Do this处理
Errors appear at low concurrency低并发时就出现错误A rate limit set for people applies to the test principal.为个人设定的限流作用到了测试用的服务主体上。Run the load test as the batch principal with its own gateway limit.以批处理服务主体的身份运行负载测试,它有自己的网关限额。
Results vary run to run每次运行结果都不一样Pay-per-token endpoints are shared, so load from other tenants shows up.按 token 计费的端点是共享的,所以其他租户的负载也会体现出来。Repeat at two times of day and use the worse result; provisioned throughput removes most of the variance.在一天中的两个时段重复测试,取较差的结果;预置吞吐量可以消除大部分波动。

How this scales如何扩展

  • From one business unit to the enterprise: onboard units one at a time by adding rows to reviewer_scope and eval cases for that unit; watch its approval rate for two weeks before the next.从一个业务单元扩展到整个企业:一次接入一个单元,方法是在 reviewer_scope 中添加记录,并为该单元添加评估用例;观察它两周的批准率,再接入下一个。
  • Raising autonomy is the largest scaling lever, and it is earned: level 3 for one exception class below an amount, after a quarter with zero unsafe errors and an approval rate at the human agreement rate, written into contract.yml and approved by its owner.提高自主等级是最大的扩展杠杆,而且必须靠证据挣来:在一个季度内不安全错误为零、批准率达到人与人一致率之后,才对某一类低于某个金额的异常开放第 3 级,并写入 contract.yml,经其负责人批准。
Architecture review: questions you will be asked架构评审:你会被问到的问题
Can we skip load testing and just buy provisioned throughput?能不能跳过负载测试,直接买预置吞吐量?

You can, and you will size it wrong. The knee is often the app or a tool, not the model, and then reserved capacity is money spent on the wrong layer.可以,但你一定会买错规格。拐点往往出在 App 或某个工具上,而不是模型;那样的话,预留的容量就是花在了错误的层上。

Done when完成标准A measured knee for staging, written next to the batch concurrency and gateway limits it justifies.得到预发环境实测的拐点,并把它写在由它推导出的批处理并发和网关限额旁边。
22Operate: rollback per layer, upgrades, retention, the autonomy review运维:按层回滚、升级、保留期、自主等级评审

Why this step, and why here为什么要做这一步,为什么在这里

Something will go wrong at 4 p.m. on the last day of the month. Each layer has its own rollback that takes minutes and does not touch the others: prompt (move an alias), code (redeploy the previous tag), data (Delta restore), queue (Lakebase branch), autonomy (one line in the contract). Knowing them in advance is what makes it safe to ship weekly.月底最后一天下午四点,总会出点什么问题。每一层都有自己的回滚方法,只需几分钟,而且不影响其他层:提示词(移动别名)、代码(重新部署上一个标签)、数据(Delta 恢复)、队列(Lakebase 分支)、自主等级(契约中的一行)。事先掌握这些,才能放心地每周发布。

What it does它做什么

The commands for each rollback, the model upgrade path (a merge request that changes agent_model and must pass the gate), retention enforcement for traces and proposals, and the quarterly review that decides whether any exception class moves up an autonomy level.每种回滚的具体命令、模型升级路径(修改 agent_model 并必须通过门槛的合并请求)、追踪和提议的保留期执行,以及决定是否有某类异常可以提升自主等级的季度评审。

How to do it怎么做

  1. Rehearse each rollback once in staging and write the time it took in the runbook.在预发环境把每种回滚都演练一次,并把所用时间写进运行手册。
  2. Subscribe to the supported-models page; any model with a retirement date gets a merge request a month ahead.订阅支持模型页面;任何有下线日期的模型,都要提前一个月提交合并请求。
  3. Quarterly: new eval version from the last quarter, human agreement sample, autonomy review with the owner.每季度:用上个季度的数据生成新的评估版本、做一次人工一致性抽样,并与负责人一起做自主等级评审。

Scripts脚本

rollbacks
# prompt: move the alias back (seconds, no deploy)
python -c "import mlflow; mlflow.genai.set_prompt_alias(name='fin_prd.ai.spend_agent_instructions', alias='production', version=7)"

# code: redeploy the previous release tag through the pipeline (GitLab: run pipeline on tag v1.8.2), or
git checkout v1.8.2 && databricks bundle deploy -t prd && databricks bundle run agent -t prd

# data: restore a table to before a bad pipeline update
databricks sql query --warehouse-id <id> "RESTORE TABLE fin_prd.ai.invoice_fields TO TIMESTAMP AS OF '2026-10-30T15:00:00'"

# queue: inspect or recover from a point in time with a Lakebase branch (console: Branches > Create from point in time)

# autonomy: lower the level in contract.yml, merge; the gate and the agent read it on the next deploy

# stop everything that writes proposals, now (reviewers keep working on what is queued)
databricks jobs list --name spend-exceptions-orchestrator   # then: databricks jobs update <job_id> with pause_status PAUSED

How to read the result如何解读结果

  • A rollback that takes longer than its rehearsal time is an incident in itself: write down why.如果一次回滚比演练时用的时间长,这本身就是一起事故:记下原因。
  • The autonomy review is a decision with evidence: unsafe errors (must be zero), approval rate against human agreement, volume, and the owner's signature. Without all four, the level stays.自主等级评审是一个基于证据的决定:不安全错误(必须为零)、与人工一致率相比的批准率、处理量,以及负责人的签字。四项缺一,等级就保持不变。

Troubleshooting排障

You see现象Why原因Do this处理
RESTORE breaks the pipelineRESTORE 导致 pipeline 出错Restoring a pipeline-managed streaming table moves it behind its checkpoint.恢复由 pipeline 管理的流式表,会让它落后于其 checkpoint。For streaming tables, prefer a full refresh of that table in a budgeted window; RESTORE is for tables you own.对于流式表,优先在有预算的时间窗口内对该表做全量刷新;RESTORE 适用于你自己拥有的表。
A model retires before the upgrade passes the gate模型在升级通过门槛之前就下线了The upgrade started too late.升级启动得太晚了。Start a month ahead; if the new model fails the gate, escalate everything (level 0) rather than ship an unmeasured model.提前一个月开始;如果新模型过不了门槛,就把所有事项都升级给人处理(第 0 级),而不是上线一个未经衡量的模型。

How this scales如何扩展

  • With many workflows, the rollbacks become a platform runbook with the same five layers for every agent. That uniformity is what lets a small platform team run twenty of them.工作流很多时,这些回滚方法就成为一份平台运行手册,每个智能体都是同样的五层。正是这种一致性,让一个小型平台团队能运行二十个这样的工作流。
Architecture review: questions you will be asked架构评审:你会被问到的问题
Where is the kill switch?紧急停止开关在哪里?

Pausing the orchestrator stops new proposals in one action; reviewers can keep working what is queued, and nothing pays without them. Because the agent never writes to the system of record, stopping it never leaves a half-done payment.暂停编排 job,一个操作就能停止产生新提议;审核人员可以继续处理已在队列中的事项,而没有他们任何款项都付不出去。因为智能体从不写入记录系统,停止它永远不会留下做到一半的付款。

Done when完成标准Every rollback has been rehearsed with a recorded time, and the first quarterly review is on the calendar with its four inputs.每种回滚都已演练并记录了时间,第一次季度评审已排进日程,并准备好了四项输入。
Not confirmed on a vendor page未在厂商页面上确认`databricks sql query` as a CLI subcommand is illustrative; run RESTORE from the SQL editor if your CLI version lacks it. Pausing a job is shown as the update you would apply; the UI pause button is equivalent.`databricks sql query` 这个 CLI 子命令只是示意;如果你的 CLI 版本没有它,就在 SQL 编辑器中执行 RESTORE。暂停 job 展示的是你需要做的更新;界面上的暂停按钮效果相同。

Architecture review board架构评审委员会

Every hard question from the steps, in one place, with the answer this design gives. Use it to prepare for a design review, or to argue with the design.把各步骤中的所有尖锐问题集中在一处,并附上本设计给出的回答。可以用它来准备设计评审,也可以用它来挑战这个设计。

01 Why level 2 and not straight to automation, if the agent is accurate?如果智能体足够准确,为什么停在第 2 级,而不直接自动化?

Accuracy on last quarter is not accountability today. Level 2 produces the evidence for level 3: thousands of human decisions labelled against the agent's proposals, with the unsafe-error count at zero. The contract lets you raise the level per exception type later, for example price variances under 500, without touching the rest.上个季度的准确率不等于今天的责任归属。第 2 级为第 3 级积累证据:成千上万条针对智能体提议的人工决定标签,并且不安全错误数为零。契约允许你日后按异常类型逐步提高等级,例如低于 500 的价格差异,而不影响其他部分。

Write the workflow contract写下工作流契约
01 Who signs off a change to a threshold?谁来批准门槛值的修改?

The owner named in the contract, in the merge request that changes it. GitLab CODEOWNERS on contract.yml makes that approval mandatory.契约中指定的负责人,在修改它的合并请求中批准。对 contract.yml 设置 GitLab CODEOWNERS,可以让这项批准成为强制要求。

Write the workflow contract写下工作流契约
02 Why not let analysts edit jobs in the UI and export them later?为什么不让分析师在界面里编辑 job,之后再导出?

Because "later" is when production and git disagree and nobody knows which is right. `databricks bundle generate` exists to import an existing resource once; after that, git is the source and the UI is read-only for production.因为“之后”恰恰是生产环境和 git 不一致、没人知道哪个才对的时候。`databricks bundle generate` 用来一次性导入已有资源;在那之后,git 是唯一来源,生产环境的界面只读。

Set up the GitLab repository and the bundle建立 GitLab 仓库和 bundle
03 Why not one service principal for all environments, it is simpler?所有环境用一个服务主体不是更简单吗?

Then staging's permissions are production's, and the branch restriction cannot exist. Two principals cost two lines in the script; the separation is the control.那样的话,预发的权限就等于生产的权限,分支限制也就无从谈起。两个服务主体只多两行脚本;这种分离本身就是控制措施。

Environments and identities: OIDC federation from GitLab环境与身份:来自 GitLab 的 OIDC 联合
03 Why a separate runtime principal, when the CI principal already exists?既然已经有 CI 服务主体,为什么还要单独的运行时服务主体?

The CI principal is whoever controls main for a few minutes; the runtime principal reads every invoice, every night. If one identity did both, any merged change could exfiltrate data at deploy time. Split, a malicious deploy can still change code, but that code then runs as a principal whose grants are fixed in governance SQL, and CI needs the Service Principal User role only to set run_as.CI 服务主体代表的是在几分钟内控制 main 的人;运行时服务主体则每晚读取每一张发票。如果一个身份兼做两件事,任何合入的变更都可能在部署时把数据带走。分开之后,恶意部署仍能改代码,但代码运行时用的是一个授权固定在治理 SQL 里的主体;CI 只需要 Service Principal User 角色来设置 run_as。

Environments and identities: OIDC federation from GitLab环境与身份:来自 GitLab 的 OIDC 联合
03 Why does a merge request get no Databricks access, not even to dev?为什么合并请求连 dev 都不能访问?

Because an MR pipeline runs code from an unreviewed branch. Federation subjects match exactly, so a principal that trusted every branch would need a wildcard that does not exist. Tests run without a workspace, and each engineer deploys dev as themselves, which also keeps their experiments apart.因为合并请求流水线运行的是未经审查分支上的代码。联合策略的 subject 是精确匹配的,要让一个服务主体信任所有分支,就需要通配符,而通配符并不存在。测试无需工作区即可运行,每位工程师以自己的身份部署 dev,这也让各自的实验互不干扰。

Environments and identities: OIDC federation from GitLab环境与身份:来自 GitLab 的 OIDC 联合
04 Why filter in Unity Catalog when the app could filter in its own query?App 自己在查询里过滤不就行了,为什么要在 Unity Catalog 里过滤?

Because the agent, Genie, a dashboard and a notebook all read the same tables. A filter in the app protects one door. A policy on the data protects all of them, and an auditor can read it in one place.因为智能体、Genie、仪表盘和 notebook 读的都是同一批表。App 里的过滤只守住一扇门,数据上的策略守住所有的门,而且审计人员只需在一个地方就能看到它。

Unity Catalog layout, grants, tags and ABAC policiesUnity Catalog 布局、授权、标签和 ABAC 策略
05 Why keep bronze at all, if silver has the clean data?既然 silver 有干净的数据,为什么还要保留 bronze?

Because silver's rules will change, and when they do you rebuild silver from bronze. Without bronze, a bug in a cast is permanent. It is also the first link of the audit trail.因为 silver 的规则会变,而规则变了就要从 bronze 重建 silver。没有 bronze,一个类型转换的 bug 就是永久性的。它也是审计链条的第一环。

Bronze: land ERP extracts and invoice PDFs incrementallyBronze:增量落地 ERP 抽取文件和发票 PDF
06 Why detect exceptions with rules and not ask the model?为什么用规则来识别异常,而不是问模型?

A three-way match is arithmetic. Rules are exact, free, explainable to an auditor, and identical on every run. The model is spent where judgment is needed: deciding what to do about the exception, with evidence.三单匹配是算术。规则精确、免费、可以向审计人员解释,而且每次运行结果完全一样。模型的力气要花在需要判断的地方:凭证据决定如何处理这个异常。

Silver and gold: expectations and the three-way matchSilver 与 gold:期望规则与三单匹配
07 Is a semantic layer over-engineering for one workflow?只有一个工作流,搞语义层是不是过度设计?

It is one file. The alternative is the first meeting where the agent's number differs from the dashboard's, which ends trust in the agent for reasons that have nothing to do with the agent.它只是一个文件。不这样做的代价是:第一次开会时,智能体给的数字和仪表盘上的不一样,于是大家对智能体失去信任,而原因跟智能体本身毫无关系。

The semantic layer: a metric view and real comments语义层:指标视图和真正有用的注释
08 Why not let the agent read the PDF itself when it needs to?为什么不让智能体在需要时自己去读 PDF?

Because then each triage pays to read the document again, the result is not stored, and nobody can query "how many invoices disagree with the ERP". Extraction is data engineering: do it once, store it, govern it.因为那样每次分诊都要为再读一遍文档付费,结果不会被保存,也没人能查询“有多少张发票与 ERP 不一致”。抽取属于数据工程:做一次、存下来、纳入治理。

Parse and extract invoice fields, then check them against the ERP解析并抽取发票字段,再与 ERP 核对
09 Could the agent classify in its own prompt instead?能不能让智能体在自己的提示词里顺便分类?

It could, and then the category would be invisible, unmeasured and paid for on every triage. As a column it is measured once, queryable, and reused by dashboards and policy routing alike.可以,但那样类别就不可见、没有被衡量,而且每次分诊都要付费。作为一列数据,它只需衡量一次,可以查询,并被仪表盘和政策路由共同复用。

Classify spend categories, and measure the classifier per class对支出类别分类,并逐类衡量分类器
10 Why not paste the whole policy into the prompt?为什么不把整份政策直接贴进提示词?

It is paid on every call, it dilutes attention, and it cannot cite a chunk id a reviewer can open. Retrieval makes the citation a pointer, which is what makes the proposal reviewable.那样每次调用都要付费,会分散注意力,而且无法引用审核人员能打开的文本块 id。检索让引用成为一个指针,正是这一点让提议变得可以审核。

Index the payment policy in AI Search在 AI Search 中为付款政策建立索引
11 Text-to-SQL is risky. Why give it to an agent that proposes payments?Text-to-SQL 有风险,为什么交给一个会提议付款的智能体?

It reads under Unity Catalog permissions and never writes, and the agent's figures are checked against the evidence before a proposal is queued. Genie is for context; the decision facts come from get_exception, a fixed function.它在 Unity Catalog 权限下只读、从不写入,而且智能体给出的数字在提议进入队列之前都要对照证据检查。Genie 用来提供背景;决策所依据的事实来自 get_exception 这个固定函数。

A Genie space over gold, benchmarked like code在 gold 上建 Genie space,并像代码一样做基准测试
12 Why is there no write tool?为什么没有写入工具?

Because a model holding a write tool is one prompt injection away from writing. The agent returns a structured proposal; code checks it and writes it to the queue. The write path has no model in it.因为持有写入工具的模型,离被提示词注入后执行写入只有一步之遥。智能体返回一个结构化提议;由代码检查后写入队列。写入路径上没有模型。

Read tools as Unity Catalog functions把读取工具做成 Unity Catalog 函数
13 Why one model and not a router across five?为什么只用一个模型,而不是在五个模型之间路由?

Every model added is another eval to run and another behaviour to explain. Add a second model only when the eval shows a cheaper one matches on a class of exceptions; then route that class, and measure it.每增加一个模型,就多一套要运行的评估、多一种要解释的行为。只有当评估表明某个更便宜的模型在某类异常上表现相当时,才增加第二个模型;然后只路由那一类,并对它进行衡量。

Models through the Unity Gateway: limits, guardrails, logs通过 Unity Gateway 访问模型:限流、护栏、日志
14 Why not a multi-agent supervisor with a policy agent, a data agent and a decision agent?为什么不用一个主管智能体,下面分政策智能体、数据智能体和决策智能体?

Module 12's measurement: more agents meant more model calls for the same answer. One agent with three tools is cheaper, faster and has one trace to read. Split only when a measured failure points at a boundary.第 12 模块的测量结果是:智能体越多,得到同样答案所需的模型调用就越多。一个智能体加三个工具更便宜、更快,也只需读一条追踪。只有当测量到的失败明确指向某条边界时才拆分。

Build the agent: tools via MCP, structured output, code-side checks构建智能体:通过 MCP 使用工具、结构化输出、代码侧检查
14 What if the model is prompt-injected by text in an invoice PDF?如果发票 PDF 里的文字对模型进行了提示词注入怎么办?

It can only change the proposal, which then fails the code checks or reaches a person who sees the evidence. It cannot pay, write, or call a write tool, because none exists. Treat document text as data: the reviewer UI escapes it.它只能改变提议,而这份提议要么过不了代码检查,要么会交到一个能看到证据的人手里。它无法付款、无法写入,也无法调用写入工具,因为根本没有这种工具。把文档文本当作数据处理:审核界面会对其进行转义。

Build the agent: tools via MCP, structured output, code-side checks构建智能体:通过 MCP 使用工具、结构化输出、代码侧检查
15 Why a custom app and not the Agent Bricks review UI or a dashboard?为什么要自己做 App,而不用 Agent Bricks 的审核界面或仪表盘?

The decision needs rules a generic UI does not have: units from Unity Catalog, the two-person rule, a required correction on reject, an append-only log. Those are payment controls. Use the MLflow labeling tools for SME feedback on traces (step 17), which is a different job.这个决定需要通用界面没有的规则:来自 Unity Catalog 的单元范围、双人复核、拒绝时必须给出纠正、只追加的日志。这些都是付款控制措施。MLflow 的标注工具用于专家对追踪的反馈(第 17 步),那是另一项工作。

The review queue and the reviewer app审核队列与审核 App
16 Why not use an LLM judge for correctness?为什么不用 LLM 评审来判断正确性?

Because there is ground truth: what a person decided. Judges are for things without ground truth, such as whether a rationale is clear, and module 12 showed judges must be calibrated against people before they are trusted.因为这里有标准答案:人做出的决定。评审模型适用于没有标准答案的东西,比如理由是否清楚;而第 12 模块已经说明,评审模型在被信任之前必须先与人工对齐校准。

The evaluation set and the release gate评估集与发布门槛
17 If reviewers check everything, why monitor at all?既然审核人员会检查所有内容,为什么还要监控?

Because reviewers get tired and approve what looks plausible. A rising approval rate can mean a better agent or a rubber stamp. Scorers that do not get tired, and a periodic second-reviewer sample, tell those apart.因为审核人员会疲劳,会批准看起来说得通的东西。批准率上升,可能意味着智能体变好了,也可能意味着审核成了橡皮图章。不会疲劳的 scorer,加上定期的第二审核人抽样,能区分这两种情况。

Production monitoring and SME feedback生产监控与专家反馈
18 Why a manual production step, when continuous deployment is best practice?持续部署才是最佳实践,为什么生产还要手动?

For a workflow that proposes payments, a named approver is a control your auditors will ask for. The manual step costs a click after an automated gate; it can become automatic later for change types the contract allows, such as prompt wording below a risk threshold.对于一个会提议付款的工作流,具名的审批人是审计人员会要求的控制措施。这个手动步骤只是在自动门槛之后多点一下;之后对于契约允许的变更类型(例如低于风险阈值的提示词措辞调整),可以改成自动。

GitLab CI/CD: test, deploy, gate, promoteGitLab CI/CD:测试、部署、门槛、晋级
19 Why not run the agent inside the job, in-process, to save the HTTP hop?为什么不在 job 里直接以进程内方式运行智能体,省掉一次 HTTP 调用?

Then the batch and the evaluated app could differ in dependencies, prompts and identity. The hop costs milliseconds against a 16-second triage; one code path is worth far more.那样的话,批处理和被评估的 App 可能在依赖、提示词和身份上出现差异。相对于一次 16 秒的分诊,这次调用只多几毫秒;而只有一条代码路径的价值要大得多。

Orchestrate with Lakeflow Jobs用 Lakeflow Jobs 编排
20 Approval rate is a vanity metric, isn't it?批准率不就是个虚荣指标吗?

Alone, yes. Paired with rejected payment proposals (which must be zero) and a monthly second-reviewer sample (do people agree with each other?), it becomes a measured accuracy with a person behind every label.单独看,是的。但配上被拒绝的付款提议(必须为零)和每月一次的第二审核人抽样(人与人之间是否一致?),它就成了一个以人为每个标签背书的实测准确率。

Observability: cost, quality, backlog, data quality可观测性:成本、质量、积压、数据质量
21 Can we skip load testing and just buy provisioned throughput?能不能跳过负载测试,直接买预置吞吐量?

You can, and you will size it wrong. The knee is often the app or a tool, not the model, and then reserved capacity is money spent on the wrong layer.可以,但你一定会买错规格。拐点往往出在 App 或某个工具上,而不是模型;那样的话,预留的容量就是花在了错误的层上。

Load test, find the knee, then scale the limit you hit做负载测试,找到拐点,再扩展你碰到的那个限制
22 Where is the kill switch?紧急停止开关在哪里?

Pausing the orchestrator stops new proposals in one action; reviewers can keep working what is queued, and nothing pays without them. Because the agent never writes to the system of record, stopping it never leaves a half-done payment.暂停编排 job,一个操作就能停止产生新提议;审核人员可以继续处理已在队列中的事项,而没有他们任何款项都付不出去。因为智能体从不写入记录系统,停止它永远不会留下做到一半的付款。

Operate: rollback per layer, upgrades, retention, the autonomy review运维:按层回滚、升级、保留期、自主等级评审

Production readiness audit生产就绪审计

A release is production-ready when every item is true and you can show the evidence. Tick as you go; ticks stay in this browser only.只有当每一项都成立,并且你能拿出证据时,一个版本才算具备生产条件。边做边勾选;勾选记录只保存在当前浏览器中。

0 / 25 · not ready yet尚未就绪

Scope and accountability范围与责任

Security and identity安全与身份

Data governance数据治理

AI qualityAI 质量

Operations运维

Sources来源