Skip to main content

datahub-bq-connector-session-patch

A DataHub BigQuery sidecar source that attributes reads whose SQL did not qualify its table names — the ones the stock connector sees, misfiles and silently discards.

Full diagnosis, design, verification and limits: datavantage/docs/datahub-unqualified-read-attribution.md.

The problem

A client with a BigQuery default dataset set can write SELECT ... FROM Bets_Details. BigQuery fills in the blank at run time, but never records it: INFORMATION_SCHEMA.JOBS carries the SQL text and the billing project, not the job's default dataset.

DataHub's connector substitutes _SESSION for the missing dataset (queries_extractor.py:542,558), on the assumption that a bare name is usually a temporary table. Its own temp-table rule then flags anything whose dataset starts with _ (:309), and the aggregator drops it — for usage (sql_parsing_aggregator.py:1022) and for the query entity (:1693).

So the connector sees the table name, guesses the wrong container, and discards the result. Nothing is reported: the sibling branch of is_temp_table records what it drops, this one returns True in silence. Measured here: one client, 2,866 jobs in 7 days, 100% unqualified, 0 usage rows.

A 0 in DataHub usage is therefore ambiguous — "nobody reads this", or "read constantly, with unqualified SQL". Decommissioning decisions depend on telling those apart.

What this does

For a query whose SQL did not qualify its table names, it reads the job's real default dataset from BigQuery — configuration.query.defaultDataset on the job resource, fetched in bulk via jobs.list — and resolves the reference against that.

This is exact, not inferred. BigQuery does not expose the default dataset through INFORMATION_SCHEMA.JOBS, which is why DataHub substitutes _SESSION and loses the reference, but it is recorded on the job itself.

Measured across this estate, the presence of a default dataset is also the discriminator between the two kinds of bare name:

traffic carries a default dataset
real unqualified reads (Matillion/CData, -ext-*-data) 100%
genuine script temp tables (Dataform, -form) 0%

So a job without one resolves to nothing — which is the right answer for tmp_players, and exactly what name matching gets wrong.

The discovered-tables index is still built, for one job only: supplying the catalogued spelling. The _SESSION upstream carries a lowercased name and URNs are case sensitive, so a table absent from the index is dropped rather than emitted under a URN that does not exist. That also stops the sidecar inventing entities the main recipe does not own.

What this replaces

Before 0.2.0 this matched the bare name against discovered tables, accepting it only when unique in scope. That is still available as name_matching_fallback: true, off by default, and it has two problems exact resolution does not:

  • it cannot resolve collisions at all. ~54% of internal view names repeat across prod_malta_*, prod_spain_*, prod_italy_*…, and the common_ layer duplicates a further 39 against them. All of those were dropped as ambiguous; all resolve exactly now.
  • scope changed the answer. A bare name unique within scope was accepted, so a reader defaulting into an out-of-scope dataset resolved confidently and wrongly. Resolution no longer depends on scope, so scope is now purely a cost decision.

It ships as a distinct source type, so the production recipe stays stock:

source:
  type: datahub_bq_connector_session_patch

Installing

Per-recipe, via Extra Pip Libraries (DataHub UI) or extra_pip_requirements. That field is scoped to one recipe, which is what keeps the production recipe unaffected.

datahub-bq-connector-session-patch[bigquery]

The [bigquery] suffix is required, or the source will not load. A DataHub executor builds its per-recipe venv as acryl-datahub[<source_type>]; because datahub_bq_connector_session_patch is not a real acryl-datahub extra, pip ignores the unknown extra and installs core acryl-datahub. This package imports datahub.ingestion.source.bigquery_v2, so the import fails and the registry reports:

datahub_bq_connector_session_patch is disabled due to a missing dependency: google;
try running `pip install 'acryl-datahub[datahub_bq_connector_session_patch]'`

That suggested remedy is a dead end — the extra it names does not exist. The equivalent two-line form works identically if you prefer it explicit:

acryl-datahub[bigquery]
datahub-bq-connector-session-patch

Either way the extra is unpinned, so against an already-installed acryl-datahub it adds only the extra's dependencies and cannot move the executor's version (verified against 1.7.0.9).

The wheel declares no mandatory dependencies — it imports only datahub.*, which any environment running a recipe already has. Declaring acryl-datahub would let pip re-resolve the executor's own pinned copy while installing this. The tested range (>=1.6,<1.8) is enforced at runtime instead: an out-of-range executor raises a structured warning into the ingestion report rather than failing the run.

The sidecar recipe

pipeline_name: bq-session-attribution        # its OWN name — never the main recipe's
source:
  type: datahub_bq_connector_session_patch
  config:
    project_id_pattern:
      allow:
        - '^dv-prod-eu-w1(-.+)?-data$'
        - '^dv-ext-prod-eu-w1(-.+)?-data$'
        - '^dv-prod-eu-w1(-.+)?-comp\d+$'
    include_tables: false          # lightweight discovery still fills table_refs
    include_views: false
    include_table_lineage: false   # refused if true — see below
    include_usage_statistics: true
    use_queries_v2: true
    include_queries: true
    include_query_usage_statistics: true
    region_qualifiers: ['region-europe-west1']
    start_time: '-7 days'
    enable_stateful_time_window: true
    stateful_ingestion:
      enabled: true                # the time-window watermark
      remove_stale_metadata: false # refused if true — see below
    env: PROD

Two settings this source refuses to start with

Both were reproduced against a live catalog. They are not style preferences, so they are enforced in code rather than left to the YAML:

setting why it is refused
stateful_ingestion.remove_stale_metadata: true The sidecar writes a status aspect on every dataset it produces usage for, enrolling them in its stale-removal checkpoint. Its URN set is usage-driven, so any dataset not read that day falls out of the checkpoint and is soft-deleted — datasets the main recipe owns. Normal operation, not an edge case.
include_table_lineage: true Resolved names drive usage attribution only. A mis-resolved write would create a wrong edge into a real table, which is worse than the missing usage this package exists to fix.

remove_stale_metadata defaults to true, so it must be set explicitly. Only the combination bites — with stateful_ingestion.enabled: false there is no checkpoint and nothing is refused.

Scope it to the readers, not to minimise ambiguity

dataset_pattern should be wide. "Ambiguous" means the name matches more than one entry in discovered_tables within the recipe's scope, so narrowing scope removes the alternatives rather than resolving between them. If a reader's default dataset is prod_spain_* but the index holds only prod_malta_*, the name resolves confidently and wrongly.

Ambiguity fails safe. A too-narrow index fails silently, in the wrong direction.

Widening is otherwise harmless: disjoint_only means the sidecar emits only URNs it actually recovered, so it stays quiet wherever SQL is already qualified and never double-books usage with the main recipe.

Reading the run report

rewritten=41 tables (2792 refs) ambiguous=18 names (63 refs) unknown=7 names (12 refs)
queries_passed=954 queries_skipped=3118 (index=1631 unique names, 412 ambiguous names)
  • distinct counters — how much of the catalog was recovered. rewritten counts distinct resolved target tables; ambiguous and unknown count distinct bare names. Deliberately not distinct _SESSION URNs: those embed the reader project, so one table read from five projects would report as five.
  • *_refs — how many reads that attributed. One hot table read 2,000 times is one rewrite and 2,000 references.
  • queries_skipped — queries whose SQL was already fully qualified. The main recipe has those; the sidecar correctly stays out of the way.
  • queries_mixed — queries carrying both an already-resolvable reference and a recovered one. Also left to the main recipe, for a subtler reason, below.

Why mixed queries are skipped

disjoint_only keeps the two pipelines from double-booking usage, which is a timeseries aspect. It does not, by itself, protect the query entity.

