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

# Select, reduce, and order executions

> Compare retained executions, remove unnecessary commands, and test command order through measured execution.

After acquisition, use `confirmed_execution` to compare sequences that Core has already acquired. Each comparison executes the candidates in your environment and returns measured objectives. The application supplies repeatable contexts; Core supplies the candidates and retains the selected execution.

This guide continues the two-axis example in [Configuration](/docs/machina/configuration). It uses the same `post`, `trajectory`, and `create_stage` helpers, `ACQUISITION_DOMAIN`, and `PREFIX`. The application observes `[x, y, vx, vy]`, accepts two normalized command values in `[-1, 1]`, and holds each command for `0.5` seconds.

## Export the acquired executions

Finish pending acquisition observations and stop acquisition writes before exporting. Retrieve every page, retain the API-generated record IDs, and carry the returned `incumbent_id` into the next configuration.

```python theme={null}
def export_executions(domain):
    records = []
    offset = 0
    expected_total = None
    incumbent_id = None

    while True:
        page = trajectory(domain, "records", {
            "best_only": True,
            "offset": offset,
            "limit": 64,
        })
        if expected_total is None:
            expected_total = page["total"]
            incumbent_id = page["incumbent_id"]
        elif (page["total"] != expected_total
              or page["incumbent_id"] != incumbent_id):
            raise RuntimeError("Acquisition changed during export; export again.")

        batch = page["records"]
        records.extend(batch)
        offset += len(batch)
        if offset == expected_total:
            break
        if not batch or offset > expected_total:
            raise RuntimeError("Unexpected records pagination.")

    if not 1 <= len(records) <= 512:
        raise RuntimeError("A structural stage needs 1–512 executions.")
    ids = [record["id"] for record in records]
    if len(set(ids)) != len(ids) or incumbent_id not in ids:
        raise RuntimeError("Export is missing unique IDs or its incumbent.")

    records.sort(key=lambda record: record["id"])
    return records, incumbent_id


records, incumbent_id = export_executions(ACQUISITION_DOMAIN)
```

The export response fields used here are `records`, `total`, and `incumbent_id`. Each execution carries `id`, `actions`, `initial_state`, and its initial measurement validity (`initial_valid`). Preserve these fields during transfer. Do not replace the returned IDs with array positions or manufacture a new incumbent.

| Execution record field | Contract                                                                                                                                                                            |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`                   | Required nonnegative integer.                                                                                                                                                       |
| `actions`              | Required numeric matrix. The generic record schema allows 1–257 rows and 1–128 values per row; the example's action contract is stricter: at most 8 rows, exactly 2 values per row. |
| `initial_state`        | Required numeric vector with 1–128 values; exactly 4 for this example.                                                                                                              |
| `initial_valid`        | Boolean; defaults to `true` when omitted. Preserve the exported value.                                                                                                              |

These later Domains start with the acquired executions explicitly transferred into them. Create a separate Domain for each intervention so that each stage's configuration and selected result remain inspectable.

## Configure a structural stage

| Configuration field | Contract                                                                                                         |
| ------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `mechanism`         | Required: `"confirmed_execution"`.                                                                               |
| `executions`        | Required: 1–512 execution records.                                                                               |
| `incumbent_id`      | Required: nonnegative integer identifying the current execution among the supplied records.                      |
| `intervention`      | `"selection"`, `"deletion"`, or `"ordering"`; default `"selection"`.                                             |
| `command_budget`    | Integer from 1 to 256; default 256. This example uses 8.                                                         |
| `objective_names`   | Required: 1–8 nonblank names, each at most 128 characters. Order defines the meaning of each feedback objective. |
| `max_contexts`      | Integer from 1 to 64; default 64.                                                                                |

`selection` compares acquired executions. `deletion` tests removing commands. `ordering` tests command order. In all three cases, execute the returned candidates and report their outcomes before accepting the stage's selected execution.

```python theme={null}
def configure_structural_stage(domain, intervention, records, incumbent_id):
    create_stage(domain, {
        "mechanism": "confirmed_execution",
        "executions": records,
        "incumbent_id": incumbent_id,
        "intervention": intervention,
        "command_budget": 8,
        "objective_names": ["completion"],
        "max_contexts": 4,
    })
```

The structural configuration does not take `state_dimensions`, `action_dimensions`, or action-bound fields. It receives the actual acquired execution records. Keep the action adapter and its bounds consistent with acquisition.

## Make contexts repeatable

A `context_id` is an application identifier, not a state vector or a command to reset the environment. Your application must map it to a reproducible scenario, including its initial position, velocity, target, and relevant environment randomness. Reset that scenario before **every** candidate execution.

The following adapter illustrates the required boundary. `reset_from_context_id` and the returned environment object's methods are application hooks, not Adapt-1 SDK methods. Implement them for your simulator or device. The neutral-padding rule shown here must also be used during acquisition: each trial has eight command slots, and a shorter candidate spends the remaining slots under the declared neutral command.

```python theme={null}
import math


