Skip to content

feat(ontology): Phase 1 — concept-index emission (issue #58, A1-A8 squashed) - #92

Merged
haiyuan-eng-google merged 1 commit into
GoogleCloudPlatform:mainfrom
caohy1988:feat/phase1-concept-index-cherry-pick
Apr 28, 2026
Merged

haiyuan-eng-google merged 1 commit into
GoogleCloudPlatform:mainfrom
caohy1988:feat/phase1-concept-index-cherry-pick

Conversation

@caohy1988

Copy link
Copy Markdown
Collaborator

Summary

Closes Phase 1 of the concept-index + runtime entity-resolution work tracked in #58. Squashed cherry-pick of five PRs that landed individually on the haiyuan-eng-google/BigQuery-Agent-Analytics-SDK-fork:

  • A1 (_fingerprint.py)
  • A2 (concept_index.py row builder)
  • A3-A5 (compile_concept_index emitter)
  • A7 (CLI flags)
  • A8 (user docs)

End-to-end after merge:

gm compile binding.yaml \
  --emit-concept-index \
  --concept-index-table proj.dataset.ontology_concept_index

emits the existing CREATE PROPERTY GRAPH DDL plus two atomic CREATE OR REPLACE TABLE statements (a main concept-index table and its __meta provenance sibling). Byte-identical SQL across runs. Without the new flag, gm compile output is byte-identical to today (regression-test pinned).

Phase 1 ships SQL emission only. The runtime consumer in bigquery_agent_analytics (OntologyRuntime, resolvers, strict verification) is Phase 2-3 follow-on work, not in this PR.

What's in the diff

+2859 / 0 across 12 files:

File Status
src/bigquery_ontology/_fingerprint.py NEW (180 lines) — A1
src/bigquery_ontology/concept_index.py NEW (336 lines) — A2
src/bigquery_ontology/graph_ddl_compiler.py +301 lines — A3-A5
src/bigquery_ontology/__init__.py +2 lines (re-export compile_concept_index)
src/bigquery_ontology/cli.py +116 lines — A7
tests/bigquery_ontology/test_fingerprint.py NEW (388 lines, 24 tests)
tests/bigquery_ontology/test_concept_index.py NEW (550 lines, 21 tests)
tests/bigquery_ontology/test_compile_concept_index.py NEW (473 lines, 31 tests)
tests/bigquery_ontology/test_cli.py +182 lines (8 A7 tests)
docs/ontology/concept-index.md NEW (277 lines) — A8
docs/ontology/cli.md +27 lines
docs/ontology/compilation.md +27 lines

Behavior pinned

  • Byte-identical regression — gm compile without the new flag matches today's output exactly.
  • Byte-deterministic concept-index SQL (D2) — same (ontology, binding, output_table, compiler_version) produces byte-identical output across runs.
  • Scope rule (D3) — abstract entities always included; concrete iff bound.
  • Multi-scheme (D4) — denormalized cross-product; DISTINCT entity_name returns one per concept.
  • Notation as first-class row (D5) — label_kind='notation' row plus per-row notation column.
  • GoogleSQL string escaping — verified end-to-end against actual BigQuery: 'O\'Brien' (single-quote → \', not ANSI ''), 'C:\\Users' (backslash doubled), 'line1\nline2' (control chars escaped), UTF-8 passthrough for non-ASCII.
  • Output-table validation — three dot-separated [A-Za-z0-9_-]+ segments; backticks rejected (the emitter adds them).
  • Required-flag enforcement — --emit-concept-index without --concept-index-table exits 2 with a clear error; reverse case (orphan --concept-index-table) also rejected.
  • Provenance Option 2 — compile_id (12-hex display) and compile_fingerprint (64-hex integrity key) on every row of both tables. Structural invariant compile_id == compile_fingerprint[:12] enforced at the function boundary; pinned by a golden vector test.
  • Empty refused — zero-row case raises ValueError rather than emit a typeless empty array.

Test plan

  • pytest tests/bigquery_ontology/test_fingerprint.py tests/bigquery_ontology/test_concept_index.py tests/bigquery_ontology/test_compile_concept_index.py tests/bigquery_ontology/test_cli.py → 123 passed
  • pytest tests/ → 2119 passed, 7 skipped, 0 failures
  • bash autoformat.sh → no diff remaining
  • End-to-end against actual BigQuery (test-project-0728-467323, 2026-04-26):
    • bq query --dry_run accepts the emitted SQL on simple + rich-SKOS ontologies
    • Real DDL execution: both tables created, all rows queryable
    • All six label_kind values round-trip; @fr annotations populate the language column; backslash + apostrophe literals round-trip; pair-consistency confirmed (main.compile_fingerprint == meta.compile_fingerprint)
    • Resolver SQL patterns from concept-index.md §8 (winning-label dedup, notation lookup, apostrophe-input resolution) all return the correct entity

Compatibility

  • compile_graph contract: unchanged, byte-identical regression test pins this.
  • gm compile without --emit-concept-index: byte-identical to today.
  • Public surface added: compile_concept_index (new function), --emit-concept-index / --concept-index-table / --compiler-version (new CLI flags). No removals or signature changes.
  • _fingerprint and concept_index modules are not re-exported from bigquery_ontology/__init__.py — internal implementation detail.

Out of scope (deferred)

  • A6 shadow-swap fallback for >50K rows — Phase 3.
  • Phase 2 SDK consumer (OntologyRuntime, resolvers, strict verification) — separate follow-on PRs.
  • Embedding-based fuzzy matching, live-agent resolver package — RFC §12.

Provenance

Per-PR review history is preserved on the fork:

Notable findings resolved before squash (full discussion threads on the linked PRs):

  • A2: skos:topConceptOf now unioned with skos:inScheme; duplicate label tuples deduped on the contract tuple.
  • A3-A5: string-literal renderer is now GoogleSQL (\' for single quotes, not ANSI ''); backslashes doubled; control chars escaped; output-table validator rejects pre-quoted backticks; Option 2 provenance split (compile_id display + compile_fingerprint integrity); golden vector test pins the byte-exact digest.
  • A7: orphan --concept-index-table (without --emit-concept-index) now rejected to surface typos.
  • A8: atomicity claim softened ("overwrites both tables atomically" was inaccurate — each CREATE OR REPLACE is atomic but the pair is not, which is exactly why compile_fingerprint exists); OntologyRuntime references reframed as future Phase 2/3; zero-row failure case stated precisely (abstract-only ontologies compile successfully).

Companion docs already on main: the RFC (docs/entity_resolution_primitives.md, #73) and the in-repo plan (docs/implementation_plan_concept_index_runtime.md, #70 / #72 / #80) frame this work; the PR is the implementation those docs describe.

…atform#58, A1-A8 squashed)

Closes Phase 1 of the concept-index + runtime entity-resolution work
tracked at GoogleCloudPlatform#58.

This is a squashed cherry-pick of five PRs that landed individually
on the haiyuan-eng-google/BigQuery-Agent-Analytics-SDK-fork: A1
(``_fingerprint``), A2 (``concept_index`` row builder), A3-A5
(``compile_concept_index`` emitter), A7 (CLI flags), A8 (user docs).

End-to-end after this merges:

  gm compile binding.yaml \
    --emit-concept-index \
    --concept-index-table proj.dataset.ontology_concept_index

emits the existing ``CREATE PROPERTY GRAPH`` DDL plus two atomic
``CREATE OR REPLACE TABLE`` statements (a main concept-index table
and its ``__meta`` provenance sibling). Same inputs produce
byte-identical SQL. Without the new flag, ``gm compile`` output is
byte-identical to today (regression test pinned).

Phase 1 ships SQL emission only. The runtime consumer in
``bigquery_agent_analytics`` (``OntologyRuntime``, resolvers, strict
verification) is Phase 2-3 follow-on work, not in this PR.

## What landed

### A1 — Internal fingerprint module (``src/bigquery_ontology/_fingerprint.py``)

Single source of truth for canonical model fingerprinting. Three
exports, all internal (underscore-prefix module, not re-exported):

- ``fingerprint_model(model: BaseModel) -> "sha256:<64 hex>"`` —
  canonical SHA-256 over ``model_dump(mode="json", by_alias=False,
  exclude_none=False)`` then sort-keyed compact JSON. Non-semantic
  YAML edits (whitespace, comments, key order) produce identical
  fingerprints; semantic edits (rename, type change) produce
  different fingerprints.
- ``compile_fingerprint(ont_fp, bnd_fp, compiler_version) -> str``
  — full 64-hex SHA-256 over the NUL-delimited UTF-8 of the three
  inputs. Canonical integrity key.
- ``compile_id(ont_fp, bnd_fp, compiler_version) -> str`` — 12-hex
  display token, derived as ``compile_fingerprint(...)[:12]``. The
  derivation is structural; ``compile_id`` never computes its own
  hash. Display-only — never used as the sole freshness check.

Invariant ``compile_id == compile_fingerprint[:12]`` is enforced at
the function boundary so the two cannot drift out of sync. Pinned
by a golden vector test (input ``("sha256:aa", "sha256:bb",
"gm-1.0.0")`` produces digest
``dd301e2874a3bc55dd3ab6ea428ad1046f6b4834b4dccd7a87cf82a1991e0184``).

### A2 — Row builder (``src/bigquery_ontology/concept_index.py``)

Pure transform from ``(Ontology, Binding)`` to a deterministic list
of ``ConceptIndexRow`` dataclasses ready for SQL emission.
Behavior:

- **Scope rule.** Abstract entities always included regardless of
  binding; concrete entities iff they appear in
  ``binding.entities``.
- **Multiplicity.** One row per ``(entity_name, label, label_kind,
  language, scheme)`` membership tuple. Multi-scheme cross-product.
- **Notation.** First-class ``label_kind='notation'`` row per
  ``skos:notation`` value, plus a per-row ``notation`` column on
  every row of the entity.
- **Schemes.** ``skos:inScheme`` and ``skos:topConceptOf`` are
  unioned and deduped — top concepts of a scheme are members of
  that scheme.
- **Sort order.** Lexicographic with NULLs last on ``(scheme,
  entity_name, label_kind, language, label, notation,
  is_abstract)``. Purely for byte-deterministic SQL emission. The
  semantic ``label_kind`` priority (``name > pref > alt > hidden >
  synonym > notation``) is applied at query time via a CASE
  expression by resolvers.
- **Dedup.** Duplicate input values (e.g. ``synonyms=["Acct",
  "Acct"]``) collapse to one row by the contract tuple. Same value
  via different ``label_kind`` (e.g. one as ``synonym`` and one as
  ``alt``) keeps both rows.

### A3-A5 — Compile emitter (``src/bigquery_ontology/graph_ddl_compiler.py``)

Adds ``compile_concept_index(ontology, binding, *, output_table,
compiler_version) -> str`` alongside the existing ``compile_graph``.
Re-exported from ``bigquery_ontology/__init__.py``. Emits two
atomic ``CREATE OR REPLACE TABLE T AS SELECT * FROM
UNNEST(ARRAY<STRUCT<...>>[...])`` statements (main + ``__meta``).
Each statement is atomic per BigQuery's DDL semantics; the pair is
not a cross-table transaction (BigQuery has no DDL transactions
across tables), so pair-consistency between main and ``__meta`` is
enforced at runtime via the shared ``compile_fingerprint``.

Two pinned columns implement the **Option 2** provenance contract:

| Column | Role | Width |
|---|---|---|
| ``compile_id`` | Display/debug token only | 12 hex chars |
| ``compile_fingerprint`` | Canonical integrity key | 64 hex chars |

Strict verification (Phase 3) will use ``compile_fingerprint``
exclusively; ``compile_id`` never appears on the verification
path.

The string-literal renderer is GoogleSQL-correct, not ANSI-SQL:
single quotes escape as ``\\'`` (the doubled-quote ANSI form
``''`` parses as two adjacent literals in BigQuery and errors with
"concatenated string literals must be separated by whitespace or
comments"). Backslashes escape as ``\\\\``; ASCII control
characters get named escapes (``\\n``, ``\\r``, ``\\t``, ``\\b``,
``\\f``) or ``\\xHH`` fallback. Non-ASCII UTF-8 passes through.
Verified end-to-end against actual BigQuery (see e2e test plan
below).

The ``output_table`` validator requires three dot-separated
segments matching ``[A-Za-z0-9_-]+`` and rejects backticks (the
emitter adds them) — keeps the SQL unbreakable by an injected
backtick.

Compile fails with a clear ``ValueError`` if the row builder
produces an empty list (no concrete bound entities and no abstract
entities) — refusing to emit a typeless empty array.

No timestamps in the emitted SQL; ``compiled_at`` was deliberately
omitted for byte-identical determinism.

### A7 — CLI flags (``src/bigquery_ontology/cli.py``)

Three new flags on ``gm compile``:

- ``--emit-concept-index`` (boolean) — opt-in toggle; without it,
  output is byte-identical to today.
- ``--concept-index-table <project.dataset.table>`` — required
  when emit is set; no silent global default. Backticks rejected;
  segments validated.
- ``--compiler-version <str>`` — optional override for the version
  string flowed into ``compile_fingerprint``. Defaults to the
  installed package version via ``importlib.metadata.version``
  with a ``"unknown"`` fallback for checkout runs.

Required-flag enforcement: ``--emit-concept-index`` without
``--concept-index-table`` exits 2 with a clear error. The reverse
(orphan ``--concept-index-table`` without the emit flag) is also
rejected so misspellings don't silently drop.

### A8 — User docs

- New ``docs/ontology/concept-index.md`` (277 lines) — full user
  reference with both table schemas (logical-vs-enforced
  ``NOT NULL`` clarified — CTAS doesn't carry table-level
  constraints), the Option 2 provenance contract, determinism
  guarantees, four canonical SQL patterns (bulk resolution,
  coverage by scheme, winning-label dedup with the priority CASE,
  manual pair-consistency check), and the Phase 1 out-of-scope
  list.
- ``docs/ontology/cli.md`` — three new flag rows + a
  "Concept-index extension" subsection with a worked example.
- ``docs/ontology/compilation.md`` — new §7a "Sibling emitter"
  noting the independent-functions relationship between
  ``compile_graph`` (unchanged byte-identical contract) and the
  new ``compile_concept_index``.

## Tests

123 new tests covering everything above:

- ``tests/bigquery_ontology/test_fingerprint.py`` (24 tests) —
  fingerprint determinism, semantic-edit sensitivity,
  ``compile_fingerprint``/``compile_id`` invariant, golden vector,
  private-surface guard.
- ``tests/bigquery_ontology/test_concept_index.py`` (21 tests) —
  row shape, scope rule (D3), multi-scheme (D4), notation as
  first-class row (D5), determinism (D2), ``skos:topConceptOf``
  union with ``skos:inScheme``, dedup contract.
- ``tests/bigquery_ontology/test_compile_concept_index.py``
  (31 tests) — output shape, provenance, byte-identical
  determinism, GoogleSQL-correct string escaping (literal
  newline, backslash, single quote → ``\\'``, control chars),
  scope round-trip, notation row, empty-rows refusal,
  output-table validation (rejects backticks, invalid chars,
  wrong segment counts).
- ``tests/bigquery_ontology/test_cli.py`` (8 new tests for the
  ``--emit-concept-index`` family) — byte-identical without flag,
  required-flag enforcement, orphan-flag rejection, combined
  output ordering, ``-o PATH`` composition, invalid-table error,
  determinism, ``--compiler-version`` override.

## End-to-end verification

Validated against actual BigQuery (test-project-0728-467323) on
2026-04-26:

- ``bq query --dry_run`` accepts the emitted SQL on both simple
  and rich-SKOS ontologies.
- Real DDL execution: both tables created, all rows queryable.
- All six ``label_kind`` values present in the index for an
  ontology with ``skos:prefLabel`` / ``skos:altLabel`` / ``skos:notation``.
- ``skos:prefLabel@fr`` populates the ``language`` column with
  ``'fr'``.
- Backslash literals (``"Bank\\Account"``) and apostrophes
  (``"O'Brien Account"``) round-trip correctly through
  emit + execute + select.
- Pair consistency confirmed:
  ``main.compile_fingerprint == meta.compile_fingerprint == true``.
- Resolver SQL patterns from §8 of ``concept-index.md`` (winning-
  label dedup with priority CASE, notation lookup, alt-label
  resolution, apostrophe input) all return the correct entity.

Per-PR review history with reviewer findings is preserved on the
fork: PRs GoogleCloudPlatform#40, GoogleCloudPlatform#41, GoogleCloudPlatform#43, GoogleCloudPlatform#46, GoogleCloudPlatform#47 in
haiyuan-eng-google/BigQuery-Agent-Analytics-SDK-fork. Notable
findings resolved before squash:

- A2 row builder: ``skos:topConceptOf`` initially missed (now
  unioned with ``skos:inScheme``); duplicate label tuples
  initially emitted as duplicate rows (now contract-tuple
  deduped).
- A3-A5 emitter: string-literal renderer initially used ANSI
  ``''`` quote-doubling (changed to GoogleSQL ``\\'`` after a
  reviewer dry-ran ``'O''Brien'`` against BigQuery and got
  "concatenated string literals must be separated by whitespace
  or comments"). Backslashes initially passed through unescaped
  (now doubled). Output-table validation initially accepted
  pre-quoted backticks (now rejected). Schema row built without a
  full integrity column (Option 2 contract: split into
  ``compile_id`` display + ``compile_fingerprint`` integrity,
  invariant ``compile_id == compile_fingerprint[:12]`` enforced
  at the function boundary).
- A7 CLI: required-flag enforcement initially missing for the
  reverse case (orphan ``--concept-index-table`` without
  ``--emit-concept-index`` now errors).
- A8 docs: initial overstatements caught — atomicity claim
  ("overwrites both tables atomically") softened to per-statement
  atomicity with explicit pair-consistency-via-fingerprint
  rationale; ``OntologyRuntime`` / verification references
  reframed as future Phase 2/3 work; abstract-only ontology
  documented as compiling successfully (not the failure case;
  zero-row case is the failure).

## Out of scope (deferred)

- A6 shadow-swap fallback for >50K rows — Phase 3.
- Phase 2 SDK consumer (``OntologyRuntime``, resolvers, strict
  verification) — separate stack of follow-on PRs.
- Embedding-based fuzzy matching, live-agent resolver package —
  RFC §12.

## Compatibility

- ``compile_graph`` contract: unchanged. Byte-identical regression
  test pins this.
- ``gm compile`` without ``--emit-concept-index``: byte-identical
  to today's output.
- Public surface added: ``compile_concept_index`` (new function),
  ``--emit-concept-index`` / ``--concept-index-table`` /
  ``--compiler-version`` (new CLI flags). No removals or
  signature changes.
- ``_fingerprint`` and ``concept_index`` modules are not
  re-exported from ``bigquery_ontology/__init__.py`` — internal
  implementation detail; importable via explicit module path.

Companion docs already on ``main``: the RFC
(``docs/entity_resolution_primitives.md``, GoogleCloudPlatform#73) and the in-repo
implementation plan
(``docs/implementation_plan_concept_index_runtime.md``, GoogleCloudPlatform#70 / GoogleCloudPlatform#72
/ GoogleCloudPlatform#80) frame the work; this PR is the Phase 1 implementation
those docs describe.
@haiyuan-eng-google
haiyuan-eng-google merged commit 4e66ccf into GoogleCloudPlatform:main Apr 28, 2026
9 checks passed
caohy1988 added a commit to caohy1988/BQAA-SDK-fork that referenced this pull request May 12, 2026
Addresses PR GoogleCloudPlatform#154 round-1 reviewer findings.

P1 #1 — table_id injection guard. ConceptIndexLookup.__init__
used to interpolate table_id directly into backtick-quoted SQL
in verify() and _run_lookup() without shape validation. New
_TABLE_ID_PATTERN regex (same discipline as
BigQueryBundleStore from Phase C): exactly three ASCII
segments, [A-Za-z0-9_-]+, fullmatch (not match — trailing
newline rejected). Backtick, semicolon, whitespace, comment
markers, wrong dot count, and non-string all raise ValueError
at construction. Validation flows through
OntologyRuntime.from_models so callers who never construct
ConceptIndexLookup directly still get the protection.

P1 GoogleCloudPlatform#2 — drop unsafe singular relationship(name) accessor; add
traversal helpers. Per GoogleCloudPlatform#58's traversal-first contract
(entity_resolution_primitives.md:118), relationship names are
NOT unique once GoogleCloudPlatform#62's relaxed (name, from, to) uniqueness
ships — traversal-style names like skos_broader legally
repeat across endpoint pairs. The singular
relationship(name) -> Relationship | None accessor would
silently return the first match and hide duplicates; dropped
entirely. New relationships_by_name(name) -> tuple[
Relationship, ...] returns every match. Plus four SKOS
traversal helpers the user asked for:

* in_scheme(scheme) -> tuple of entity names (forward map).
* broader(entity_name) -> direct skos:broader parents.
* narrower(entity_name) -> inverse (children that declare
  this as broader). Not transitive.
* related(entity_name) -> skos:related values (not
  auto-symmetrized).

Companion notations_for(entity_name) returns every notation
value (scalar or list), companion to notation_for which
returns only the first.

P2 #1 — verify() always re-queries. Dropped the _verified
cache flag. The docstring promised "re-check before long
batches" but the cached fast path made re-runs no-ops. Now
every verify() call hits BigQuery again so a table swap or
fingerprint update mid-flight is caught. Construction-time
eager verify still runs once; subsequent verify() calls all
re-query.

P2 GoogleCloudPlatform#2 — reject multiple __meta rows. PR GoogleCloudPlatform#92's emission writes
exactly one meta row per table; multiple rows indicate manual
tampering. verify() SQL now uses LIMIT 2 (not LIMIT 1) so a
multi-row case is detectable without a full scan; len(rows)
!= 1 fails closed with new MetaTableMultipleRowsError
(subclasses ConceptIndexError). The empty case still uses
MetaTableEmptyError; multi is a distinct error code so
callers can switch on the failure mode.

P2 GoogleCloudPlatform#3 — labels_for() now emits skos:notation as
label_kind='notation', matching PR GoogleCloudPlatform#92's six-kind vocabulary
(name / pref / alt / hidden / synonym / notation). The
previous omission meant a caller comparing in-memory labels
against emitted concept-index rows would see five kinds
locally vs six remotely.

Tests: 39 -> 50 cases. New TestRoundOneFindings (11 cases)
locks each finding with explicit reproducers:

* test_lookup_rejects_malformed_table_id — every injection
  pattern + valid form acceptance.
* test_runtime_propagates_table_id_validation — validation
  flows through OntologyRuntime factories.
* test_relationships_by_name_returns_every_match — builds
  duplicate-name relationships directly via the Pydantic
  models (load_ontology enforces pre-GoogleCloudPlatform#62 uniqueness, so the
  test bypasses the YAML path).
* test_singular_relationship_accessor_is_dropped —
  hasattr(runtime, "relationship") is False.
* test_in_scheme_lists_member_entities,
  test_broader_narrower_related — traversal helpers.
* test_verify_always_re_queries — swappable fake client
  returning matching→mismatched fingerprints across calls;
  construction + two re-checks all hit BigQuery (3 calls
  total).
* test_multiple_meta_rows_fails_closed,
  test_verify_uses_limit_2_to_detect_multi_row — multi-row
  __meta path + LIMIT 2 SQL lock.
* test_labels_for_includes_notation,
  test_notations_for_returns_all_values — notation surfaces
  in labels_for; CA appears as BOTH 'synonym' (declared in
  synonyms:) AND 'notation' (declared in skos:notation),
  matching PR GoogleCloudPlatform#92's multiplicity contract.

Live BQ validation: ran
tests/test_ontology_runtime_live.py against real BigQuery
(test-project-0728-467323 / adk_e2e_test) — the full
emit-DDL → create-tables → attach-runtime →
verify-fingerprint → run-resolver → notation-lookup →
drop-tables round-trip passes in ~15s. All 50 CI tests
pass; pyink + isort clean.
caohy1988 added a commit to caohy1988/BQAA-SDK-fork that referenced this pull request May 12, 2026
…ale doc summaries

Addresses PR GoogleCloudPlatform#154 round-2 reviewer findings.

P2 - lookup_by_notation() was querying the per-row notation
column (``WHERE notation = @notation``), but PR GoogleCloudPlatform#92's
concept-index emission contract says:

* every declared notation value gets one
  ``label_kind='notation'`` row where ``label`` IS the
  notation, and
* the per-row ``notation`` column is only the per-entity
  *display token* — for multi-notation entities,
  ``_entity_notation()`` keeps only the lexicographically
  smallest value.

Result: ``lookup_by_notation("B")`` on an entity declaring
``skos:notation: ["A", "B"]`` used to miss the entity
entirely because the ``notation`` column held "A". Fix:
query ``WHERE label_kind = 'notation' AND label = @notation``
so all declared notations are reachable.

Tests: 50 -> 52.

* test_lookup_by_notation rewritten to match the new
  predicate (rows now carry label='CA', label_kind='notation').
* test_lookup_by_notation_finds_secondary_notations is the
  reviewer's reproducer: notation row with label='B' but
  the per-row notation column carrying 'A' — the entity is
  found via the new predicate.
* test_lookup_by_notation_sql_pins_label_predicate captures
  the SQL and asserts ``label = @notation`` is in the
  WHERE clause AND ``WHERE notation = @notation`` is not —
  prevents regression.

Live BQ validation: bumped the live test fixture to declare
two notations (skos:notation: ["CA", "ZZ-LATE"]) and added a
lookup for the secondary value. Locks the round-1 P2 fix
against real BigQuery, not just the in-memory fake:

* lookup_by_notation("CA") finds the entity (primary,
  lex-min).
* lookup_by_notation("ZZ-LATE") ALSO finds the entity even
  though the per-row notation column is "CA" — the new
  predicate path is the only correct one.
* Round-trip passes end-to-end against
  test-project-0728-467323 in ~30s.

P3 - stale doc summaries:
* docs/README.md index entry now lists
  MetaTableMultipleRowsError alongside the other three
  stable failure codes, and calls out the round-1 fixes
  (table_id validation, always-requery verify, traversal
  helpers).
* CHANGELOG entry updated with MetaTableMultipleRowsError
  in the failure-codes list and bumped from "39 cases" to
  "52 cases."
* docs/ontology_runtime_reader.md test-section bumped from
  50 -> 52, TestConceptIndexLookupQueries count from 8 -> 10
  with the notation-predicate semantics spelled out, live
  test description updated to mention the multi-notation
  fixture.
caohy1988 added a commit to caohy1988/BQAA-SDK-fork that referenced this pull request May 12, 2026
…t first-authored

Addresses PR GoogleCloudPlatform#154 round-3 P2 reviewer finding.

P2 - notation_for() returned the first authored skos:notation
list value, but PR GoogleCloudPlatform#92's emitter uses min(values) for the
per-row notation display column (see
bigquery_ontology.concept_index._entity_notation). The two
views disagreed when notations were declared in non-sorted
order: an entity with skos:notation: ["B", "A"] would have
ExactEntityResolver report "B" while concept-index-backed
rows reported "A". The reader runtime and the concept-index
table must agree on the same display token.

Fix: notation_for(entity_name) now returns min(notations_for(
entity_name)) so the runtime view matches the emission's
lex-min rule. notations_for() still preserves declaration
order — callers needing every authored value (e.g. to feed
ConceptIndexLookup.lookup_by_notation) keep their option.

Tests: 52 -> 54.

* test_notation_for_returns_lex_min_display_token: entity
  declaring skos:notation: ["B", "A", "C"] returns "A" from
  notation_for() (lex-min, not first-authored "B").
* test_exact_resolver_uses_lex_min_notation: end-to-end lock
  via ExactEntityResolver — candidate.notation == lex-min
  so the two resolver paths agree on the same entity's
  notation.

Live BQ validation: bumped the live fixture from
skos:notation: ["CA", "ZZ-LATE"] (already sorted, where lex-
min == first-authored "CA") to ["ZZ-LATE", "CA"] (first-
authored "ZZ-LATE", lex-min "CA"). The live test now asserts
runtime.notation_for("CaliforniaRegion") == "CA" against
real BigQuery — locking both the round-2 multi-notation
lookup AND the round-3 lex-min display-token rule.
Round-trip passes against test-project-0728-467323 in ~16s.

Docs:
* ontology_runtime_reader.md: notation_for table row
  describes the lex-min rule, test list bumped to 54 with
  the new regression spelled out.
* CHANGELOG: CI case count bumped 52 -> 54.
haiyuan-eng-google pushed a commit that referenced this pull request May 12, 2026
…oncept-index lookup (#58 reader) (#154)

* feat(ontology): runtime reader — OntologyRuntime + EntityResolver + concept-index lookup (#58 reader)

Reader follow-on to PR #92's concept-index emission. Closes
the last feature dependency for issue #107's
four-guarantee notebook (the resolve beat).

Public surface in ``bigquery_agent_analytics``:

* OntologyRuntime — frozen dataclass; loads ontology +
  binding (from YAML files via from_files or in-memory via
  from_models) plus an optional ConceptIndexLookup wired to
  the emitted BigQuery table. Read-only accessors over
  entities / relationships / synonyms / annotations / SKOS
  schemes / notations / labels; provenance properties
  (compile_fingerprint / compile_id) computed locally via
  the same bigquery_ontology._fingerprint helpers PR #92's
  emission uses.

* EntityResolver Protocol + two reference impls:
  - ExactEntityResolver: in-memory match on entity_name,
    no BigQuery roundtrip; at most one candidate per query.
  - LabelSynonymResolver: BQ-backed match against
    concept-index label / synonym / notation rows; re-ranks
    candidates by label-kind priority
    (name > pref > alt > hidden > synonym > notation).

  NO embedding / LLM / fuzzy in this slice — explicit
  non-goals; future PRs can implement the Protocol without
  touching the runtime surface.

* ConceptIndexLookup — BigQuery-backed accessor that is
  fingerprint-strict. Three trust points:
  1. Eager verify() at construction. The runtime computes
     expected_fp = compile_fingerprint(fingerprint_model(
     ontology), fingerprint_model(binding), compiler_version)
     locally and compares against the table's __meta row.
     Mismatch raises FingerprintMismatchError before
     from_files / from_models returns.
  2. Public verify() method for explicit re-checks before
     long batches.
  3. Per-query "WHERE compile_fingerprint = @expected_fp"
     defense in depth. Even if the table is swapped or
     partially corrupted between verify and query, stale
     rows can't surface in the result.

  Three lookup methods: lookup_by_label (with label_kind /
  language / case_insensitive filters), lookup_by_entity_name,
  lookup_by_notation. Returns ConceptIndexRowView dataclass
  matching PR #92's main-table schema 1:1.

Stable failure codes — all subclass ConceptIndexError:
* FingerprintMismatchError — __meta row's compile_fingerprint
  differs from locally-computed value.
* MetaTableMissingError — __meta sibling table doesn't
  exist / query failed.
* MetaTableEmptyError — __meta exists but zero rows
  (PR #92 always writes exactly one).

Same trust discipline as Phase C compiled extractors —
stale provenance never produces a confident match.

Tests:

* tests/test_ontology_runtime.py: 39 CI cases using
  in-memory fake BQ clients. Layered coverage:
  TestOntologyRuntimeConstruction (5), TestOntologyRuntimeAccessors
  (10), TestConceptIndexLookupVerify (4), TestConceptIndexLookupQueries
  (8), TestExactEntityResolver (5), TestLabelSynonymResolver
  (5), TestEntityResolverProtocol (2).

* tests/test_ontology_runtime_live.py: gated behind
  BQAA_RUN_LIVE_TESTS=1 + BQAA_RUN_LIVE_ONTOLOGY_RUNTIME_TESTS=1
  + PROJECT_ID + DATASET_ID. Compiles a tiny ontology to
  concept-index SQL via PR #92's emission path, executes
  the DDL to create real BQ tables, attaches the runtime,
  runs LabelSynonymResolver + lookup_by_notation, asserts
  every candidate carries the runtime's compile_fingerprint,
  drops the tables on the way out.

Docs: docs/ontology_runtime_reader.md describes the
contract, trust gates, failure codes, public API. CHANGELOG
+ docs/README.md index entries added.

* fix(ontology-runtime): 5 reviewer findings + live BQ validation

Addresses PR #154 round-1 reviewer findings.

P1 #1 — table_id injection guard. ConceptIndexLookup.__init__
used to interpolate table_id directly into backtick-quoted SQL
in verify() and _run_lookup() without shape validation. New
_TABLE_ID_PATTERN regex (same discipline as
BigQueryBundleStore from Phase C): exactly three ASCII
segments, [A-Za-z0-9_-]+, fullmatch (not match — trailing
newline rejected). Backtick, semicolon, whitespace, comment
markers, wrong dot count, and non-string all raise ValueError
at construction. Validation flows through
OntologyRuntime.from_models so callers who never construct
ConceptIndexLookup directly still get the protection.

P1 #2 — drop unsafe singular relationship(name) accessor; add
traversal helpers. Per #58's traversal-first contract
(entity_resolution_primitives.md:118), relationship names are
NOT unique once #62's relaxed (name, from, to) uniqueness
ships — traversal-style names like skos_broader legally
repeat across endpoint pairs. The singular
relationship(name) -> Relationship | None accessor would
silently return the first match and hide duplicates; dropped
entirely. New relationships_by_name(name) -> tuple[
Relationship, ...] returns every match. Plus four SKOS
traversal helpers the user asked for:

* in_scheme(scheme) -> tuple of entity names (forward map).
* broader(entity_name) -> direct skos:broader parents.
* narrower(entity_name) -> inverse (children that declare
  this as broader). Not transitive.
* related(entity_name) -> skos:related values (not
  auto-symmetrized).

Companion notations_for(entity_name) returns every notation
value (scalar or list), companion to notation_for which
returns only the first.

P2 #1 — verify() always re-queries. Dropped the _verified
cache flag. The docstring promised "re-check before long
batches" but the cached fast path made re-runs no-ops. Now
every verify() call hits BigQuery again so a table swap or
fingerprint update mid-flight is caught. Construction-time
eager verify still runs once; subsequent verify() calls all
re-query.

P2 #2 — reject multiple __meta rows. PR #92's emission writes
exactly one meta row per table; multiple rows indicate manual
tampering. verify() SQL now uses LIMIT 2 (not LIMIT 1) so a
multi-row case is detectable without a full scan; len(rows)
!= 1 fails closed with new MetaTableMultipleRowsError
(subclasses ConceptIndexError). The empty case still uses
MetaTableEmptyError; multi is a distinct error code so
callers can switch on the failure mode.

P2 #3 — labels_for() now emits skos:notation as
label_kind='notation', matching PR #92's six-kind vocabulary
(name / pref / alt / hidden / synonym / notation). The
previous omission meant a caller comparing in-memory labels
against emitted concept-index rows would see five kinds
locally vs six remotely.

Tests: 39 -> 50 cases. New TestRoundOneFindings (11 cases)
locks each finding with explicit reproducers:

* test_lookup_rejects_malformed_table_id — every injection
  pattern + valid form acceptance.
* test_runtime_propagates_table_id_validation — validation
  flows through OntologyRuntime factories.
* test_relationships_by_name_returns_every_match — builds
  duplicate-name relationships directly via the Pydantic
  models (load_ontology enforces pre-#62 uniqueness, so the
  test bypasses the YAML path).
* test_singular_relationship_accessor_is_dropped —
  hasattr(runtime, "relationship") is False.
* test_in_scheme_lists_member_entities,
  test_broader_narrower_related — traversal helpers.
* test_verify_always_re_queries — swappable fake client
  returning matching→mismatched fingerprints across calls;
  construction + two re-checks all hit BigQuery (3 calls
  total).
* test_multiple_meta_rows_fails_closed,
  test_verify_uses_limit_2_to_detect_multi_row — multi-row
  __meta path + LIMIT 2 SQL lock.
* test_labels_for_includes_notation,
  test_notations_for_returns_all_values — notation surfaces
  in labels_for; CA appears as BOTH 'synonym' (declared in
  synonyms:) AND 'notation' (declared in skos:notation),
  matching PR #92's multiplicity contract.

Live BQ validation: ran
tests/test_ontology_runtime_live.py against real BigQuery
(test-project-0728-467323 / adk_e2e_test) — the full
emit-DDL → create-tables → attach-runtime →
verify-fingerprint → run-resolver → notation-lookup →
drop-tables round-trip passes in ~15s. All 50 CI tests
pass; pyink + isort clean.

* fix(ontology-runtime): lookup_by_notation queries label-kind row + stale doc summaries

Addresses PR #154 round-2 reviewer findings.

P2 - lookup_by_notation() was querying the per-row notation
column (``WHERE notation = @notation``), but PR #92's
concept-index emission contract says:

* every declared notation value gets one
  ``label_kind='notation'`` row where ``label`` IS the
  notation, and
* the per-row ``notation`` column is only the per-entity
  *display token* — for multi-notation entities,
  ``_entity_notation()`` keeps only the lexicographically
  smallest value.

Result: ``lookup_by_notation("B")`` on an entity declaring
``skos:notation: ["A", "B"]`` used to miss the entity
entirely because the ``notation`` column held "A". Fix:
query ``WHERE label_kind = 'notation' AND label = @notation``
so all declared notations are reachable.

Tests: 50 -> 52.

* test_lookup_by_notation rewritten to match the new
  predicate (rows now carry label='CA', label_kind='notation').
* test_lookup_by_notation_finds_secondary_notations is the
  reviewer's reproducer: notation row with label='B' but
  the per-row notation column carrying 'A' — the entity is
  found via the new predicate.
* test_lookup_by_notation_sql_pins_label_predicate captures
  the SQL and asserts ``label = @notation`` is in the
  WHERE clause AND ``WHERE notation = @notation`` is not —
  prevents regression.

Live BQ validation: bumped the live test fixture to declare
two notations (skos:notation: ["CA", "ZZ-LATE"]) and added a
lookup for the secondary value. Locks the round-1 P2 fix
against real BigQuery, not just the in-memory fake:

* lookup_by_notation("CA") finds the entity (primary,
  lex-min).
* lookup_by_notation("ZZ-LATE") ALSO finds the entity even
  though the per-row notation column is "CA" — the new
  predicate path is the only correct one.
* Round-trip passes end-to-end against
  test-project-0728-467323 in ~30s.

P3 - stale doc summaries:
* docs/README.md index entry now lists
  MetaTableMultipleRowsError alongside the other three
  stable failure codes, and calls out the round-1 fixes
  (table_id validation, always-requery verify, traversal
  helpers).
* CHANGELOG entry updated with MetaTableMultipleRowsError
  in the failure-codes list and bumped from "39 cases" to
  "52 cases."
* docs/ontology_runtime_reader.md test-section bumped from
  50 -> 52, TestConceptIndexLookupQueries count from 8 -> 10
  with the notation-predicate semantics spelled out, live
  test description updated to mention the multi-notation
  fixture.

* fix(ontology-runtime): notation_for returns lex-min display token, not first-authored

Addresses PR #154 round-3 P2 reviewer finding.

P2 - notation_for() returned the first authored skos:notation
list value, but PR #92's emitter uses min(values) for the
per-row notation display column (see
bigquery_ontology.concept_index._entity_notation). The two
views disagreed when notations were declared in non-sorted
order: an entity with skos:notation: ["B", "A"] would have
ExactEntityResolver report "B" while concept-index-backed
rows reported "A". The reader runtime and the concept-index
table must agree on the same display token.

Fix: notation_for(entity_name) now returns min(notations_for(
entity_name)) so the runtime view matches the emission's
lex-min rule. notations_for() still preserves declaration
order — callers needing every authored value (e.g. to feed
ConceptIndexLookup.lookup_by_notation) keep their option.

Tests: 52 -> 54.

* test_notation_for_returns_lex_min_display_token: entity
  declaring skos:notation: ["B", "A", "C"] returns "A" from
  notation_for() (lex-min, not first-authored "B").
* test_exact_resolver_uses_lex_min_notation: end-to-end lock
  via ExactEntityResolver — candidate.notation == lex-min
  so the two resolver paths agree on the same entity's
  notation.

Live BQ validation: bumped the live fixture from
skos:notation: ["CA", "ZZ-LATE"] (already sorted, where lex-
min == first-authored "CA") to ["ZZ-LATE", "CA"] (first-
authored "ZZ-LATE", lex-min "CA"). The live test now asserts
runtime.notation_for("CaliforniaRegion") == "CA" against
real BigQuery — locking both the round-2 multi-notation
lookup AND the round-3 lex-min display-token rule.
Round-trip passes against test-project-0728-467323 in ~16s.

Docs:
* ontology_runtime_reader.md: notation_for table row
  describes the lex-min rule, test list bumped to 54 with
  the new regression spelled out.
* CHANGELOG: CI case count bumped 52 -> 54.

* fix(ontology-runtime): ExactEntityResolver honors limit=0 + refresh stale live-fixture doc

Addresses PR #154 round-4 P3 reviewer findings.

P3 #1 - ExactEntityResolver.resolve() accepted ``limit`` for
Protocol symmetry but ignored it — always returned one
candidate for a match regardless of cap. LabelSynonymResolver
honored ``limit=0`` via the BQ slice. Now both Protocol
implementations agree: ``limit <= 0`` returns ``[]`` so
callers can disable a resolver branch by passing ``limit=0``
regardless of which implementation they hold.

* test_limit_zero_returns_empty: limit=0 + limit=-1 both
  return []; limit=1 still returns the one match.

P3 #2 - docs/ontology_runtime_reader.md live-test description
still said ``["CA", "ZZ-LATE"]``, but the actual round-3 live
test reversed the list to ``["ZZ-LATE", "CA"]`` so
first-authored ≠ lex-min and the lex-min display-token rule
is provably load-bearing. Doc now spells out the non-sorted
order, lists all three live assertions (primary + secondary
notation lookups plus the lex-min notation_for check), and
the proof shape stays obvious to readers.

CI suite bumped 54 -> 55 in both docs/ontology_runtime_reader.md
and CHANGELOG.md. TestExactEntityResolver entry bumped 5 -> 6
with the limit=0 case documented.
caohy1988 added a commit to caohy1988/BQAA-SDK-fork that referenced this pull request May 14, 2026
…oogleCloudPlatform#58)

Pass 5: replace Section 4 placeholder. Also adds inheritance
stripping to ``mako_artifacts.py`` so the binding compiles
through ``gm compile`` cleanly.

Fixture change: ``_strip_inheritance`` post-processor

The MAKO TTL declares ``mako:Candidate rdfs:subClassOf
mako:RoleTrait``; the OWL importer surfaces it as
``Candidate.extends: RoleTrait``. ``gm compile`` v0
doesn't support inheritance and rejects the binding with
``compile-validation — Entity 'Candidate' uses 'extends'``,
which blocks Section 4's ``--emit-concept-index`` step.

``RoleTrait`` is a marker class in MAKO (REQ-ONT-022,
"single-primary-parent inheritance discipline") with no
properties beyond the ``id`` PK every other entity already
carries. ``_strip_inheritance`` drops ``extends`` from the
post-import YAML, adds the ``id`` PK Candidate inherited
from RoleTrait, and records the discard under
``mako_demo:stripped_inheritance`` (per-entity flat string,
plus a comma-joined top-level summary — annotations are
typed ``dict[str, str]`` so the value can't be a list).

The check passes: 18 / 6 / 9 counts unchanged, both
``gm validate`` invocations still clean, ``gm compile
--emit-concept-index`` now emits the property-graph DDL
+ the concept-index ``CREATE OR REPLACE TABLE`` pair.

Section 4 cells:

* 4.1 [md] Framing — user-typed → canonical via
  concept-index lookup. PR GoogleCloudPlatform#92 emission + GoogleCloudPlatform#58 reader.
  Notes that MAKO TTL ships no SKOS labels, so the demo
  resolves by entity name only; richer TTLs extend the
  same demo with no code changes.
* 4.2 [py] Run ``gm compile --emit-concept-index
  --concept-index-table <FQN>`` and print the two
  ``CREATE OR REPLACE TABLE`` statements (main + __meta)
  with their shared ``compile_fingerprint``.
* 4.3 [py] Apply the DDL to the scratch dataset, construct
  ``OntologyRuntime.from_files(..., concept_index_table=,
  bq_client=)``, wrap in ``LabelSynonymResolver``, resolve
  ``"DecisionExecution"``. Print each candidate's
  ``entity_name`` / ``matched_label_kind`` / ``compile_id``.
* 4.4 [py] GQL traversal scoped by the resolved entity:
  ``COUNT(*)`` over ``GRAPH_TABLE(... MATCH
  (n:{resolved_entity}) ...)`` plus a hub-shape
  ``(de:DecisionExecution)-[:partOfSession]->
  (s:AgentSession)`` sample so the resolver → graph wiring
  is visible. Guard-rail check on the resolved entity to
  ensure it's in the demo allowlist before f-stringing into
  the GQL label position.
* 4.5 [md] Closing.

All cells gate on ``FEATURES["concept_index_reader"]``.
haiyuan-eng-google pushed a commit that referenced this pull request May 14, 2026
…O notebook (#107 phase 1) (#155)

* feat(examples/migration_v5): fixtures foundation for the four-guarantee notebook

Phase 1 of issue #107: fixtures directory under
examples/migration_v5/ that the four-guarantee MAKO demo
notebook (landing in a follow-up commit) consumes.

Inputs from the user-authored side (the "what you actually
have to provide" floor — one ontology file):

* mako_core.ttl — the real MAKO ontology pulled from the
  reference gist (https://gist.github.com/haiyuan-eng-google/
  a69ff6282ebcc877f77f9aa4e3db1afd). Domain-agnostic
  decision semantics, agent coordination, outcome tracking
  per Yahoo Monetization Platform's design doc.

Generated / scaffolded artifacts (the SDK + plugin produce
these; the demo never asks the user to hand-author them):

* ontology.yaml — full 380-line auto-import via gm import-owl
  --include-namespace https://ontology.yahoo.com/mako/.
  Captures all 41 MAKO entities; the notebook displays this
  in Section 0 to show the realistic "import → resolve
  FILL_INs → curate" workflow.
* ontology_demo.yaml — hand-curated 5-entity demo subset
  (AgentSession, DecisionPoint, Candidate, SelectionOutcome,
  ContextSnapshot) with FILL_IN primary keys resolved to id
  per MAKO's "every artifact has a stable identifier"
  contract. Validates clean against gm validate. The other
  36 MAKO entities would scaffold the same way — narrowing
  keeps the notebook's four-guarantee story focused.
* binding.yaml — auto-scaffolded via gm scaffold --ontology
  ontology_demo.yaml --dataset migration_v5_demo --project
  test-project-0728-467323 --out scaffold/. Demonstrates
  the "one file in, two files out" minimum-input path the
  storyboard's Section 0.5 calls out.
* table_ddl.sql — companion to binding.yaml, also from gm
  scaffold.
* property_graph.sql — user-authored CREATE PROPERTY GRAPH
  for the demo subset. Beat 1's "you own the graph
  definition" evidence. Uses __DATASET__ placeholder for
  per-run dataset substitution.

Demo-specific Python fixtures (the notebook imports these):

* seed_events.py — deterministic seeded RNG generator
  producing 404 events across 50 sessions: each session
  contains 2-4 decision points; each decision evaluates
  3-5 candidates against a context snapshot and produces
  one outcome. Seeded RNG (_RANDOM_SEED = 20260512) so the
  notebook's outputs round-trip byte-identically across
  runs. Event shape mirrors the BQ AA plugin's payload so
  Beat 3 extractors see the same surface as production.
* reference_extractors.py — handwritten extractor for
  mako_decision events (1 DecisionPoint + 1
  SelectionOutcome + 1 ContextSnapshot reference + N
  Candidates + their edges per event), plus the exact
  EXTRACTORS / RESOLVED_GRAPH / SPEC module contract
  bqaa-revalidate-extractors requires. Mirrors the BKA
  decision pattern from
  bigquery_agent_analytics.structured_extraction.
* revalidation_thresholds.json — threshold gate values for
  bqaa-revalidate-extractors --thresholds-json: 95%
  compiled_unchanged_rate, 99% parity_match_rate, etc.

Validation done in this commit:

* gm validate examples/migration_v5/ontology_demo.yaml →
  clean.
* gm validate examples/migration_v5/binding.yaml --ontology
  examples/migration_v5/ontology_demo.yaml → clean.
* seed_events.py generates 404 events across 50 sessions
  (50 session-start + 50 session-end + 152 context + 152
  decision events).
* reference_extractors.extract_mako_decision_event() on the
  first seeded decision produces 8 nodes (1 DecisionPoint +
  1 Outcome + 1 Context + 5 Candidates) and 7 edges.

Next commit lands the notebook itself.

* docs(examples/migration_v5): README for the fixture foundation

Surface the design decisions baked into the fixtures so the
fixture-shape review can happen before the notebook PR.
Per-decision rationale on: 5-entity MAKO subset, id-as-primary-key
strategy, NON-sorted skos:notation on DecisionPoint (exercises the
round-3 lex-min display-token rule end-to-end), seeded event shape
+ per-beat coverage check, reference extractor scope. Lists the
four validation commands already run + their pass status.

* refactor(examples/migration_v5): TTL-only authored input + mako_agent.py

Addresses PR #155 round-1 reviewer findings.

The previous fixture shape conflated "demo configuration"
with "ontology curation": ontology_demo.yaml was a
hand-curated subset, seed_events.py hardcoded event types
and demo-only fields not present in MAKO, property_graph.sql
used semantic edge columns inconsistent with the scaffolded
binding's from_id/to_id defaults, and project/dataset were
baked into checked-in artifacts.

Revised contract: exactly TWO files in examples/migration_v5/
are user-authored inputs. Everything else is a generator
output.

Authored inputs:
* mako_core.ttl — the real MAKO ontology.
* mako_agent.py — the only authored Python. Loads the TTL,
  resolves FILL_IN primary keys to synthesized id: string
  (matches MAKO's "every artifact has a stable identifier"
  design contract), drops cross-namespace dangling
  relationships (e.g. delegatedTo → prov:Agent — MAKO
  extends PROV-O but the demo doesn't model the external
  namespaces; dropped relationships are recorded in the
  ontology's annotations under
  mako_demo:dropped_cross_namespace_relationships so the
  loss is auditable). Generates binding for any
  (project, dataset) pair, derives table DDL +
  property-graph SQL from the binding (edge columns are
  consistent across both — no more from_id vs session_id
  mismatch), and emits a deterministic event stream whose
  payloads carry ONLY MAKO-declared data properties.

Generated artifacts (reproducibility snapshots produced by
mako_agent.regenerate_snapshots):
* ontology.yaml — gm import-owl output with FILL_INs
  resolved, dangling relationships dropped.
* binding.yaml — derived from the ontology for the demo
  entity set.
* table_ddl.sql — derived from the binding.
* property_graph.sql — derived from the binding. Edge
  columns match table_ddl.sql.
* events.jsonl — 398 deterministic events across 50
  sessions.

Demo entity set bumped from 5 → 6: DecisionExecution is
MAKO's central hub (partOfSession an AgentSession,
atContextSnapshot a ContextSnapshot,
executedAtDecisionPoint a DecisionPoint,
hasSelectionOutcome a SelectionOutcome). The decision-flow
story doesn't hold together without it.

Edge set is now fully TTL-driven: the agent walks
ontology.relationships and picks every relationship whose
endpoints both fall within DEMO_ENTITIES. No hardcoded edge
list. Picks up 9 relationships from MAKO without any name
authoring (atContextSnapshot, evaluatesCandidate,
executedAtDecisionPoint, hasSelectionOutcome, partOfSession,
rejectedCandidate, selectedCandidate, plus two others).

Event payload contract: MAKO models domain entities; the
BQ AA plugin telemetry envelope wraps each event with
event_type / session_id / span_id / event_timestamp /
content. The content dict carries only MAKO-declared data
properties (AgentSession.sessionId, DecisionExecution
.businessEntityId / latencyMs / spanId / traceId,
DecisionPoint.reversibility, ContextSnapshot.snapshotPayload
/ snapshotTimestamp) plus foreign-key references. No
demo-only invented fields.

Validation done:
* gm validate ontology.yaml → clean.
* gm validate binding.yaml --ontology ontology.yaml → clean.
* mako_agent.py end-to-end: {"ontology_entities": 18,
  "binding_entities": 6, "binding_relationships": 9,
  "events": 398}.

README rewritten to document the authorship boundary
explicitly and call out each design choice with the
rejected alternative spelled out.

* refactor(examples/migration_v5): split artifacts vs runnable plugin-instrumented agent

Addresses PR #155 round-2 product clarification (#155 comment
4437670647). Previous shape had mako_agent.py double as
TTL→artifacts AND event generator, which silently bypassed the
BQ AA plugin's event-emission contract. New shape pins the
contract: the demo's event source of truth is a runnable agent
talking to BigQueryAgentAnalyticsPlugin, not a Python fixture.

Authored inputs (now five files, all in this directory):

* mako_core.ttl — unchanged. The real MAKO ontology.
* mako_artifacts.py — renamed from mako_agent.py; stripped of
  TelemetryEvent / generate_events / events_as_jsonl. Pure
  TTL→ontology / binding / DDL / property-graph pipeline.
  Does NOT generate events.
* mako_demo_agent.py — new. Runnable ADK Agent with five MAKO
  decision-flow tools (capture_context,
  propose_decision_point, evaluate_candidate, commit_outcome,
  complete_execution) and BigQueryAgentAnalyticsPlugin
  wiring. Same pattern as
  examples/decision_lineage_demo/agent/agent.py. Uses Vertex
  AI Gemini (default gemini-2.5-flash).
* run_agent.py — new. Driver. `python run_agent.py --sessions
  50 --project X --dataset Y` runs the agent for N sessions
  and the plugin populates agent_events as a side effect.
  Each prompt asks the agent to walk through one full MAKO
  decision flow; the plugin captures the LLM_RESPONSE rows +
  TOOL_* rows that downstream analytics consume.
* export_events_jsonl.py — new. Optional. Exports a pinned
  subset of agent_events to a local JSONL snapshot for the
  notebook's deterministic offline revalidation tests. NOT an
  event generator — reads from BigQuery.

Generated artifacts (reproducibility snapshots; regenerable
via `python mako_artifacts.py --project X --dataset Y`):

* ontology.yaml, binding.yaml, table_ddl.sql,
  property_graph.sql

Removed:
* events.jsonl — was a fixture-script output; the new shape
  makes this a captured BQ snapshot only.
* TelemetryEvent class + generate_events function from the
  artifact module. Events now come from the plugin, not a
  fixture.

Validation done in this commit:
* PYTHONPATH=src python mako_artifacts.py → 18 ontology
  entities, 6 binding entities, 9 relationships.
* PYTHONPATH=src python -m bigquery_ontology.cli validate
  ontology.yaml → clean.
* PYTHONPATH=src python -m bigquery_ontology.cli validate
  binding.yaml --ontology ontology.yaml → clean.
* mako_demo_agent imports cleanly: LlmAgent + 5 tools +
  BigQueryAgentAnalyticsPlugin attached.
* run_agent.py --help works without live BQ / Vertex.

NOT done in this commit (next step on the same branch):
* Live end-to-end run of run_agent.py against the demo's
  Vertex AI + BigQuery dataset. This is the notebook's job
  in Beat 0; landing it as a separate commit after this
  fixture shape is signed off.
* The notebook itself.

README rewritten to spell out the authorship boundary
explicitly and document each design decision with the
rejected alternative spelled out.

* fix(examples/migration_v5): self-edge dup columns + property-type DDL + trace mapping

Round-3 fixes for PR #155 review:

* P1 — self-referential edges generated duplicate columns.
  ``evolvedFrom`` / ``supersededBy`` are
  DecisionExecution → DecisionExecution self-edges; naming
  both endpoints ``decision_execution_id`` produced
  ``CREATE TABLE foo (decision_execution_id STRING,
  decision_execution_id STRING)``. ``make_binding`` now
  switches to ``src_{base}_id`` / ``dst_{base}_id`` only
  for self-edges; heterogeneous edges keep the simpler
  naming. Property graph SQL stays in sync because it reads
  ``from_columns`` / ``to_columns`` from the same binding.

* P1 — table DDL ignored ontology property types. Every
  column was ``STRING`` (plus a hacky ``*Timestamp``
  suffix), silently dropping the typing the TTL declared
  (e.g. ``DecisionExecution.latencyMs`` is ``xsd:integer``,
  but landed as STRING). ``make_table_ddl`` now takes the
  ontology, builds an ``(entity, prop) → BQ type`` map via
  the new ``_bq_type_for`` helper, and emits real BQ types.
  ``latency_ms`` is now ``INT64`` in ``table_ddl.sql``.

* README — added explicit "trace → MAKO mapping" contract.
  The agent uses realistic snake_case tool names (e.g.
  ``decision_point_id``, ``snapshot_payload``,
  ``business_entity_id``) rather than TTL-camelCase. The
  README now spells out which trace fields become
  TTL-declared properties at extraction time and which are
  trace-only (e.g. ``rationale``, ``candidate_label``).

* fix(examples/migration_v5): DDL metadata cols, plugin schema, ident validation

Round-4 fixes for PR #155 review:

* P1 — table DDL now includes the SDK metadata columns that
  binding-validate requires on every bound table. The
  materializer (``ontology_materializer._entity_columns`` /
  ``_relationship_columns``) writes ``session_id STRING`` +
  ``extracted_at TIMESTAMP`` on every ``materialize()``
  call, and ``binding_validation.py`` (lines 488, 806)
  enforces both columns. Without them, the notebook's
  binding-validate step would fail before ontology-build.
  ``make_table_ddl`` now appends both, deduping against any
  domain property that already maps to the same column
  (MAKO's ``AgentSession.sessionId → session_id`` is the
  canonical collision case).

* P1 — ``export_events_jsonl.py`` now targets the BQ AA
  plugin's real schema. The previous SELECT projected
  ``event_id``, ``agent_name``, ``payload``, ``content``,
  ``event_timestamp``, ``partition_date`` — none of which
  exist on the plugin's table. The plugin emits
  ``timestamp``, ``event_type``, ``agent``, ``session_id``,
  ``invocation_id``, ``user_id``, ``trace_id``, ``span_id``,
  ``parent_span_id``, plus JSON ``content`` / ``attributes``
  / ``latency_ms`` (verified by reading
  ``_get_events_schema`` in
  ``bigquery_agent_analytics_plugin.py``). Partitioning is
  on ``timestamp`` (DAY), not a separate column. Ordering
  is now ``ORDER BY timestamp, span_id`` since there is no
  ``event_id``.

* P2 — ``export_events_jsonl.py`` validates each segment of
  ``--project / --dataset / --table`` against
  ``[A-Za-z0-9_-]+`` (same character class
  ``bq_bundle_mirror._TABLE_ID_PATTERN`` uses) before
  interpolating into the ``FROM`` clause. BigQuery
  identifiers can't be passed as query parameters; this
  check rejects whitespace, backticks, semicolons, dots,
  and any character outside the BQ-permitted set per
  segment.

README updated with two new design-decisions sections:
events.jsonl is captured from the real plugin schema, and
the DDL carries SDK metadata columns.

* docs(examples/migration_v5): node_id convention + soften exporter docstring

Round-5 doc-only follow-ups from PR #155 review:

* P2 — pin the reference-extractor node_id convention in
  README. The materializer
  (``ontology_materializer._build_edge_row`` line 322)
  derives edge FK column values by *parsing endpoint
  node_ids*, not by reading node properties. A node_id like
  ``sess:DecisionExecution:id=exec-1`` will not populate an
  ``decision_execution_id`` FK column ---- whatever keys
  the binding declares for FKs are the keys the extractor
  must encode in the node_id. This is a silent-failure
  trap (extractor "runs", edges get empty-string FKs) and
  is especially subtle for self-edges where the same node
  needs ``src_*`` / ``dst_*`` keys too. Documented the
  convention with a worked DecisionExecution example so
  the notebook + reference extractor (follow-up commit)
  can centralize the encoding in a ``node_id_for(...)``
  helper.

* P3 — soften the exporter docstring. The selected
  columns are a *subset* of the plugin schema, not the
  full schema: ``content_parts`` (REPEATED RECORD for
  multimodal parts) is omitted because the MAKO decision
  flow is text-only. Docstring now says "selected columns
  from the plugin schema" and points to the one-line
  change needed if a future demo needs multimodal trace
  replay.

* docs(examples/migration_v5): README parity with round-5 doc fixes

Two stale phrasings in README missed by the previous
commit:

* ``_build_edge_row`` doesn't exist; the function is
  ``_route_edge`` (``ontology_materializer.py:314``).
  Behavior described was already correct, only the symbol
  name was wrong.

* "Mirrors the BQ AA plugin's real schema" overstates what
  the exporter does ---- ``content_parts`` (REPEATED
  RECORD) is omitted because the MAKO demo is text-only.
  README now matches the exporter docstring: "projects the
  subset of the plugin schema the notebook needs", with
  the one-line change for multimodal replay.

* docs(examples): replace migration notebook with four-guarantee scaffold (#107)

First pass for #107: replace the ontology-migration notebook content
with the four-guarantee storyboard scaffold.

Section 0 fully written (no live BQ required to parse):

* License header + title + four-guarantee narrative table.
* "What you need to bring" — minimum-input answer: one
  ontology file. Three input shapes side by side.
* Install + auth + scratch dataset + ``FEATURES`` flags
  for per-beat gating (#58/#75/#76/#104/#105).
* TTL → ontology / binding / DDL via
  ``mako_artifacts.regenerate_snapshots(project, dataset)``.
* Apply ``table_ddl.sql`` against the scratch dataset.
* Run the real ADK Gemini agent via ``run_agent.py
  --sessions N``; the BQ AA plugin populates
  ``agent_events`` as a side effect.
* Sanity-check counts by event_type.

Sections 1-4 are section-header markdown placeholders; the
beat-specific cells (Own / Validate / Extract cheaply /
Resolve) land in passes 2-5. Section 5 (close) is fully
written so the storyboard's recap is in place.

The notebook validates against nbformat 4.5 (verified via
``nbformat.validate``) and the code cells parse as valid
Python (verified via ``ast.parse`` after stripping the
``!pip`` magic).

Live execution against ``test-project-0728-467323``
follows as a separate commit once Sections 1-4 are filled
in.

* fix(examples/migration_v5): live-run readiness nits from round-6 review

Four small fixes uncovered when the notebook scaffold put
``run_agent.py`` on the live path:

* P2 — agent SYSTEM_PROMPT step 5 now lists all four
  arguments ``complete_execution`` requires
  (``decision_point_id``, ``context_id``, ``outcome_id``,
  ``business_entity_id``). Gemini can infer from the
  function schema, but the instruction was weaker than the
  tool signature, which risks degraded event quality on
  the live run.

* P3 — notebook cell 13 now passes ``env={**os.environ,
  "DEMO_AGENT_LOCATION": AGENT_LOCATION, ...}`` to
  ``subprocess.run`` so a notebook-variable override of
  ``AGENT_LOCATION`` / ``PROJECT_ID`` / ``DATASET_ID``
  actually reaches the child process. Without this, the
  displayed value diverges from what the agent module
  picks up at import time.

* P3 — feature-flag wording updated. All underlying issues
  have shipped; the gates are runtime/cost knobs now ("flip
  False to skip live, expensive, or environment-specific
  beats"), not dependency gates.

* P3 — the PR claim "code cells parse via ``ast.parse``"
  needed qualification since the ``!pip`` install cell is
  valid IPython but not valid Python. The verification
  script now explicitly skips shell-magic cells before
  ``ast.parse``.

* docs(examples): notebook Section 1 — Beat 1, "you own the graph" (#104)

Pass 2: replace the Section 1 placeholder with the live
"own the graph" beat. Cells 1.1-1.6:

* 1.1 [md] Framing — before #104 every build ran
  ``CREATE OR REPLACE PROPERTY GRAPH``; after, the SDK
  populates base tables and leaves the user's graph DDL
  alone.
* 1.2 [py] Apply ``examples/migration_v5/property_graph.sql``
  to the scratch dataset.
* 1.3 [py] Capture ``before_skip_build_ts`` *after* the
  user's DDL finishes; baseline a GQL traversal so we have
  a row-count reference for cell 1.5.
* 1.4 [py] Discover ``session_ids`` from ``agent_events``;
  run ``bq-agent-sdk ontology-build --skip-property-graph
  --ontology --binding --session-ids --location``. Print
  the build's ``property_graph_status`` so the skipped
  state is visible.
* 1.5 [py] Two-pronged evidence:
  - (a) ``INFORMATION_SCHEMA.JOBS_BY_PROJECT`` filtered by
    ``creation_time > @before_ts`` + dataset-name pattern
    + ``REGEXP_CONTAINS(UPPER(query),
    r'CREATE\s+(OR\s+REPLACE\s+)?PROPERTY\s+GRAPH')``.
    Combining the timestamp filter (so the user's own
    cell-1.2 DDL is excluded) with the regex catches the
    SDK-issued spelling.
  - (b) Re-run the GQL traversal; assert the count is
    ``>= before_skip_build_rows`` (the graph object is
    intact and now has populated base tables).
* 1.6 [md] Beat 1 closing.

All cells gate on ``FEATURES["skip_property_graph"]``;
flipped off they print "Skipped: skip_property_graph
feature off" rather than failing.

Used ``rf"""`` for the JOBS_BY_PROJECT SQL so the regex
literal ``r'CREATE\s+...'`` doesn't trigger
Python 3.12+'s SyntaxWarning on the ``\s`` escape.

* fix(examples): Section 1 verify-cell parity with live #104 regression test

Three findings from review of pass 2 (Section 1):

* P1 — JOBS_BY_PROJECT filter now mirrors the live #104
  integration test
  (``tests/test_integration_ontology_binding.py``):
  ``query LIKE '%mako_demo_graph%' AND EXISTS (SELECT 1
  FROM UNNEST(j.labels) AS l WHERE l.key='sdk_feature'
  AND l.value='ontology-gql')``. The previous
  ``query LIKE '%{DATASET_ID}%'`` filter was too narrow —
  a regressed SDK can target the orchestrator dataset
  rather than the binding's dataset in split setups, and
  the regression would slip past a dataset-pattern check.
  Filtering by graph name + SDK feature label catches the
  regression regardless of which dataset the build wrote
  into. The post-DDL timestamp filter still excludes the
  user's own authored DDL from cell 1.2 (which also
  carries the ontology-gql label).

* P2 — Cell 1.4 now asserts ``build_result["property_graph_status"]
  == "skipped:user_requested"`` immediately after parsing
  the CLI stdout. A regression that returned success but a
  different (or absent) status would otherwise silently
  pass the JOBS_BY_PROJECT check too.

* P3 — Cell 1.5 now asserts ``total_rows > 0`` (sum of
  ``build_result["rows_materialized"]``). The previous
  GQL ``after >= before`` check trivially passed when
  both counts were zero, so an empty-graph regression
  would slip through. The build's own materialization
  count is the authoritative answer to "did extraction
  produce data?"

* docs(examples): notebook Section 2 — Beat 2, pre-flight binding-validate (#105)

Pass 3: replace the Section 2 placeholder with the live
"validate" beat. Also fixed a small wording nit in cell 1.5
markdown (no longer says "against the scratch dataset",
since the JOBS_BY_PROJECT filter is now graph-name + SDK-
label scoped, not dataset-scoped).

Section 2 cells:

* 2.1 [md] Framing — pre-flight catches drift in under a
  second; exit code 1 short-circuits before AI.GENERATE
  fires.
* 2.2 [py] Inject column-rename drift:
  ``ALTER TABLE context_snapshot RENAME COLUMN
  snapshot_payload TO snapshot_payload_v2``. Print the
  table's columns before + after so the drift is visible.
* 2.3 [py] Run ``binding-validate --format json``.
  Assertions: exit code 1, at least one ``MISSING_COLUMN``
  failure on ``context_snapshot.snapshot_payload``. Print
  each failure with ``binding_path`` + ``bq_ref`` (the
  fields that point at the exact authoring site).
* 2.4 [py] Restore the column name and re-run. Assertions:
  exit code 0, ``report.ok is True``.
* 2.5 [py] Combine Beat 1 + Beat 2 in one invocation:
  ``ontology-build --skip-property-graph --validate-binding``.
  Assertions: ``property_graph_status =
  'skipped:user_requested'`` AND ``rows_materialized
  total > 0`` (the build's authoritative
  did-extraction-produce-data answer).
* 2.6 [md] Closing.

All cells gate on ``FEATURES["binding_validate"]``; cell
2.5 also requires ``skip_property_graph``. Gated off,
cells print "Skipped: ..." rather than failing.

Cell 1.5 markdown reworded: "jobs targeting
``mako_demo_graph`` and carrying the SDK's
``sdk_feature='ontology-gql'`` label, with
``creation_time > before_skip_build_ts``". The code does
not filter by dataset name; the markdown now matches.

* fix(examples): Section 2 round-8 — JSON code casing + idempotent restore

Three findings from review of pass 3 (Section 2):

* P1 — Cell 2.3 was checking ``f["code"] == "MISSING_COLUMN"``,
  but the CLI emits ``f.code.value`` from the
  ``FailureCode`` enum, whose values are lowercase
  (``"missing_column"``). The Python enum *names* are
  uppercase but the JSON values aren't — easy to miss
  without reading the CLI source. Cell 2.3 now checks
  ``"missing_column"`` and the 2.3 framing markdown calls
  out the casing convention explicitly.

* P2 — Cell 2.2 mutates the live table; if anything between
  it and cell 2.4 asserts, the column stays renamed and
  the rest of the notebook breaks. Cell 2.3 was the most
  likely culprit (it asserts on the validator output).
  Two compounding fixes:
  - Cell 2.3 now prints all structured output *before*
    asserting, so the report shape is visible even when an
    assertion raises.
  - Cell 2.4's restore is now idempotent — it reads the
    current schema and renames-or-noops based on which
    column exists, so the user can re-run cell 2.4 by
    itself after a cell-2.3 failure and get back to the
    binding-expected shape.

* P3 — Cell 2.3 markdown said paths look like
  ``entities.ContextSnapshot.properties.snapshotPayload.column``,
  but the validator emits indexed paths
  (``binding.entities[2].properties[1].column``). The
  notebook prints ``binding_path``, so the framing now
  matches the real shape with a one-line callout about
  the name-keyed fallback for the unresolved-spec case.

* docs(examples): notebook Section 3 — Beat 3 cost + validate (#75 + #76)

Pass 4: replace Section 3 placeholder. Cell 2.4 also
hardened against kernel-restart loss of ``rename_to`` /
``validate_cmd``.

Section 3 cells:

* 3.1 [md] Framing — session-aggregated AI.GENERATE is the
  cost driver; compiled extractors handle structured spans,
  AI handles narrative spans; validation-gated prune
  determines transcript composition. Table maps C1 / C2
  sub-phases to cells.
* 3.2 [py] Live baseline: per-session transcript size from
  ``agent_events`` (``LENGTH(TO_JSON_STRING(content))``
  per row, summed per session). Estimate uses
  4-chars-per-token; honest about being a prompt-size
  estimate, not billing usage. Per-event token attribution
  isn't available from current architecture; the **session**
  is the cost unit.
* 3.3 [py] / 3.4 [py] / 3.5 [py] / 3.7 [py] — gated
  placeholders. The cells need
  ``examples/migration_v5/reference_extractor.py`` (a
  MAKO-specific reference extractor analogous to the
  shipped ``extract_bka_decision_event``). PR #155 is
  fixtures-only; the reference extractor + the live
  measurement / runtime / savings cells land in PR #156.
  Each placeholder documents the future-PR shape so the
  follow-up author has a target.
* 3.6 [py] **Live** ``ValidationReport`` demo against
  synthetic ``ExtractedGraph`` fixtures. NODE / FIELD /
  EDGE scopes all fire as expected (verified locally
  against ``mako_artifacts``-generated ontology +
  binding); each scope is asserted so a regression in
  ``graph_validation.py`` scope classification would
  catch here.
* 3.8 [md] Beat 3 status — what's live vs what waits on
  PR #156.

The cell-2.4 harden: ``rename_to`` defaults to
``"snapshot_payload_v2"`` if not already in ``locals()``,
and ``validate_cmd`` is rebuilt locally if missing. So
restart-and-rerun-from-cell-2.4 works cleanly.

* fix(examples): Beat 3 baseline guard rails + Section 5 recap honesty

Two round-9 fixes:

* P2 — Cell 3.2 (baseline cost view) now uses
  ``SUM(COALESCE(LENGTH(TO_JSON_STRING(content)), 0))``
  so a row whose ``content`` is NULL doesn't NULL-out the
  session total (and crash the format string downstream).
  Adds two guard-rail assertions: ``baseline_rows`` must
  be non-empty and ``total_chars`` must be positive. A
  zero baseline would mean "Section 0 didn't actually
  populate ``agent_events``" — surface that as a hard
  failure rather than letting Beat 3 quietly claim a live
  baseline on an empty corpus.

* P2/P3 — Section 5's recap row for "Extract cheaply"
  said "Per-session token table shows the savings", but
  this PR only ships the *baseline* table; the
  compiled-savings *delta* is deferred to PR #156. Row
  now says "Cell 3.2 establishes the pre-compile
  baseline; the compiled-savings delta lands with PR #156"
  so the recap matches what's actually live.

* docs(examples): notebook Section 4 — Beat 4, concept-index resolver (#58)

Pass 5: replace Section 4 placeholder. Also adds inheritance
stripping to ``mako_artifacts.py`` so the binding compiles
through ``gm compile`` cleanly.

Fixture change: ``_strip_inheritance`` post-processor

The MAKO TTL declares ``mako:Candidate rdfs:subClassOf
mako:RoleTrait``; the OWL importer surfaces it as
``Candidate.extends: RoleTrait``. ``gm compile`` v0
doesn't support inheritance and rejects the binding with
``compile-validation — Entity 'Candidate' uses 'extends'``,
which blocks Section 4's ``--emit-concept-index`` step.

``RoleTrait`` is a marker class in MAKO (REQ-ONT-022,
"single-primary-parent inheritance discipline") with no
properties beyond the ``id`` PK every other entity already
carries. ``_strip_inheritance`` drops ``extends`` from the
post-import YAML, adds the ``id`` PK Candidate inherited
from RoleTrait, and records the discard under
``mako_demo:stripped_inheritance`` (per-entity flat string,
plus a comma-joined top-level summary — annotations are
typed ``dict[str, str]`` so the value can't be a list).

The check passes: 18 / 6 / 9 counts unchanged, both
``gm validate`` invocations still clean, ``gm compile
--emit-concept-index`` now emits the property-graph DDL
+ the concept-index ``CREATE OR REPLACE TABLE`` pair.

Section 4 cells:

* 4.1 [md] Framing — user-typed → canonical via
  concept-index lookup. PR #92 emission + #58 reader.
  Notes that MAKO TTL ships no SKOS labels, so the demo
  resolves by entity name only; richer TTLs extend the
  same demo with no code changes.
* 4.2 [py] Run ``gm compile --emit-concept-index
  --concept-index-table <FQN>`` and print the two
  ``CREATE OR REPLACE TABLE`` statements (main + __meta)
  with their shared ``compile_fingerprint``.
* 4.3 [py] Apply the DDL to the scratch dataset, construct
  ``OntologyRuntime.from_files(..., concept_index_table=,
  bq_client=)``, wrap in ``LabelSynonymResolver``, resolve
  ``"DecisionExecution"``. Print each candidate's
  ``entity_name`` / ``matched_label_kind`` / ``compile_id``.
* 4.4 [py] GQL traversal scoped by the resolved entity:
  ``COUNT(*)`` over ``GRAPH_TABLE(... MATCH
  (n:{resolved_entity}) ...)`` plus a hub-shape
  ``(de:DecisionExecution)-[:partOfSession]->
  (s:AgentSession)`` sample so the resolver → graph wiring
  is visible. Guard-rail check on the resolved entity to
  ensure it's in the demo allowlist before f-stringing into
  the GQL label position.
* 4.5 [md] Closing.

All cells gate on ``FEATURES["concept_index_reader"]``.

* fix(examples): Section 4 round-10 — compiler-version drift + non-zero asserts

Three findings from review of pass 5 (Section 4):

* P1 — Cell 4.3 hard-coded ``compiler_version=
  "bigquery_ontology 0.2.2"`` in ``OntologyRuntime.from_files``,
  but ``gm compile`` defaults to the installed package
  version (0.2.3 in the reviewer's env). The version
  string is part of the fingerprint hash, so the runtime
  trips ``FingerprintMismatchError`` the moment package
  versions don't line up. Fix: query
  ``{CONCEPT_INDEX_TABLE}__meta.compiler_version`` after
  applying the DDL and pass that value to
  ``from_files(...)``. Same source of truth the compiler
  emitted; no manually-pinned constant to drift.

* P2 — Cell 4.4 printed the GQL count and the hub-shape
  rows without ever asserting either was non-empty. A
  zero count or zero hub rows would still close the cell
  "successfully", making the demo's climax claim
  ("user-typed name routes to real graph data") an empty
  print. Added ``assert count > 0`` and
  ``hub_rows = list(...); assert hub_rows`` with messages
  that point at the likely Beat 1 root cause (empty
  materialization).

* P3 — Beat 4 closing markdown said "the user typed
  natural language; the SDK resolved it via the SKOS
  taxonomy the user authored once". Accurate for a
  SKOS-rich TTL; misleading for the MAKO fixture, which
  ships no labels and resolves only by canonical entity
  name. Reworded to explicitly call out that fact and
  describe the label-kind ranking
  (``name > pref > alt > synonym > notation``) that
  kicks in when richer rows are present.

* fix(examples): Section 4 P1 (actually) + label-kind ranking

Round-10 claimed to source ``compiler_version`` from the
``__meta`` table, but the patch never landed: an
AssertionError on a subsequent cell aborted the script
before the file write. The committed file still had
``compiler_version="bigquery_ontology 0.2.2"`` hard-coded,
which trips ``FingerprintMismatchError`` against any other
installed package version (0.2.3 in the reviewer's env).

Properly apply the fix this time. Cell 4.3 now:

* Queries
  ``SELECT compiler_version, compile_fingerprint FROM
  `{CONCEPT_INDEX_TABLE}__meta``` right after applying the
  DDL.
* Binds the result to ``COMPILER_VERSION`` and passes it
  to ``OntologyRuntime.from_files(...)``. The SDK's own
  ``__meta`` row is the source of truth — there's no
  manually-pinned constant to drift.
* Prints both ``compiler_version`` and
  ``compile_fingerprint`` so the audit trail is visible.

Also: Beat 4 closing markdown had ``name > pref > alt >
synonym > notation``, but the runtime priority
(``_LABEL_KIND_PRIORITY``) is ``name > pref > alt >
hidden > synonym > notation``. Added the missing
``hidden`` rung.

* docs(examples): Beat 4 wording consistent with what the fixture actually does

Two doc-only nits from round-11 review:

* Beat 4 prose in four sites still said the user types
  natural-language inputs like ``"Consumer Banking"`` and
  the resolver maps to canonical names like
  ``skos:RetailBanking``. The MAKO TTL ships no SKOS
  labels, so this fixture resolves canonical entity names
  (``DecisionExecution``), not natural-language. The
  intro table, Beat 4 framing, climax-query paragraph,
  and Section 5 recap row are now consistent: each calls
  out "canonical entity label in this fixture; richer
  ontologies use the same resolver path for
  ``skos:altLabel`` / ``skos:prefLabel`` /
  ``skos:notation`` rows."

* The 4.1 framing also listed ``label_kind`` candidates
  without ``hidden`` (Beat 4 closing already had it, the
  4.3 framing didn't). Added ``hidden`` so the three
  ``label_kind`` enumerations in the notebook match the
  runtime priority
  (``name > pref > alt > hidden > synonym > notation``).

* feat(examples): live notebook + fixture fixes for end-to-end run

Live end-to-end run against ``test-project-0728-467323``
(3 sessions, scratch dataset
``migration_v5_demo_7da57280``). All 59 cells passed.

Fixture changes that unblocked the live run:

* Entity PK columns are now per-entity rather than a bare
  ``id``. The materializer's
  ``_relationship_columns`` (``ontology_materializer.py``)
  looks up edge FK columns in
  ``src_prop_map[col].sdk_type`` — that lookup requires
  the FK column to *exactly* name a column on the source
  entity. With bare ``id``, every edge would land
  ``(id STRING, id STRING)`` (duplicate column) AND the
  materializer's FK→PK type lookup would still miss for
  cross-entity edges. Renaming PK columns to
  ``{entity_short}_id`` matches the convention the
  original V5 spec used (``decision_id``, ``adUnitId``,
  etc.) and the integration-test fixture
  (``tests/fixtures/test_binding.yaml``). Note the
  ``_entity_id_column`` helper no longer strips ``agent_``
  for AgentSession — that strip collided with
  ``AgentSession.sessionId``'s ``session_id`` column and
  the SDK metadata ``session_id``. AgentSession is now
  ``agent_session_id``.
* Self-edges are dropped (was 9 → 7 relationships). MAKO's
  ``evolvedFrom`` and ``supersededBy`` are
  ``DecisionExecution → DecisionExecution`` self-edges;
  the materializer's FK→PK lookup can't disambiguate them
  via ``src_/dst_`` prefixed columns and the natural
  composite-key pair is ``(decision_execution_id,
  decision_execution_id)`` — duplicate. The ontology still
  declares the edges; only the binding scope drops them.
* Property graph DDL: edge ``REFERENCES`` clauses use the
  node-table **alias** (``decision_execution`` not
  ``\`proj.ds.decision_execution\```) because BigQuery
  rejects qualified refs in
  ``CREATE PROPERTY GRAPH``. Node ``KEY (...)`` and edge
  ``REFERENCES alias (col)`` both use the per-entity PK
  column (``KEY (decision_execution_id)`` instead of
  ``KEY (id)``). Edge tables additionally need explicit
  ``KEY (src_col, dst_col)`` — BQ rejects without it.
* Inheritance: ``_strip_inheritance`` post-processor drops
  ``extends: RoleTrait`` from Candidate so ``gm compile``
  v0 accepts the binding (v0 doesn't support inheritance).

Notebook changes for the live path:

* Cell 1.4 + cell 2.5 subprocess calls now surface the
  child process's stderr on failure. Previous
  ``capture_output=True, check=True`` masked the error
  text from the notebook; the operator had to re-run the
  CLI by hand to see what failed.
* Cells 2.3 / 2.4 / 2.5 add a local ``import json``
  because cell 1.4 imports ``json as _json`` (aliased)
  which leaves the bare name ``json`` unbound for later
  cells.
* Cell 4.4 builds a ``_PK_COL`` map (entity → PK column)
  because the GQL ``COLUMNS`` clause needs the per-entity
  PK column name (``decision_execution_id`` etc.), not
  ``id`` which is now the property *logical* name only.
* Hub-shape traversal in Beat 4 now degrades gracefully
  to a "AgentSession synthesis is a PR #156 follow-up"
  note rather than asserting. The AI extraction in this
  demo doesn't synthesize ``AgentSession`` nodes /
  ``partOfSession`` edges from the plugin envelope; the
  follow-up will.

Live evidence captured in the executed notebook (now
committed with outputs):

  - Beat 1 verify: GQL count before=0, after=2; no
    SDK-issued CREATE OR REPLACE PROPERTY GRAPH job;
    rows_materialized total = 35;
    property_graph_status = 'skipped:user_requested'.
  - Beat 2: drift detected (exit 1, missing_column);
    restore + re-validate (exit 0, report.ok = True);
    combined build (exit 0, rows_materialized total = 35).
  - Beat 3.6: ``ValidationReport`` against synthetic
    ``ExtractedGraph`` — NODE + FIELD + EDGE scopes all
    fire as expected.
  - Beat 4: concept index materialized; resolver returns
    DecisionExecution with compile_id ``eca9978b0550``;
    GRAPH_TABLE count = 4 against the user-authored
    property graph.

Beat 3 compile / runtime / savings cells (3.3-3.5, 3.7)
remain PR #156 placeholders; their gates are still
documented as "requires MAKO reference extractor".

* docs(examples): post-live-run cleanup — install cell, README, copy

Four follow-up nits from review of the live-run capture:

* **install cell**: ``!pip install ... google-adk[vertexai] ...``
  failed under zsh with ``no matches found`` because zsh
  glob-expanded the ``[vertexai]`` extra. Switched to
  ``%pip install`` (Jupyter magic that bypasses shell
  expansion) and quoted the extra. Without the fix the
  install was silently a no-op and downstream cells ran
  against whatever was already in the kernel env —
  explaining the ``bigquery_ontology 0.2.2`` in the
  committed outputs vs. ``0.2.3`` in a fresh checkout.

* **Generated artifacts regenerated against the default
  ``(test-project-0728-467323, migration_v5_demo)`` pair**
  rather than the scratch dataset from the live run.
  Previous commit shipped ``binding.yaml`` /
  ``table_ddl.sql`` / ``property_graph.sql`` against the
  ephemeral ``migration_v5_demo_7da57280`` dataset, which
  is residue, not stable defaults. Reviewers can now ``cat``
  the artifacts and see the canonical target.

* **README**: substantial rewrite. Removed the "fixture
  only, notebook is future work" framing; added two new
  design-decision sections (8: per-entity PK columns, 9:
  self-edges dropped, 10: inheritance stripped); updated
  the relationship count (9 → 7); corrected the FK column
  description (was "AgentSession FK is ``session_id``"
  via ``_entity_id_column`` stripping ``agent_`` — now
  ``agent_session_id`` since the strip was removed in the
  live-run reconciliation); removed the obsolete
  self-edge node_id encoding section (self-edges are now
  dropped); added a "What's NOT in this commit" pointing
  at PR #156's ``AgentSession`` synthesis follow-up.

* **Notebook framing**: corrected "nine real MAKO
  relationships" → "seven" so the framing matches the
  binding.

Live-run evidence in the committed executed notebook is
unchanged; the cells ran against the scratch dataset
correctly because ``mako_artifacts.regenerate_snapshots``
is called at runtime with the scratch ``(project,
dataset)``. The committed snapshot is the stable default
that the regenerator overwrites every time.

* docs(examples): rerun notebook with %pip install cell

Live rerun against fresh scratch dataset
``migration_v5_demo_badf2e2a``. All 59 cells passed. The
``%pip`` install cell still surfaces a PEP-668
``externally-managed-environment`` rejection in homebrew
Python (the install cell is targeted at Colab; in a
system-managed env the operator pre-installs into a venv
before launching the kernel). That's environment-
specific, not a notebook-correctness issue — the live
evidence below confirms the SDK behavior works against
real BigQuery + Vertex regardless.

Updated evidence (from the committed executed notebook):

  - Beat 1: GQL count before=0, after=1; rows_materialized
    total=19; property_graph_status='skipped:user_requested'.
  - Beat 2: drift caught (exit 1), restored (exit 0),
    combined build clean (rows_materialized total=19).
  - Beat 3: 3.3-3.5+3.7 print the "requires MAKO reference
    extractor at examples/migration_v5/reference_extractor.py
    — lands in follow-up PR #156" skip marker. 3.6 fires
    NODE + FIELD + EDGE.
  - Beat 4: resolver returns DecisionExecution with
    compile_id=07aa0018288c; GRAPH_TABLE count = 2. Hub-
    shape returns zero (expected — AgentSession synthesis
    lands with PR #156).

* docs(examples): env-aware install cell + README evidence cleanup

Three follow-up nits from review of the previous rerun:

* P1 — install cell rewritten as **environment-aware**.
  * In Colab: runs ``%pip install`` via
    ``get_ipython().run_line_magic("pip", ...)`` (the
    Jupyter magic that installs into the kernel env
    without going through the shell). Quoted
    ``"google-adk[vertexai]"`` so zsh doesn't glob it.
  * Outside Colab: skips the install entirely. System
    Python (PEP 668-managed) refuses pip installs and
    the expected workflow is a pre-baked venv. The cell
    checks that the required modules are importable
    and raises a ``RuntimeError`` with a copy-paste
    install command if any are missing.
  No more red ``externally-managed-environment`` in the
  committed notebook output.

* P2 — README's "live evidence" paragraph reworded so it
  describes the *shape* of the evidence rather than the
  exact numbers from one specific run. The committed
  executed notebook is the authoritative source for the
  per-cell values; the README now says
  ``after=N>0``, ``rows_materialized total>0``,
  ``count is non-zero``, etc.

* PR body refresh happens via ``gh pr edit`` after this
  commit lands.

Re-run captured (scratch ``migration_v5_demo_56f9179f``,
3 sessions). Install cell now prints
``"Local kernel — all required packages are importable."``
Per-beat live evidence (committed in the executed
notebook):
* Beat 1: count ``before=0, after=2``, ``rows_materialized
  total=38``, ``property_graph_status='skipped:user_requested'``.
* Beat 2: drift caught (exit 1) + restored (exit 0) +
  combined build clean (``rows_materialized total=19``).
* Beat 3: 3.3-3.5 + 3.7 print the ``"requires MAKO
  reference extractor ... lands in follow-up PR #156"``
  skip marker. 3.6 fires NODE + FIELD + EDGE.
* Beat 4: resolver returns ``compile_id=ba9c1ff85870``;
  ``GRAPH_TABLE count = 3``. Hub-shape returns zero
  (expected; AgentSession synthesis is PR #156).

* fix(examples/migration_v5): restore default-dataset snapshots after rerun

The previous commit captured the executed notebook which had
just regenerated the snapshots against the scratch dataset
(`migration_v5_demo_56f9179f`). Run `mako_artifacts.py`
with default args to restore the canonical
`(test-project-0728-467323, migration_v5_demo)` shape.

This is the same trap from the previous round; the checked-in
artifacts should always be the stable default, never live-run
residue. The notebook regenerates against the scratch at
runtime; on disk, the committed copy is the canonical
reviewer-readable target.

* docs(examples): soften Beat 4.4 framing to match what cell prints

The Beat 4.4 markdown said the cell emits a sample showing
each DecisionExecution connects an AgentSession,
ContextSnapshot, DecisionPoint, and SelectionOutcome. The
committed output only proves a nonzero DecisionExecution
count and then reports the ``partOfSession`` hub traversal
returns zero rows (AgentSession synthesis from the plugin
envelope lands with PR #156).

Reworded the framing to match: the count traversal alone
proves the resolver → graph wiring works end-to-end; the
hub-shape sample is explicitly deferred to PR #156.

* docs(examples): soften hub-shape inline comment to match deferred state

The markdown framing for cell 4.4 was already softened in
the previous commit, but the inline code comment above the
hub-shape query still said Confirms the user-authored
graph object answers a real path query. The committed
output intentionally shows zero hub rows because the
AgentSession synthesis from the plugin envelope is a PR
#156 follow-up. Updated the comment to match.
caohy1988 added a commit to caohy1988/BQAA-SDK-fork that referenced this pull request May 15, 2026
Surfaces four public-API additions that landed in the 0.3.0 window but
were not release-noted in the initial bump:

* A2A_INTERACTION typed view (adk_a2a_interactions) — PR GoogleCloudPlatform#136.
* CodeEvaluator.context_cache_hit_rate(...) + CLI — PR GoogleCloudPlatform#114.
* gm compile --emit-concept-index / --concept-index-table — PR GoogleCloudPlatform#92.
* ontology-build --skip-property-graph — PR GoogleCloudPlatform#108.

Per release-note review on PR GoogleCloudPlatform#163.
@caohy1988 caohy1988 mentioned this pull request May 15, 2026
4 of 5 tasks
haiyuan-eng-google pushed a commit that referenced this pull request May 15, 2026
* chore(release): 0.3.0

Cuts the 0.3.0 release from the accumulated Unreleased section.

* Bump version: 0.2.3 → 0.3.0 in pyproject.toml.
* Date the existing Unreleased block as ``[0.3.0] - 2026-05-15`` and add
  a Release-highlights summary at the top.
* Re-open an empty ``[Unreleased]`` section for post-release work.

No code changes; all entries in the 0.3.0 block are already merged on
main.

* chore(release): 0.3.0 — add missing user-visible entries

Surfaces four public-API additions that landed in the 0.3.0 window but
were not release-noted in the initial bump:

* A2A_INTERACTION typed view (adk_a2a_interactions) — PR #136.
* CodeEvaluator.context_cache_hit_rate(...) + CLI — PR #114.
* gm compile --emit-concept-index / --concept-index-table — PR #92.
* ontology-build --skip-property-graph — PR #108.

Per release-note review on PR #163.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants