Skip to content

About

Lineage-aware, execution-time deduplication for enterprise AI agents (DataHub-native)

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

91 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

TokenGuard

Lineage-aware, execution-time deduplication for enterprise AI agents (DataHub-native).

TokenGuard is a proxy / "team of governance agents" that sits in front of enterprise-agent tool calls. For every tool call it:

  1. Resolves the raw call to a governed DataHub lineage subgraph (an Intent) -- entities, bounded lineage, glossary/domain/classification tags, and a deterministic parameter vector.
  2. Matches that intent against prior intents:
    • Tier 1 -- exact hash cache (deterministic key of operation + params
      • session/agent scope).
    • Tier 2 -- near-duplicate matching: Weisfeiler-Leman structural similarity, cosine-similarity over parameters, governance-equivalence (glossary/domain/classification), and optional query-shape corroboration.
  3. Gates any match through a governance check -- schema drift, lineage change, governance-boundary (leak prevention), and metadata staleness -- with a conservative "when in doubt, re-execute" bias.
  4. Serves the cached result on a pass, or forwards + records a fresh execution, writing closed-loop provenance back to the graph (tokenguard.dedup_record, tokenguard.breaker_trip) that the resolver reads back before the next action -- today advisory (logged for visibility when it disagrees with the in-process candidate pool, never itself overriding a serve decision; see "DataHub surfaces used" below).
  5. Circuit-breaks runaway agents: a per-agent sliding-window call counter quarantines an agent that exceeds a threshold, with a governance-visible marker written back to the graph.

The goal: never serve a stale, misclassified, or unauthorized result to an agent -- while avoiding redundant, costly LLM/tool executions across a fleet of agents that keep asking (structurally, and later semantically) the same governed questions. The gate is the durable value; the savings are real but modest and honestly measured (docs/MEASUREMENT_REPORT.md), not the headline claim.

Architecture at a glance

tool_call -> resolver.resolve()      -> Intent (+ A2.5 prior-dedup read-back)
          -> matching.MatchingPipeline.match() -> Tier1 | Tier2(A+B+C[+D])
          -> gate.evaluate()          -> serve? or re-execute (fail-closed)
          -> writeback.record_dedup() / record_breaker_trip()
          -> circuit_breaker.CircuitBreaker  (quarantine on breach)

tokenguard.proxy.Proxy is the sole composition root wiring these modules together. See TokenGuard_Architecture_Spec.md (§2-§8, §11), TASKS.md (Track A build spec, A0-A8), and PLAN.md for the full design.

Buildability: no external services required

DataHub access sits behind a client interface (tokenguard.datahub.client.DataHubClient) with an in-memory fake (InMemoryDataHubClient) backed by a well-governed sample catalog -- glossary terms, domains, classification/PII tags, lineage chains across Finance/Marketing/ML. Every unit and end-to-end test, and the demo, runs entirely in-memory: no live DataHub, no live Redis, no network calls, no Docker. docker-compose.yml separately provisions a real DataHub Core instance for a live demo (see below) -- it is not required to build, test, or run the reference implementation.

DataHub surfaces used -- and not used, and why

Stated plainly, since it's easy to over-imply from the project name:

Surface Used? How
Lineage graph (get_lineage, get_lineage_paths_between) Yes Bounds every Intent's touched-entity subgraph (resolver.py)
Glossary / domain / classification (governance metadata) Yes GovernanceFingerprint (governance-equivalence matching, tier2_governance.py), and the fail-closed authorization check in gate.py
Schema metadata Yes Schema-drift detection (gate.py::check_schema_drift)
Structured-property mutation API (write-back) Yes writeback.record_dedup()/record_breaker_trip() -- live-confirmed DEFINE->WRITE->READ-BACK against DataHub Core v1.5.0.6, docs/DATAHUB_WRITEBACK_SPIKE.md
get_dataset_queries (real observed query shapes) Yes, optional Tier-2D corroboration (tier2_query.py); advisory-only, never a false veto when absent
DataHub Core GMS, over the acryl-datahub SDK's DataHubGraph Yes tokenguard/datahub/mcp_client.py's GmsDataHubClient -- direct SDK-to-GMS calls, no intermediate server
MCP Server (mcp-server-datahub) No TokenGuard talks to GMS directly over the SDK, not through an MCP tool-call boundary. GmsDataHubClient was named McpDataHubClient until this was called out as misleading; the old name is kept only as a backward-compatible alias. Rationale: the gate is a synchronous, in-process serve/no-serve decision on every tool call -- routing that through an MCP round trip would add latency for no capability gain, since the SDK already exposes everything the gate needs.
Agent Context Kit / DataHub Skills / Analytics Agent No Not integrated. These are separate DataHub product surfaces this submission does not touch; naming them here so a judge doesn't have to go looking to find out.