def reset_from_context_id(context_id):
    # Load your saved scenario specification, reset the environment, and return
    # an object implementing hold_command(command, duration) and completion().
    raise NotImplementedError("Connect this to your environment reset.")


def execute_candidate(execution, context_id):
    actions = execution["actions"]
    if not 1 <= len(actions) <= 8:
        raise ValueError("Candidate exceeds the configured command budget.")
    for action in actions:
        if len(action) != 2 or any(
            not math.isfinite(value) or not -1 <= value <= 1
            for value in action
        ):
            raise ValueError("Candidate violates the two-axis action contract.")

    env = reset_from_context_id(context_id)
    for action in actions:
        env.hold_command(action, duration=0.5)
    for _ in range(8 - len(actions)):
        env.hold_command([0.0, 0.0], duration=0.5)

    # completion() uses the shared distance, speed, and safety-stop contract.
    # One value, in the same order as objective_names=["completion"].
    return [float(env.completion())]
```

For hardware, the adapter also owns fixed command limits and termination handling. Apply the same declared rules to every candidate. A command being removed does not imply an arbitrary change to the trial's observation window.

Use the completion definition from [Schemas and configuration](/docs/machina/configuration): distance at most `0.05` metres and speed at most `0.1` metres/second at the declared assessment time, with safety stops returning `False`. `hold_command` must stop physical actuation after a terminal event; further calls must not restart the device or simulator.

## Run nomination and confirmation

Use one set of contexts for nomination, then a separate set for confirmation. For each proposal, evaluate every returned candidate on every supplied context. The candidate count can change between proposals; derive it from the response each time.

```python theme={null}
def compare_candidates(domain, request_id, context_ids, reference_state):
    if not 1 <= len(context_ids) <= 4:
        raise ValueError("Use 1–4 contexts for this configuration.")
    if len(set(context_ids)) != len(context_ids):
        raise ValueError("Context IDs must be unique within a comparison.")

    proposal = trajectory(domain, "propose", {
        "state": reference_state,
        "goal": [0.0],
        "mode": "explore",
        "request_id": request_id,
        "context_ids": context_ids,
    })
    candidates = proposal["candidates"]
    if not candidates:
        raise RuntimeError("Proposal returned no candidates.")

    outcomes = []
    for candidate_index, candidate in enumerate(candidates):
        for context_id in context_ids:
            objectives = execute_candidate(candidate["execution"], context_id)
            outcomes.append({
                "candidate_index": candidate_index,
                "context_id": context_id,
                "objectives": objectives,
            })

    return trajectory(domain, "observe", {
        "decision_id": proposal["decision_id"],
        "outcomes": outcomes,
    })
```

The shared `propose` request requires `state` and `goal`. For these structural comparisons, the client pattern uses an exported execution's `initial_state` and the placeholder goal `[0.0]`; measured `objectives` supply the comparison outcome. The placeholder is not the environment's target. The target is part of each reset context.

`request_id` identifies the proposal. Calling it `nomination-v1` does not set a phase flag: there is no `phase` field in this request. Complete the first proposal's observation before requesting the confirmation comparison.

The `candidate_index` is the position in that proposal's `candidates` array. It is distinct from an execution record's `id`. Keep the returned `decision_id` attached to the entire result batch. Do not submit only a winner, an average, or a partial candidate/context matrix.

Each outcome requires `candidate_index` (integer, 0–4095), `context_id` (a nonblank string of at most 128 characters), and `objectives` (a numeric vector). Send one objective per configured name, in that exact order. The request schema allows 1–32768 outcome rows; numeric values must be finite and within `[-1e12, 1e12]`. The single completion objective in this example is `0.0` or `1.0`.

If execution is interrupted, preserve the proposal and measurements so that you can finish the batch. If you abandon it, cancel the pending decision using `trajectory(domain, "cancel", {"decision_id": decision_id})`; cancellation supplies no learning outcome.

## Carry the selected execution into the next stage

Register the context IDs below in your application before running this loop. Each ID must resolve to its own saved scenario. The nomination and confirmation sets are disjoint, and the next intervention starts in a new Domain.

```python theme={null}
structural_domains = {}

for intervention in ("selection", "deletion", "ordering"):
    domain = f"{PREFIX}-{intervention}"
    structural_domains[intervention] = domain
    configure_structural_stage(domain, intervention, records, incumbent_id)

    for phase in ("nomination", "confirmation"):
        context_ids = [f"{intervention}-{phase}-{i}" for i in range(4)]
        compare_candidates(
            domain=domain,
            request_id=f"{phase}-v1",
            context_ids=context_ids,
            reference_state=records[0]["initial_state"],
        )

    stage_state = trajectory(domain, "state", {})
    selected = stage_state["selected_execution"]
    if not selected:
        raise RuntimeError("Stage did not return a selected execution.")
    records = [selected]
    incumbent_id = selected["id"]

base_execution = records[0]
```

The application transfers Core's `selected_execution` unchanged. It does not sort candidates by its own aggregate metric and choose a replacement. Keep `base_execution` available for the next stage: [Contextual refinement](/docs/machina/refinement).
