a2a-metatrace / scripts /export_hf.py
dangoldbj's picture
release v1
d38477a verified
Raw
History Blame Contribute Delete
9.47 kB
"""Export the raw A2A-MetaTrace capture JSON into a HuggingFace-style dataset.
Each generation run (``corpus.run_corpus``) writes a capture document
``results/corpus/a2a_metatrace.json`` whose ``messages`` list is a flat sequence of
metadata-only records ``obs(m)`` with workflow ground-truth labels.
This script turns that capture into the layout the HuggingFace Hub expects:
* one Parquet file per config under ``data/<config>/train.parquet`` (message-level rows,
the natural tabular form; reconstruct a workflow by grouping on ``trace_id``), and
* a dataset card ``README.md`` whose YAML front matter declares the ``configs`` and
``dataset_info`` so ``datasets.load_dataset("<repo>", "<config>")`` just works.
Run:
uv run python scripts/export_hf.py
The published artifact is ``data/*.parquet`` + ``README.md``; the raw JSON is an
intermediate (gitignored). The prose datasheet lives in ``DATASHEET.md``.
"""
from __future__ import annotations
import json
from pathlib import Path
import pandas as pd
ROOT = Path(__file__).resolve().parents[1]
CORPUS = ROOT / "results" / "corpus"
DATA = ROOT / "data"
# capture file -> (config name, mode, transport). A config is one coherent slice a
# consumer would load on its own; mode/transport ride along as columns too.
CONFIGS: list[tuple[str, str, str, str]] = [
# traffic from real official a2a-samples agents
("a2a_metatrace.json", "default", "agents", "https"),
]
# The message-level row schema. Order is the dataset's column order; dtypes are the
# HuggingFace feature dtypes the card advertises.
SCHEMA: list[tuple[str, str]] = [
("trace_id", "int64"), # workflow id; group on this to reconstruct a workflow
("task_class", "string"), # the label an adversary recovers
("variant", "string"), # the concrete composition (group for leave-variant-out)
("client_id", "string"), # orchestrating client (opaque token)
("n_stages", "int32"), # stages in this workflow
("stage_idx", "int32"), # which stage this message belongs to
("step_type", "string"), # discovery_query|discovery_result|request|update|response
("direction", "string"), # c2s | s2c
("src", "string"), # opaque source endpoint token
("dst", "string"), # opaque destination endpoint token
("t", "float64"), # relative timestamp (seconds)
("length", "int64"), # wire byte length of the message (the obs(m) volume axis)
("capability", "string"), # capability named at this stage
("label_visible", "bool"), # whether the semantic label is visible at this message
("mode", "string"), # agent backend
("transport", "string"), # transport the capture ran over
]
def _frame(capture: dict, mode: str, transport: str) -> pd.DataFrame:
rows = []
for m in capture["messages"]:
row = {name: m.get(name) for name, _ in SCHEMA if name not in ("mode", "transport")}
row["mode"], row["transport"] = mode, transport
rows.append(row)
df = pd.DataFrame(rows, columns=[n for n, _ in SCHEMA])
for name, dtype in SCHEMA:
df[name] = df[name].astype(dtype)
return df
def _features_yaml() -> list[str]:
return [f" - name: {n}\n dtype: {d}" for n, d in SCHEMA]
def _front_matter(stats: list[dict]) -> str:
configs = []
info = []
for s in stats:
configs.append(
f"- config_name: {s['config']}\n"
f" data_files:\n"
f" - split: train\n"
f" path: data/{s['config']}/train.parquet"
)
info.append(
f"- config_name: {s['config']}\n"
f" features:\n" + "\n".join(_features_yaml()) + "\n"
f" splits:\n"
f" - name: train\n"
f" num_examples: {s['rows']}"
)
total = sum(s["rows"] for s in stats)
size_bucket = ("1K<n<10K" if total < 10_000 else
"10K<n<100K" if total < 100_000 else "100K<n<1M")
return (
"---\n"
"pretty_name: A2A-MetaTrace\n"
"task_categories:\n- tabular-classification\n"
"tags:\n"
"- traffic-analysis\n- metadata-privacy\n- agent\n- a2a\n"
"- multi-agent\n- workflow-fingerprinting\n"
f"size_categories:\n- {size_bucket}\n"
"configs:\n" + "\n".join(configs) + "\n"
"dataset_info:\n" + "\n".join(info) + "\n"
"---\n"
)
def _body(stats: list[dict]) -> str:
rows = "\n".join(
f"| `{s['config']}` | {s['mode']} | {s['transport']} | {s['workflows']} | "
f"{s['classes']} | {s['variants']} | {s['rows']} |"
for s in stats
)
return f"""# A2A-MetaTrace
A labeled, **metadata-only** corpus of multi-agent **A2A** (Agent-to-Agent) workflow
traffic. Each row is one wire message reduced to what a passive network observer sees,
`obs(m) = (src, dst, t, length, direction)`, with workflow ground-truth labels; message
bodies are discarded. The corpus exists to study how much of a *pending agent workflow*
leaks from communication-graph metadata alone, and to evaluate metadata-protecting
transports against it.
**Provenance (disclosed).** Workflows run over the real `a2a-sdk` protocol path
(Agent Cards, discovery, `message/send`, SSE) against real official `a2a-samples` agent
servers backed by real language-model calls. The workflow *compositions* and *labels*
are ours (see `DATASHEET.md`). This is the honest provenance claim: the protocol path and
agent behavior are real; the composition is designed.
## Config
| config | agent backend | transport | workflows | classes | variants | rows (messages) |
|---|---|---|---|---|---|---|
{rows}
The corpus is captured from official `a2a-samples` agents composed into multi-agent
workflows; transport is HTTPS-direct (the metadata-protecting transport is evaluated
analytically; see `DATASHEET.md`).
## Usage
```python
from datasets import load_dataset
import pandas as pd
ds = load_dataset("a2a-metatrace", split="train") # message-level rows
df = ds.to_pandas()
# reconstruct workflows and their labels by grouping on trace_id
by_wf = df.groupby("trace_id")
labels = by_wf["task_class"].first()
```
A workflow is the unit an adversary classifies; featurize per `trace_id` (message counts,
length stats, timing, direction n-grams) and recover `task_class`. Use the `variant`
column for a **leave-variant-out** split (generalization to unseen compositions).
## Regenerating the corpus
The published Parquet is produced by capturing real official `a2a-samples` agents. To
reproduce it end to end:
1. **Get the agents.** Clone the official samples repo and point the harness at its
Python agents directory:
```bash
git clone https://github.com/a2aproject/a2a-samples.git
export A2A_SAMPLES_DIR=$(pwd)/a2a-samples/samples/python/agents
```
2. **Provide model credentials.** The sample agents call real models:
- `export OPENAI_API_KEY=...` (the OpenAI- and LiteLLM-backed agents), and
- for the Google-ADK agents, a Vertex project via Application Default Credentials:
`export GOOGLE_CLOUD_PROJECT=...` and `gcloud auth application-default login`.
Keys may instead be placed in a local `.envrc` (`export KEY=VALUE` lines); see
`corpus/sample_agents.py` for all configuration variables.
3. **Install and run** (Python 3.13):
```bash
uv sync
uv run python -m corpus.run_corpus --runs-per-class 30 # writes results/corpus/a2a_metatrace.json
uv run python scripts/export_hf.py # writes data/ + this README
```
See `DATASHEET.md` for the workflow classes, provenance, and disclosed model substitutions.
## What it is for
- **Workflow-fingerprinting / traffic analysis** on agent interoperation traffic.
- **Evaluating metadata-protecting transports** for agent interoperation.
- A reproducible, provenance-disclosed alternative to purely synthetic agent-traffic models.
See `DATASHEET.md` for construction, intended use, and limitations. Regenerate this card
and the Parquet files with `uv run python scripts/export_hf.py`.
## Citation
```bibtex
@misc{{a2ametatrace,
title = {{A2A-MetaTrace: a metadata-only corpus of multi-agent A2A workflow traffic}},
author = {{Dangol, Bijaya}},
year = {{2026}}
}}
```
"""
def main() -> None:
stats: list[dict] = []
for fname, config, mode, transport in CONFIGS:
src = CORPUS / fname
if not src.exists():
print(f"skip {config}: no capture at {src.name}")
continue
cap = json.loads(src.read_text())
df = _frame(cap, mode, transport)
out = DATA / config
out.mkdir(parents=True, exist_ok=True)
df.to_parquet(out / "train.parquet", index=False)
stats.append({
"config": config, "mode": mode, "transport": transport,
"rows": len(df), "workflows": int(df["trace_id"].nunique()),
"classes": int(df["task_class"].nunique()),
"variants": int(df["variant"].nunique()),
})
print(f"wrote data/{config}/train.parquet "
f"({len(df)} rows, {df['trace_id'].nunique()} workflows)")
if not stats:
print("no captures found; run `python -m corpus.run_corpus` first")
return
(ROOT / "README.md").write_text(_front_matter(stats) + "\n" + _body(stats))
print(f"wrote README.md (dataset card) for {len(stats)} configs")
if __name__ == "__main__":
main()