Query entities are keyed by get_query_fingerprint(sql, platform, fast=True) — a pure function of the SQL text, so both pipelines derive the same urn:li:query:<fp>. But querySubjects is a versioned aspect, not timeseries. If the sidecar emitted its narrowed subject set for a query the main recipe also sees, whichever ran last would win, and the entity would flip between the two subject sets on every scheduled run.

Passing the union instead would fix the subjects and double-book usage for the already-resolvable half. Neither is acceptable, so a mixed query is left entirely to the main recipe and counted. Measured on dv-ext-prod-eu-w1-data over 7 days: queries_mixed=0 — the guard costs nothing there, because that client's SQL is uniformly unqualified.

A per-reader-project breakdown is logged alongside it, so a project that recovers nothing shows up at 0.0% rather than vanishing.

Two failures that look like success

Both were hit during development. Each leaves the run green and the output plausible:

  1. discovered_tables is empty at construction. The source passes a live reference to bq_schema_extractor.table_refs, which only fills during the schema pass. The index is built lazily on first use, never in __init__.
  2. Refs are projects/P/datasets/D/tables/T, not P.D.T. Naive dotted parsing matches nothing.

Because of these the source raises a structured warning if the index came out empty or nothing was rewritten. Never trust a negative result without checking the index size.

Limits

Unique-name resolution only. Where a bare name matches several catalogued objects it is dropped. How much that costs depends entirely on the estate:

population ambiguous names
views in dv-ext-prod-eu-w1-data 0.0% (162/162 unique)
views in dv-prod-eu-w1-data 54.4%
tables referenced estate-wide 53.0%

The external-facing views carry licence/brand suffixes and are unique by construction. The internal estate's per-market layout duplicates names across prod_malta_*, prod_spain_*, prod_italy_*…, and the cross-market common_ layer duplicates a further 39 names against them — so roughly half of any bare reads against it stay unrecovered.

Resolving those needs leaf-set matching, not name matching: the colliding common-vs-market views have identical names but cleanly distinct leaf sets. That is explicitly out of scope — see §9.1 of the design doc for what it would take.

Measuring a scope before shipping it

export BQ_SESSION_PATCH_BILLING_PROJECT=dv-ext-prod-eu-w1-data
python tools/measure_scope.py eu baseline --days 7
python tools/measure_scope.py eu patched  --days 7
python tools/diff_runs.py runs/mcps_eu_baseline_7d.json runs/mcps_eu_patched_7d.json

Scope flags: --projects for explicit ids, --project-pattern to override the region's project_id_pattern.allow regexes, --days for the window.

The billing project must be explicit — --billing, or $BQ_SESSION_PATCH_BILLING_PROJECT, or inferred when --projects names exactly one. DataHub passes it straight to bigquery.Client(...), and when it is None the client inherits whatever google.auth.default() resolves: GOOGLE_CLOUD_PROJECT first, then the ADC file's quota project, then the active gcloud config. A stray env var will therefore bill every INFORMATION_SCHEMA job to an unrelated project and fail as bigquery.jobs.create denied against a project you never named. The script refuses to start rather than inherit one, and prints both the billing and the ambient project so a mismatch is visible.

measure_scope.py writes MCPs to a file sink (nothing reaches GMS) and prints the per-project recovery table; diff_runs.py reports datasets gaining usage, query entities gained and readers newly attributed, and fails if any schemaMetadata, upstreamLineage or datasetProperties aspect leaked into the output.

Trying it against a local DataHub

recipes/local/ holds a two-step pair for a quickstart instance, scoped to one project:

make venv && source .venv/bin/activate
datahub ingest -c recipes/local/01-catalog.yml       # stock `bigquery` — the catalog
datahub ingest -c recipes/local/02-usage-sidecar.yml # this package — the recovered usage

Step 1 runs with usage on, exactly as production does, and still misses the unqualified reads — that is the premise. Step 2 shows what it missed. Measured against dv-ext-prod-eu-w1-data over 7 days:

step 1 (catalog) step 2 (sidecar)
datasets with a usage aspect 5 +59
query entities 170 +61
aspects emitted schema, lineage, properties, usage, queries usage and queries only

Both use ADC, so the VPN must be up — VPC-SC blocks ADC while the bq CLI keeps working, which makes the failure look like a permissions problem.

They run stateless (stateful_ingestion.enabled: false), so re-running re-emits the same days. Timeseries aspects append rather than upsert, so repeated local runs accumulate duplicate usage documents for a day. Harmless locally; in a real deployment keep the stateful time window, which is what makes each day emit exactly once.

Developing

make venv       # .venv on python 3.11, package installed editable + test extras
make test       # 94 tests against a real acryl-datahub
make gate       # the acceptance gate: must FAIL on stock, PASS patched
make published  # is this version already on PyPI, and does it match dist/?
make release    # test, gate, bump, rebuild, verify  -> dist/
make publish

make published answers the question verify-dist cannot. PyPI releases are immutable, so the two ways to get hurt are uploading a version that already exists, and having a local build silently diverge from the one that was published. It checks both, and its exit codes are the interface:

exit meaning
0 published, and local artifacts match (or none exist to compare)
1 not published — the version is missing, or the project does not exist
2 could not determine — PyPI unreachable
3 published, but dist/ differs from what was uploaded

make published VERSION=0.1.0 checks any version. 2 is deliberately not 1: an unreachable PyPI is not clearance to publish, so make published || make publish fails closed on a network hiccup rather than republishing over a live version.

make venv exists for interactive work and for the tools/ scripts, which need real BigQuery credentials and so cannot run in a throwaway environment. make test and make gate deliberately do not use it — they build their own environment per run, so a stale or hand-modified .venv can never make them pass.

make gate is the one that matters on an acryl-datahub bump. This package patches private internals, so make test alone would stay green even if upstream fixed the defect out from under it — at which point this package is dead weight and should be retired, not shipped. gate fails loudly in that case.

Upstream

The defect is unfixed on datahub-project/datahub master as of 2026-09-14. The ask there is modest: report the _SESSION discard, or offer opt-in resolution against discovered tables. See UPSTREAM-ISSUE.md.

Metadata

Release files for datahub-bq-connector-session-patch 0.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for datahub-bq-connector-session-patch 0.2.1
File Size Uploaded Provenance Actions
datahub_bq_connector_session_patch-0.2.1.tar.gz 55.7 kB Without provenance Details for datahub_bq_connector_session_patch-0.2.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for datahub-bq-connector-session-patch 0.2.1
File Interpreter ABI Platform Actions
datahub_bq_connector_session_patch-0.2.1-py3-none-any.whl Python 3 none any Details for datahub_bq_connector_session_patch-0.2.1-py3-none-any.whl

Total release size: 84.8 kB

Release files / datahub_bq_connector_session_patch-0.2.1.tar.gz

Download URL datahub_bq_connector_session_patch-0.2.1.tar.gz
Size 55.7 kB
Tags Source
SHA-256 checksum
How to use checksums
916db67cb66aa561f0da33fed768c3b24b31b1ff8e8efd544d5057d015cc1d8f
BLAKE2b-256 checksum
How to use checksums
c6b1e477947c0f3e475e66a7a93974340b9b78d96d97b7b1d71aafe93f8e070d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.10.8 {"installer":{"name":"uv","version":"0.10.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / datahub_bq_connector_session_patch-0.2.1-py3-none-any.whl

Download URL datahub_bq_connector_session_patch-0.2.1-py3-none-any.whl
Size 29.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3101cfc6fef1023fe7892658e339cce487928d3a4dd99ea602ced39617050aa4
BLAKE2b-256 checksum
How to use checksums
b93b78c938c99d36cfd42141f63a1c8f70da2e56076620f43608aa545842b433
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.10.8 {"installer":{"name":"uv","version":"0.10.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for datahub-bq-connector-session-patch 0.2.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page