> ## Documentation Index
> Fetch the complete documentation index at: https://docs.argalabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Sync Braintrust traces

> Pull Braintrust traces and filter them in your infrastructure before uploading evidence to Arga Training

Run the Python SDK's Braintrust worker in your infrastructure. It reads a project, selects supported Gmail/Stripe evidence locally, and sends the same filtered contract as [live tracing](https://docs.argalabs.com/sdks/python/tracing.md) to Arga Training.

The worker uses your Braintrust credential locally. Arga receives only the filtered projection. This worker does not use Arga's legacy server-side Braintrust import.

## Install and authenticate

```bash theme={null}
pip install --upgrade arga-py-sdk
```

Use v0.2.0 or later on a Linux/macOS host or container. The sync worker uses the standard package; the `braintrust` Python package is not required to read traces.

Supply these environment variables securely through your secret manager:

| Variable | Purpose |
| - | - |
| `BRAINTRUST_API_KEY` | Read access to the selected Braintrust project |
| `ARGA_TRACE_KEY` | An [upload-only Arga key](https://docs.argalabs.com/sdks/python/tracing.md#create-an-upload-key) bound to the same `source` you pass to sync |

Use a separate full Arga credential for task generation and review. Do not include keys in policy JSON, command arguments, traces or logs.

## Choose the goal and tool mappings

Save a local `trace-policy.json`:

```json theme={null}
{
  "revision": "support-v1",
  "text_fields": ["goal", "policy"],
  "goal_pointer": "/input/task",
  "policies": [
    "Refund only the duplicate charge and include prior refunds in the total.",
    "Customer confirmations require the accountable owner's review before sending."
  ],
  "operations": {
    "read_message": "gmail.messages.get",
    "fetch_charge": "stripe.charges.retrieve",
    "issue_refund": "stripe.refunds.create"
  }
}
```

`goal_pointer` is a JSON pointer selecting a string from the root span. For example, `/input/task` selects `{"input":{"task":"Resolve the duplicate payment..."}}`. Use `/input` when the input itself is a string.

Canonical executed tool names, such as `stripe.charges.retrieve`, work without a mapping. Each mapped span must contain provider-shaped arguments and responses: a charge retrieval uses `input.id` and a charge object in `output`; a list uses the provider's normal page shape. V1 does not infer nested wrappers such as `output.result`. Normalize custom shapes on your host before calling `project_trace`.

LLM, score and eval spans are ignored, including tool suggestions inside model outputs. Unknown executed tool spans create a coverage gap. A tool suggestion is not evidence that an operation ran.

The CLI example selects only the goal and listed policies. Review those strings before export. Gmail subject/body remain excluded. The JSON CLI cannot run a custom text callback; use the Python worker below when selected text needs your own local filter.

## Start the worker

Choose an initial timezone-aware timestamp for your project:

```bash theme={null}
python -m arga_sdk.tracing sync \
  --source support-agent \
  --project YOUR_BRAINTRUST_PROJECT_UUID \
  --state "$HOME/.local/state/arga/braintrust-support.json" \
  --since 2026-11-17T00:00:00+00:00 \
  --policy ./trace-policy.json \
  --watch
```

Replace the project UUID and start timestamp. Use `--region eu` for an EU Braintrust project; the default is `us`. The default destination is `https://api.argalabs.com`.

Without `--watch`, one bounded window runs and the process exits. The watcher processes five-minute windows, rereads two minutes of overlap, and waits 30 seconds once caught up. It fetches each selected trace's full tree, including children outside the root's discovery window.

Root and tool `metrics.start`/`metrics.end` must establish completed calls. End times before start times and ambiguous mutation ordering block generation. Parallel reads are accepted; overlapping reads/writes or writes remain coverage gaps.

## Use a custom local text filter

`filter_training_text` is your existing local filtering function. This example selects Gmail subject/body as well as goal/policy and applies the callback before aliases and credential masking:

```python theme={null}
import os
from datetime import datetime, timezone
from arga_sdk.tracing import CapturePolicy
from arga_sdk.tracing.braintrust import BraintrustSync

with BraintrustSync(
    source="support-agent",
    project_id=os.environ["BRAINTRUST_PROJECT_ID"],
    braintrust_key=os.environ["BRAINTRUST_API_KEY"],
    arga_key=os.environ["ARGA_TRACE_KEY"],
    state_path="/private/arga/braintrust-support.json",
    since=datetime(2026, 11, 17, tzinfo=timezone.utc),
    goal_pointer="/input/task",
    policies=["Customer confirmations require owner review before sending."],
    policy=CapturePolicy(
        text_fields=frozenset({"goal", "policy", "gmail.subject", "gmail.body"}),
        transform_text=filter_training_text,
        revision="support-v1",
    ),
) as sync:
    counters = sync.sync_once()
    print(counters)
```

Choose a private writable `state_path` and your intended start time. Pass `operations={...}` for custom tool names. You can also configure `window` and `lookback` as `timedelta` values for denser sources.

## Check progress and retries

`sync_once()` returns content-free counters:

| Counter | Meaning |
| - | - |
| `uploaded` | Episodes acknowledged by Arga in this window |
| `unchanged` | Previously acknowledged, unchanged episodes skipped |
| `pending` | Unfinished or unresolved roots retained locally for retry |
| `coverage_gaps` | Roots whose projection failed in this window |
| `caught_up` | The selected window reached this call's end timestamp |

An unfinished root stays pending until it completes. A malformed tree or other projection failure stays pending while healthy roots continue. Fix source coverage rather than treating pending counts as a successful import.

An unacknowledged Arga upload prevents the watermark from advancing. Query failures, invalid responses and read limits also stop the window. Retrying uses the persisted aliases and acknowledgement hashes to suppress unchanged uploads. Revised evidence creates a new immutable collection.

Queries are capped at 2 MB and 1,000 records. Pending roots are bounded to 1,000. Reduce the window or intentionally backfill a dense source. Spans arriving beyond the lookback require an explicit backfill; this worker is not a lossless audit log.

## Protect the checkpoint

The worker writes atomically with mode `0600` and uses a lock to prevent concurrent workers sharing a checkpoint. The file contains an alias key, pending root references and acknowledgement hashes, not API keys or raw span payloads. Keep it private and out of version control.

Preserve the checkpoint across restarts. Use a new checkpoint when changing source, project, collection policy, mappings, start time, destination or account. Renewing an upload key for the same owner/source can reuse the checkpoint.

Accepted evidence appears under [Training](https://app.argalabs.com/training) with the Braintrust sync source. Continue with [task and verifier generation](https://docs.argalabs.com/sdks/python/training.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.