The write-back read-back (resolver.py's A2.5 step) is real and demonstrated (examples/demo.py round-trips it), but is currently advisory, not load-bearing: Proxy.handle() logs when the durable graph record disagrees with the in-process candidate pool, but the gate-checked MatchingPipeline remains the sole authoritative serve/no-serve path. This is a deliberate choice (a stale or unverifiable cross-process hint should never itself short-circuit a governance check) but it means "the next agent inherits the knowledge" is true in the sense that the fact is visible on the graph, not yet in the sense that it changes the next agent's serve decision. Closing that gap is future work, not claimed as done here.

Trust Model

When a ScopeResolver is wired into a Proxy (tokenguard/scope.py), TokenGuard derives each request's governance scope from a server-held table keyed on the caller-supplied agent_id — a caller can no longer serve itself another agent's classified result by simply declaring a wider RequesterScope (docs/SECURITY_REVIEW.md F1). For a registered agent_id, the server-resolved scope always wins: the caller's own asserted RequesterScope is either identical-or-narrower (silently ignored, the resolved scope is substituted anyway) or wider (the whole call is rejected before any resolve/match/gate/execute work happens).

This protection is opt-in, not a default. Proxy(client=...) with no scope_resolver argument — which is exactly what build_default_proxy() and the tokenguard-demo console script do unless you configure one — constructs an empty StaticScopeResolver({}): every agent_id resolves registered=False and the pre-F1 behavior applies. This is logged loudly (logger.warning(...)) at Proxy construction time, not hidden. To close the gap without writing code, set TOKENGUARD_STATIC_SCOPE_TABLE_JSON to a JSON object ({"agent_id": {"allowed_domains": [...], "allowed_classifications": [...]}}); build_default_proxy() picks it up automatically. To wire it programmatically, construct your own StaticScopeResolver/DataHubScopeResolver and pass scope_resolver=... to Proxy(...).

This is not authentication. agent_id itself is still passed by the caller at the transport boundary (B1) and is not cryptographically verified — TokenGuard does not (yet) bind it to an mTLS certificate, a signed JWT, or an SSO/IdP claim. An agent whose identity has not been registered with a ScopeResolver falls back to trusting its own asserted scope (configurable via TOKENGUARD_SCOPE_UNREGISTERED_AGENT_POLICY, "trust_caller_scope" by default, "deny" for a stricter default once every legitimate agent is registered). Real identity binding (mTLS/JWT/IdP) is deferred, disclosed, and out of scope for this reference implementation. If you choose DataHubScopeResolver (scope read from a DataHub-graph-backed grant) rather than StaticScopeResolver (seeded in-process from trusted config), you are responsible for securing write-access to the tokenguard.agent_scope structured property at the DataHub ACL layer — TokenGuard itself does not authorize who may call write_agent_scope_grant, and an attacker who can reach that write path could self-register an escalated scope grant. See tokenguard/scope.py's module docstring and docs/SECURITY_REVIEW.md F1 for the full attack this closes and what remains open.

Quickstart

# 1. Create and activate a virtualenv
python3 -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate

# 2. Install the package (editable) + dev/test deps
pip install -e ".[dev]"

# 3. Run the in-memory demo -- drives the real Proxy end to end
python examples/demo.py
# or via the console script:
tokenguard-demo

# 4. Run the full test suite
pytest -q

# 5. Lint
ruff check .

The demo shows, against the real Proxy (not a mock/stub):

  • A genuine Tier-1 dedup hit (identical repeated call served from cache).
  • A genuine gate-forced re-execution (a schema-drift mutation forces a cache-eligible call to re-execute instead of serving stale data).
  • A closed-loop write-back record (tokenguard.dedup_record), read back to prove the loop closes.
  • Real, cost-model-derived tokens/dollars-saved figures (not hardcoded literals).

See examples/README.md for a detailed walkthrough of the demo's output.

Demo video

https://youtu.be/LaCDV4H9riM (2:47, under the 3:00 cap).

Testable URL / live dashboard

Public judge-testable URL (Azure VM)

This is the URL that will be opened during judging:

https://tokenguard.itinerario.io

It serves the FastAPI/SPA dashboard (backend/ + frontend/) over a Cloudflare named tunnel (tokenguard-demo, egress-only, no inbound NSG rule needed) proxying 127.0.0.1:8000 on the VM, running as the tokenguard-ui systemd unit with Restart=always. It runs TOKENGUARD_UI_MODE=live against a real, self-hosted DataHub GMS (GmsDataHubClient, TOKENGUARD_DATAHUB_BACKEND=mcp -- the config value name predates the class rename and is left as-is, see "DataHub surfaces used" above) -- a judge visiting this URL sees real graph reads and real Proxy.handle() outcomes, not the hermetic in-memory fake.

A live KPI bar (decisions, bad serves blocked, tokens/dollars saved -- labeled modeled estimate (testbed), see "Token accounting" above), an outcome bar broken down by reason-code family, a scrolling live decision feed, and a "Gate Decision Theater" detail panel all update continuously over Server-Sent Events (/events).

What's actually driving it, honestly stated: this is not organic or growing production traffic. A background loop (backend.live_decision_source) replays a small, fixed governed workload -- the same ~8 finance_catalog entities and 5 agent identities, ~10 requests per ~3-second cycle, forever -- against the real DataHub GMS. What's genuinely real on every cycle: each decision is an actual Proxy.handle() call against live graph state, not a canned response; every 3rd cycle injects a real mutation (a bumped content_version/updated_at on the 10-Q filing, i.e. a genuine restatement), so the freshness-gate refusals you see are real, not scripted outcomes; and the cold-read misses use a fresh per-cycle nonce, so those really are new cache keys every cycle. What doesn't change: the entity/agent/operation universe itself is fixed and repeating -- the decision count you see is cycle-count x 10 accumulated since the process started, not a count of distinct real-world events. So "decisions recorded" and "tokens saved" grow because the loop keeps running, not because new content or new callers are arriving.

Deploy / redeploy steps:

ssh <user>@172.190.201.72
cd ~/tokenguard-app && git fetch && git checkout <tag-or-branch>
.venv/bin/pip install -e ".[ui]"
sudo systemctl restart tokenguard-ui

Streamlit demo (offline/local judge fallback)

A hermetic, in-memory Streamlit UI over the real tokenguard.proxy.Proxy -- no live DataHub, no network, no mock; synthetic demo data only. Four prefilled sidebar buttons let a judge see all four decision types in well under a minute: a dedup hit, a freshness-forced re-execution (restated SEC filing), an MNPI/F1 scope-escalation refusal, and a research-dedup saturation short-circuit -- each tagged with its TG-GATE-*/TG-DEDUP-* reason code, plus a live audit-ledger view (the compliance-evidence artifact) that grows with every click. A "Submit your own action" form additionally lets a judge pick their own agent/access-level/dataset combination (from a fixed, pre-registered menu, not an arbitrary dataset) and watch the same Proxy decide live -- including reproducing the F1 scope-escalation attack by deliberately claiming a wider access level than the acting agent is registered for. This is not what's deployed at the public judging URL above -- run it locally:

pip install -e ".[app]"
./scripts/run_streamlit.sh
# -> http://localhost:8501

streamlit lives in its own optional app extra (pyproject.toml) and is imported ONLY inside app/streamlit_app.py -- the hermetic default install (no extras), pytest -q, and ruff check . all stay green with streamlit absent from the environment (see tests/test_streamlit_app_smoke.py's skip-if-absent guard). See docs/STREAMLIT_PLAN.md for the full design.

Metrics / evaluation

Before funding further matching-precision work (LSH/Merkle/adaptive thresholds), docs/PLAN_AUDIT.md §5 requires measuring the numbers that decide whether it pays off: Tier-1-vs-Tier-2 fire-rate split, savings by tier, DataHub (GMS SDK) round-trips per call, and a false-cache-serve rate. Those numbers are produced by a runnable, hermetic harness (no external services, no mocks — it drives the real Proxy):

python examples/measure.py

which reports:

  • Tier-1 vs Tier-2 fire-rate split + savings-by-tier, over a realistic mixed call stream (not an every-tier-hits fixture) — tokenguard.metrics.TierMetrics.
  • The same stream re-run with tier1_key_scope="cross_session", to correct for the session-scope artifact that otherwise launders cross-session exact repeats into fake "Tier-2" hits.
  • DataHub (GMS SDK) round-trip counts per handle(), broken down by stage (resolve/gate/match/write-back), plus the same counts priced at a modeled 50ms/round-trip — tokenguard.datahub.instrumentation.CountingDataHubClient, a transparent decorator that survives the fake→real DataHubClient swap.
  • Candidate-pool size at the point Tier-2 would scan it, on this fixture's realistic call volume.
  • False-cache-serve rate + mean-hit-distance against a labeled adversarial catalog (magnitude-collision params, mixed-governance queries, added-upstream lineage, partial-fetch fail-open, plus a genuine positive-control cross-entity Tier-2 serve) — tokenguard.datahub.adversarial_catalog.build_adversarial_catalog() + tokenguard.eval.safety.run_safety_harness.

docs/MEASUREMENT_REPORT.md captures the numbers from an actual run, with the verdict they imply for the LSH/Merkle/adaptive-threshold decision. Re-run the harness yourself to reproduce or refresh them.

Project layout

tokenguard/
  proxy.py                # composition root: Proxy.handle(), the sole importer
                           # of every other module
  resolver.py              # raw tool call -> Intent (+ A2.5 prior-dedup read-back)
  gate.py                  # schema-drift / lineage-change / governance-boundary gate
  writeback.py              # closed-loop structured-property write-back + read-back
  circuit_breaker.py        # per-agent sliding-window quarantine
  matching/
    pipeline.py             # Tier1 -> Tier2(A/B/C)+D orchestration
    tier1_exact.py           # exact hash cache
    tier2_structural.py      # Weisfeiler-Leman structural similarity
    tier2_parametric.py      # cosine similarity over parameter vectors
    tier2_governance.py      # governance-equivalence check
    tier2_query.py           # optional query-shape corroboration
    store.py                 # TTL result store (in-memory, or Redis-backed)
  datahub/
    client.py                # DataHubClient interface (the buildability seam)
    fake.py                   # InMemoryDataHubClient (no external services)
    sample_catalog.py          # well-governed sample catalog fixture
  types.py                   # shared frozen dataclasses (Intent, MatchResult, ...)
  config.py                  # centralized Settings, env-var overrides

examples/
  demo.py                    # runnable demo driving the real Proxy
  measure.py                  # MEASURE-FIRST harness (docs/PLAN_AUDIT.md §5):
                              # fire-rate/savings-by-tier, round-trips,
                              # false-serve safety rate -- see "Metrics /
                              # evaluation" above and docs/MEASUREMENT_REPORT.md
  README.md                  # demo walkthrough

tests/                      # unit + end-to-end tests (all hermetic, in-memory)
docker-compose.yml          # provisions real DataHub Core for a live demo

Project layout / docs

Beyond the reference implementation itself:

Testing

pytest -q          # full suite, hermetic (in-memory fake DataHub, no external services)
ruff check .       # lint

CI (.github/workflows/ci.yml) runs both on every push/PR across Python 3.10-3.12, plus a smoke run of examples/demo.py -- entirely hermetic, no external services are started.

Live demo against real DataHub Core

docker-compose.yml provisions a real DataHub Core stack (Elasticsearch + PostgreSQL + DataHub GMS/frontend) for a live, non-in-memory demonstration:

docker-compose up -d
# DataHub UI: http://localhost:3000

# Once GMS is healthy, validate the real write-back loop end to end:
DATAHUB_GMS_URL=http://localhost:8080 python scripts/validate_datahub_writeback.py

# or, to do both steps (incl. waiting for GMS) in one command:
./scripts/run_live_demo.sh

This is optional and separate from the reference implementation: building, testing, and running the in-memory demo above never requires it.

docs/artifacts/LIVE_DATAHUB_RUN.md is a committed transcript of this exact validation, run 2026-07-25 against real DataHub Core v1.5.0.6 (the same GMS instance the public judging URL above reads from) -- so a judge doesn't have to stand up the stack themselves to see the write-back loop actually round-trip against real DataHub, only to reproduce it if they want to verify it firsthand.

docs/artifacts/LIVE_DATAHUB_TIER2_RUN.md extends this to the Tier-2 matcher itself: two mirrored dataset entities (scripts/validate_datahub_tier2_live.py, or ./scripts/run_tier2_live_validation.sh for a one-command run against this same VM) created live under a demo-namespaced DataHub platform, with a genuine Tier-2 structural/parametric/governance-equivalence match (wl_overlap/cosine/gov all 1.0) run through the real Proxy/MatchingPipeline/GmsDataHubClient -- not InMemoryDataHubClient, the fake every other test/demo uses.

Configuration

All tunable knobs (Tier-1 key scope, governance strictness, cosine threshold, lineage hop depth, Redis URL, circuit-breaker thresholds, hash algorithm) live in tokenguard.config.Settings with TOKENGUARD_* environment-variable overrides. See examples/README.md's Configuration section for the full list.

About

Lineage-aware, execution-time deduplication for enterprise AI agents (DataHub-native)

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages