File size: 14,234 Bytes
ba07c83
 
 
 
 
 
 
 
 
 
 
9a0ff98
 
 
ba07c83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf0d2b5
 
9a0ff98
 
 
 
ba07c83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a0ff98
 
 
 
 
 
 
cf0d2b5
 
 
 
 
 
 
 
 
 
 
 
 
ba07c83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf0d2b5
 
 
 
 
ba07c83
 
 
 
 
 
 
 
cf0d2b5
 
 
 
 
 
ba07c83
 
cf0d2b5
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
# Consumer-facing dataset adapter

`agent_trajectories` has two intentionally separate adapter layers:

1. **Source adapters** acquire a pinned external release and normalize its
   benchmark-specific rows into the canonical `Trajectory` schema. They run
   during ingestion or an explicit refresh.
2. **The consumer adapter** reads only the persisted canonical library and its
   read-only metadata index. Training and evaluation jobs never import
   benchmark parsers, contact upstream hosts, or rewrite dataset files.

The stable entry point is `CanonicalDatasetAdapter`. Its API version is `1.3`;
the package version is `0.5.0`. Existing source, sampling and view interfaces
remain supported.

```python
from agent_trajectories import CanonicalDatasetAdapter

dataset = CanonicalDatasetAdapter("data/library")
print(dataset.available_benchmarks())
print(dataset.available_sources())
```

The adapter validates `manifest.json`, requires the persisted `index.sqlite`
and available canonical shards, and opens SQLite in read-only mode. A federated
release can contain full-inventory metadata while marking some payloads as
metadata-only. It keeps only lightweight selected index rows in memory.
Unsampled event payloads are parsed one trajectory at a time.

## Query contract

`DatasetQuery` fields use OR semantics within a field and AND semantics across
fields:

- `benchmarks`: stable families such as `swe-bench`, `swe-gym`, `swe-smith`,
  `terminal-bench`, `tau2-bench`, `tau3-bench`, `browsecomp`, `mind2web`, and
  `toolbench`;
- `source_ids`: exact canonical sources such as `swegym_sampled` or
  `agentsuite_tau2`;
- `source_versions`: exact immutable source revisions;
- `agent_models` and `agent_scaffolds`;
- `trajectory_ids`, `task_keys`, and compatible `environment_keys`;
- task-level library `splits`: `train`, `validation`, `test`, or
  `protected_evaluation`;
- `quality_tiers` and persisted task/environment `quality_ranks`;
- `demonstration_provenance`: `expert_or_reference_demonstration` or
  `recorded_agent_completion`;
- `curated_selections`: pinned original author training selections, enumerated
  by `available_curated_selections()`;
- `supported_views`: records must support every requested view (`full_trajectory`
  or `assistant_turn`), checked before sampling;
- dynamic `content_availability`: `hosted`, `overlay`, or `metadata_only`;
- audited `research_permissions`, `training_permissions`,
  `training_verifications`, `commercial_training_permissions`, and
  transformed `redistribution_permissions`;
- `structurally_eligible` and `training_eligible` gates;
- `selection`: `all_attempts`, `all_successful`, or `best_verified`.

The concise string aliases `all`, `successful`, and `best` are also accepted,
as are `full`/`full-trajectory` and `turn`/`assistant-turn` view names. Enum
members are preferred when static typing is available.

`DatasetQuery.for_training(...)` enables both structural and training-source
gates. This quality gate is not a legal-permission decision; combine it with
the permission fields for the downstream project's policy. `best_verified`
returns at most one successful source-evaluator or
independently reproduced trajectory per selected task. Apply an
`environment_keys` filter when alternatives from different environment
versions must not compete. Quality rank itself is always calculated within a
compatible task/environment group over the full canonical population; source
filtering never silently rewrites the stored rank.

`for_training` always excludes `protected_evaluation` task assignments, even
when a training source also contains that task. AReaL's unreconstructed contexts
are explicitly turn-only records: only their source answer is supervised,
earlier assistant messages are context, and full view raises an error. Exact
contiguous AReaL dialogs support both views. See
[v0.5.0 SFT examples and author selections](v0.5.0_sft_expansion.md).

Expert demonstrations and successful agent completions are deliberately
separate filters:

```python
experts = DatasetQuery(
    demonstration_provenance=("expert_or_reference_demonstration",),
)
successful_agents = DatasetQuery(
    demonstration_provenance=("recorded_agent_completion",),
    selection=TrajectorySelection.ALL_SUCCESSFUL,
)
```

## Full-trajectory SFT

```python
from agent_trajectories import (
    CanonicalDatasetAdapter,
    DatasetQuery,
    TrainingView,
    TrajectorySelection,
)

dataset = CanonicalDatasetAdapter("data/library")
query = DatasetQuery.for_training(
    benchmarks=("swe-gym", "swe-smith"),
    splits=("train",),
    selection=TrajectorySelection.ALL_SUCCESSFUL,
)

for example in dataset.iter_examples(query, view=TrainingView.FULL_TRAJECTORY):
    row = example.to_dict()
    model_input = row["model_input"]
    loss_mask = row["loss_mask"]
    lineage = row["metadata"]["lineage"]
    # Apply a model-specific chat template/tokenizer downstream.
```

Each full example has the complete event sequence, assistant-only
`target_event_ids`, and an aligned `loss_mask`. Outcomes, verification evidence
and ranks are in metadata, never in `model_input`.

## Assistant-turn SFT

```python
query = DatasetQuery.for_training(
    source_ids=("agentsuite_tau2",),
    splits=("train",),
)

for turn in dataset.iter_examples(query, view=TrainingView.ASSISTANT_TURN):
    row = turn.to_dict()
    assert len(row["context"]) == row["target_index"]
    assert row["target_event_id"] == row["metadata"]["lineage"]["turn_id"]
    model_input = row["model_input"]       # causal prefix only
    supervised_target = row["supervised_target"]
```

Full and turn views derive from the same canonical record, retain the same task
split and source lineage, and have equivalent assistant targets. Turn context
contains no target event, future observation, later action, outcome, or answer.

## Best trajectory and multiple completions

Select the best verified trajectory for every selected task:

```python
best = DatasetQuery(
    benchmarks=("swe-bench",),
    splits=("protected_evaluation",),
    selection=TrajectorySelection.BEST_VERIFIED,
)
for record in dataset.iter_records(best):
    print(record.metadata.task_key, record.metadata.quality_rank)
```

Request one exact canonical trajectory:

```python
record = dataset.get_trajectory("trajectory:...")
print(record.trajectory.events)
print(record.lineage())
```

Collapsed duplicate IDs are resolved to their retained canonical trajectory;
`contributing_trajectory_ids` preserves every original ID.

Enumerate all completions for a task, in quality order:

```python
first = next(dataset.metadata(DatasetQuery(source_ids=("agentsuite_tau2",))))
attempts = dataset.alternatives(first.task_key)
for attempt in attempts:
    print(
        attempt.metadata.trajectory_id,
        attempt.metadata.quality_rank,
        attempt.metadata.outcome_category,
        attempt.metadata.agent_model,
    )
```

`environment_key=` can restrict alternatives to one compatible environment.

## Deterministic sampling

```python
from agent_trajectories import SamplingConfig, SamplingStrategy

population = DatasetQuery.for_training(splits=("train",))

# Uniform trajectory sampling.
random_sample = SamplingConfig(count=1_000, seed=42)

# Uniform task sampling; the best matching attempt represents each drawn task.
task_sample = SamplingConfig(
    count=1_000, seed=42, strategy=SamplingStrategy.TASK
)

# Round-robin sources, then sample within each source.
balanced_sample = SamplingConfig(
    count=1_000, seed=42, strategy=SamplingStrategy.SOURCE_BALANCED
)

for record in dataset.iter_records(population, sampling=balanced_sample):
    print(record.metadata.trajectory_id, record.metadata.source_id)
```

Set `with_replacement=True` for repeated draws. The same persisted library,
query, seed and sampling configuration produce the same ordered IDs.
Task-level sampling prevents tasks with many recorded attempts from dominating.
Source-balanced sampling distributes draws round-robin across non-empty sources
and deterministically redistributes unused capacity when a source is exhausted.

## Streaming and batching

```python
for batch in dataset.iter_batches(
    8,
    DatasetQuery.for_training(splits=("train",)),
    view=TrainingView.ASSISTANT_TURN,
):
    rows = [example.to_dict() for example in batch]
    print(len(rows), rows[0]["sample_id"])
```

These are bounded Python batches, not tensors. Canonical storage stays
framework-independent and downstream code retains control of templates,
tokenization, truncation, packing and collation.

PyTorch is optional and imported lazily:

```python
torch_dataset = dataset.as_torch_iterable(
    DatasetQuery.for_training(splits=("train",)),
    view=TrainingView.ASSISTANT_TURN,
)

# Standard torch DataLoader worker processes are sharded by item index.
from torch.utils.data import DataLoader
loader = DataLoader(torch_dataset, batch_size=None, num_workers=2)
```

The core package has no ML-framework dependency. Install the optional extra
only when needed: `pip install 'agent-trajectory-datasets[torch]'`.

## Evaluation over all trajectories

Task splits are assigned once by canonical `task_key`, then joined into every
source and both derived views. A task cannot appear in more than one of
`train`, `validation`, `test`, and `protected_evaluation`.

```python
evaluation = DatasetQuery(
    benchmarks=("tau2-bench",),
    splits=("validation", "test", "protected_evaluation"),
    selection=TrajectorySelection.ALL_ATTEMPTS,
)

for record in dataset.iter_records(evaluation):
    print(record.metadata.task_key, record.trajectory.outcome.success)
```

For all references, source verdicts and verification evidence associated with
one task:

```python
task = next(dataset.metadata(evaluation)).task_key
bundle = dataset.evaluation_bundle(task, query=evaluation)
for reference in bundle.references:
    print(
        reference.trajectory_id,
        reference.outcome.success,
        reference.verification.method,
        reference.verification.evidence,
        reference.supervised_targets,
    )
```

Historical source outcomes are evaluation references, not scores for a new
model. Native environment success still requires running the corresponding
benchmark evaluator. Unknown outcomes remain unknown rather than being counted
as failures.

## Metadata and lineage

Every `DatasetRecord` carries `TrajectoryMetadata`, including:

- canonical task, trajectory and environment IDs;
- benchmark family, source ID, immutable revision, upstream record locator and
  canonical/source split;
- agent model and scaffold;
- quality tier, numeric score and within-task quality rank;
- structural/training eligibility;
- current payload availability and the complete source permission audit,
  including verification state, commercial-training status and conditions;
- outcome category, reward, verification method/strength and independent-replay
  status;
- every duplicate source trajectory ID collapsed into the canonical record.

`record.lineage()` adds the complete `SourceRef`, producer provenance, source
outcome and full verification evidence. Derived examples store that object at
`example.metadata["lineage"]`; assistant-turn examples also store `turn_id` and
full examples store all supervised `turn_ids`.

## Federated payloads and authorized overlays

`available_sources()` enumerates the complete indexed inventory;
`content_sources()` lists sources whose event payload is currently readable.
Inspect one permission record without loading trajectories:

```python
rights = dataset.permissions("agentsuite_tau2")
print(rights.dimensions["model_training"])
print(dataset.content_availability("agentsuite_tau2"))
```

When a project is separately authorized to retrieve a metadata-only source,
run its explicit pinned source adapter and provide the resulting canonical
file or directory as an overlay:

```python
dataset = CanonicalDatasetAdapter(
    "./sft-benchmark-trajectories",
    content_overlays={
        "agentsuite_tau2": "./authorized/canonical/agentsuite_tau2",
    },
)

query = DatasetQuery(
    source_ids=("agentsuite_tau2",),
    content_availability=("overlay",),
)
for record in dataset.iter_records(query):
    ...
```

The overlay is read-only and is not copied or uploaded. Canonical IDs join it
to the hosted full-inventory index. Selecting records whose payload is still
absent raises `MissingTrajectoryContentError` with the missing source IDs;
metadata queries never silently discard them.

## Initial ingestion and explicit refresh

Normal consumption performs no downloads. Initial ingestion is a separate,
explicit operation. For a hosted release:

```bash
.venv/bin/python scripts/import_hf_release.py SOURCE_ID DATASET_ID \
  --revision IMMUTABLE_SHA \
  --output data/full/canonical/OUTPUT \
  --cache data/cache/full/OUTPUT \
  --config CONFIG --split SPLIT

.venv/bin/python scripts/build_complete_library.py \
  --input-dir data/full/canonical/OUTPUT \
  --output data/library
```

The complete multi-source build command and source-specific revisions are in
the root README and `docs/trajectory_sources.md`.

A refresh is never implicit. Choose and audit a new upstream immutable SHA and
write it to a new canonical output directory. For an existing published
library, use the append workflow; it copies the old SQLite index, reads only
the new canonical shards, preserves all old score rows and shard bytes, and
updates only affected task assignments:

```bash
.venv/bin/python scripts/import_hf_release.py SOURCE_ID DATASET_ID \
  --revision NEW_IMMUTABLE_SHA \
  --output data/full/canonical/OUTPUT_NEW_SHA \
  --cache data/cache/full/OUTPUT_NEW_SHA \
  --config CONFIG --split SPLIT

# Review release-manifest.json and rejects before appending.
.venv/bin/python scripts/append_library.py \
  --base data/library \
  --input-dir data/increment-v0.4.0/canonical \
  --output data/library-v0.4.0 \
  --release v0.4.0
```

`append_report.json` explicitly records the base manifest hash, accepted and
duplicate counts, affected tasks, and that base scores and shards were not
reprocessed. This separation makes changes reviewable and keeps training runs
pinned to the manifest and shard hashes they actually consumed.