# Docs > Documentation for SignalFlag, the test infrastructure platform for physical AI SignalFlag is the test infrastructure platform for physical AI. These docs cover setting up the platform, running test batches, integrating with CI, building metrics, and consuming results via the CLI, SDK, MCP server, and web app. They also include reference material for the open-core libraries and conceptual explanations of simulation-based evaluation. # Tutorials # Tutorials Hands-on walkthroughs that take you from zero to working results. ~5 min Step 1 See SignalFlag Working in Five Minutes Run one command to fill a project with real test results, an A/B comparison, and a dashboard. Nothing to configure. [Start tutorial →](./sdk-demo/) ~15 min Deep dive Bootstrap a Demo Project with the CLI The same command in full: every flag, and a section on each demo detailing its topics, metrics, status checks and dashboard. [Read the reference →](./demo-projects/) ~10 min Step 2 Get Your First Metrics in SignalFlag Use the Python SDK to push data from your own machine and see metrics in the dashboard. No Docker or cloud infrastructure needed. [Start tutorial →](./first-external-batch/) ______________________________________________________________________ Once you've completed the tutorials, the [How-to Guides](../setup/) cover bringing your own system, experiences, and metrics into SignalFlag. # See SignalFlag Working in Five Minutes This tutorial runs a demo that fills a SignalFlag project with real test results, so you can see what the platform does before connecting anything of your own. No Docker, no container registry, no config to write. One command. **Time:** about 5 minutes, plus a few minutes of waiting for metrics. **Before you start:** - You have a SignalFlag account. Sign up at [app.signalflag.ai/signup](https://app.signalflag.ai/signup) if you don't. - You have Python 3.10 or newer. - You can open a browser to authenticate. ______________________________________________________________________ ## What you're building The demo replays test data from a real navigation project into your own SignalFlag project. When it finishes you'll have: - **Two batches of tests**, one per version of the navigation stack. The same scenarios ran in both, so every test has a counterpart in the other batch. - **Metrics on every test**: speed and localization error over time, goal state timelines, pass/fail checks, and more, with camera footage on the tests that recorded it. - **The files each run produced**, attached to the test they came from, so the raw material sits next to the charts drawn from it. - **An A/B comparison** between the two batches, showing which scenarios regressed and which improved. - **A dashboard** comparing the two versions across every run of them. That's the navigation demo. A second one replays MuJoCo policy evaluations — see [Choosing a demo](#choosing-a-demo) below. ______________________________________________________________________ ## Step 1: Install the SDK Shell ``` pip install signalflag ``` The SDK used to be published as `resim-sdk`. That name still installs and works; `signalflag` is the same package and the one to use from here on. ______________________________________________________________________ ## Step 2: Run the demo Shell ``` signalflag-demo --demo navigation ``` The package also installs `resim-demo`, an alias for the same command, so anything already scripted against the old name keeps working. First it downloads the test data it replays, reporting progress as it goes. That happens once — later runs reuse the cached copy. Then it asks you to authenticate in a browser: Output ``` Authenticating by Device Code Please navigate to: https://resim.us.auth0.com/activate?user_code=XXXX-XXXX ``` Visit that URL, sign in, and the demo continues on its own. Subsequent runs reuse the cached token. Each demo works in a project of its own, creating it if it doesn't exist, so it won't touch your real projects. The navigation demo uses one called `SignalFlag SDK Demo`. To use a different one: Shell ``` signalflag-demo --demo navigation --project-name "my project" ``` ### Choosing a demo `--demo` picks which demo to run. There's no default — running `signalflag-demo` on its own lists the ones that ship: Shell ``` signalflag-demo ``` | `--demo` | What it replays | | ------------ | ------------------------------------------------------------------------------------------------------------------------------------ | | `navigation` | A robot running errands around a hospital. Dense telemetry across 34 scenarios, covering almost every chart type SignalFlag renders. | | `mujoco` | An ALOHA bimanual manipulation policy evaluated in MuJoCo, one test per cube placement, compared across two policy builds. | Each lands in its own project and on its own branch, so running both leaves you with two independent sets of results to look at. [Bootstrap a Demo Project with the CLI](../demo-projects/) details what each one contains, metric by metric. ______________________________________________________________________ ## Step 3: Follow the four links When the demo finishes it prints where to go: Output ``` SignalFlag SDK demo complete. Batch A (baseline, nav-v2.0.0) https://app.signalflag.ai/projects/.../batches/... Batch B (candidate, nav-v3.0.0) https://app.signalflag.ai/projects/.../batches/... A/B comparison https://app.signalflag.ai/projects/.../batches/.../compare-batch/batch/... Trends dashboard https://app.signalflag.ai/projects/.../dashboards/... Metrics are computed after each batch closes, which takes a few minutes. Reload these pages when it finishes. ``` Metrics are computed once each batch closes, so the pages look empty at first. Give it a couple of minutes and reload. ### Batch A and Batch B Each batch page lists its tests with a pass, warning, or blocker status. Open any test to see its metrics: speed over time, distance to each goal, what the navigation stack was doing as a state timeline, a table judging whether the localizer's confidence was honest, and on some tests the onboard camera footage. The **Events** tab shows the moment the robot reached its goal, and the **Logs** tab holds the files that run produced. Batch-level metrics sit on the batch page itself, aggregating across every test. ### The A/B comparison This is the page that answers "did this version make things better or worse". Metrics are matched by name between the two runs, so each chart from Batch A sits next to the same chart from Batch B. **Merged Metrics** goes further and draws both runs on the same axes. The **Tests** tab is the fastest read: it groups the scenarios by how their outcome differs between the two batches, so the regressions and the fixes are each their own list. See the [A/B comparison guide](../../guides/ab-comparison/) for the full picture. ### The dashboard The batches show you two runs. The dashboard aggregates across them, grouped by build version: how each version's tests turned out, its mean localization error, and how many tests have run. Run the demo again and those bars take in the new runs too. ______________________________________________________________________ ## Next steps - **See what else the demos contain.** [Bootstrap a Demo Project with the CLI](../demo-projects/) documents every flag of the command and details both demos: their topics, every metric, their status checks and dashboards. - **Emit your own data.** [Get Your First Metrics in SignalFlag](../first-external-batch/) walks through the same API the demo uses, starting from an empty script. - **Write your own metrics.** Start with the [metrics guide](../../guides/metrics/), and develop them against a debug dashboard before running a batch. # Bootstrap a Demo Project with the CLI One command fills a SignalFlag project with real test results — batches of tests, metrics computed on them, and a trends dashboard. The demos replay data captured from evaluations that actually ran, so what you get is a working project to explore rather than a screenshot tour. There is nothing to configure, no Docker, and no build to register. Three demos ship today. Two compare two versions of the same system head to head — an A/B pair, with a comparison page between the batches. The third, `session`, is a different shape: real field sessions from one system, replayed one batch per session and trended over time rather than paired off. Each demo lands in its own project, so you can run all three and leave them side by side. This page walks through the command, then details exactly what each demo puts in your account. **Time:** about 5 minutes per demo, plus a few minutes of waiting for metrics. **Before you start:** - You have a SignalFlag account. Sign up at [app.signalflag.ai/signup](https://app.signalflag.ai/signup) if you don't. - You have Python 3.10 or newer. - You can open a browser to authenticate. Looking for the short version? [See SignalFlag Working in Five Minutes](../sdk-demo/) is install, run, look — the fastest path to something on screen. This page is the same command documented in full, plus a section on each demo's contents. ______________________________________________________________________ ## What you're building The navigation and MuJoCo demos give you the same shape of results: - **Two batches of tests**, run against two versions of the same system. Both batches run the same experiences, which is what pairs every test with its counterpart in the other batch. - **Metrics on every test**, computed from the replayed data by a metrics config that ships inside the package. - **The files the runs produced**, attached to the tests that made them, so the raw material sits next to the charts drawn from it — on every MuJoCo test, and on the navigation tests that recorded camera footage. - **An A/B comparison** between the two batches, showing which experiences regressed and which improved. - **A trends dashboard** that groups results by build version and takes in every run of the demo, not just this one. The `session` demo gives you a different shape, because it is answering a different question — not "did build A beat build B" but "how did today's session compare to the last several": - **Four batches, one per field session**, each holding exactly one test — the whole session, not one scenario cut out of it. - **Every session's raw recording attached to its test** — the mcap snippets and clip GIFs a real robotics session produces, not synthetic stand-ins. - **A system, and every session's experience tagged**, so they show up together in the project's [Sessions](../../guides/sessions/) library — this demo's real trend view, so there is no metrics dashboard. ______________________________________________________________________ ## Step 1: Install the CLI Shell ``` pip install signalflag ``` The wheel installs the demo as a console script under two names, `signalflag-demo` and `resim-demo`. They are the same command — `resim-demo` is kept so anything already scripted against the old package name keeps working. `python -m signalflag.demo` runs it too. The SDK used to be published as `resim-sdk`. That name still installs and works; `signalflag` is the same package and the one to use from here on. ______________________________________________________________________ ## Step 2: See which demos ship `--demo` has no default. The demos are peers, so running one you didn't ask for would be a surprise. Run the command with no arguments and it lists what is on offer instead: Shell ``` signalflag-demo ``` Output ``` signalflag-demo replays real test data into your own ReSim project. Pick one with --demo: mujoco An ALOHA bimanual manipulation policy in MuJoCo: one test per cube placement, compared across two policy builds. navigation A hospital navigation suite: dense telemetry across 34 scenarios, covering every chart type ReSim ships. session Four real field sessions from a legged robot: GNSS, IMU and gait telemetry, one batch per session on a shared branch. For example: signalflag-demo --demo navigation ``` Each demo has its own project, branch and metrics config, so running all three leaves you with three independent sets of results, and none goes near your real projects: | `--demo` | Project | Branch | Batches | Data to download | | ------------ | ---------------------------------------- | --------------------------- | ------------ | ---------------- | | `navigation` | `SignalFlag SDK Demo` | `sdk-demo` | 2 × 34 tests | ~7 MB | | `mujoco` | `SignalFlag SDK Demo (MuJoCo)` | `sdk-demo-mujoco` | 2 × 20 tests | ~110 MB | | `session` | `SignalFlag SDK Demo (Logs to Insights)` | `sdk-demo-logs-to-insights` | 4 × 1 test | ~950 MB | [The navigation demo](#the-navigation-demo), [the MuJoCo demo](#the-mujoco-demo) and [the session demo](#the-session-demo) below go through what each one contains, metric by metric. ______________________________________________________________________ ## Step 3: Bootstrap the demo Shell ``` signalflag-demo --demo navigation ``` Four things happen, in this order. **It fetches the data it replays.** Each demo's data is a single tarball in a public bucket, pinned by checksum and cached after the first run. The download comes before the login on purpose: there is no point sending you through a browser only to fail on a download afterwards. Output ``` Downloading demo data (7 MB) 7 / 7 MB (100%) Checking it downloaded intact ``` **It authenticates you.** The first run opens a device-code login. Later runs reuse the cached token. Output ``` Authenticating by Device Code Please navigate to: https://resim.us.auth0.com/activate?user_code=XXXX-XXXX ``` Visit that URL, sign in, and the demo continues on its own. **It creates the project, the branch and the dashboard.** The project is created only if it doesn't already exist. Syncing the demo's metrics config is what creates the branch and the dashboard along with it. Output ``` Creating project 'SignalFlag SDK Demo' ``` **It replays the two batches.** Every test is created, its emissions and events are pushed through the same typed SDK calls you would use for your own data, its files are attached, and it is closed. Output ``` Running batch A: Nav stack v2 (baseline) (34 tests) Hospital East Hallway Navigation From North Hallway - Bright with Pedestrians Hospital East Hallway Navigation From North Hallway - Bright without Pedestrians ... Running batch B: Nav stack v3 (candidate) (34 tests) ... ``` Both batches land on one branch. A dashboard is scoped to a single branch, so sharing one is what lets a single dashboard trend across both; the batches are told apart by their build version instead. ______________________________________________________________________ ## Step 4: Follow the four links When it finishes, the demo prints where to go: Output ``` SignalFlag SDK demo complete. Batch A (baseline, nav-v2.0.0) https://app.signalflag.ai/projects/.../batches/... Batch B (candidate, nav-v3.0.0) https://app.signalflag.ai/projects/.../batches/... A/B comparison https://app.signalflag.ai/projects/.../batches/.../compare-batch/batch/... Trends dashboard https://app.signalflag.ai/projects/.../dashboards/... Metrics are computed after each batch closes, which takes a few minutes. Reload these pages when it finishes. ``` Metrics are computed once each batch closes, so the pages look empty at first. Give it a couple of minutes and reload. - **Batch A and Batch B** list their tests with a pass, warning or blocker status. Open any test for its metrics, plus an **Events** tab and a **Logs** tab wherever that run recorded something for them. - **The A/B comparison** matches metrics by name between the two runs, so each chart from Batch A sits next to the same chart from Batch B. The **Tests** tab groups experiences by how their outcome differs, which puts the regressions and the fixes in their own lists. See the [A/B comparison guide](../../guides/ab-comparison/). - **The dashboard** aggregates across runs rather than showing one, grouped by build version. Run the demo again and the same bars take in the new runs too. ______________________________________________________________________ ## Command reference ### Flags | Flag | Default | What it does | | ------------------------------------ | -------------- | ---------------------------------------------------------------------------------- | | `--demo {mujoco,navigation,session}` | none | Which demo to run. Required. | | `--project-name` | the demo's own | Project to run in, created if it does not exist. | | `--branch` | the demo's own | Branch to create every batch on. | | `--data-dir` | none | Replay an already-extracted bundle from this directory instead of downloading one. | | `--quiet` | off | Only report failures. | Passing any of the other flags without `--demo` is an error rather than a listing, because dropping your argument and exiting successfully would read as though the run had happened: Output ``` signalflag-demo: error: --demo is required when passing --project-name ``` To keep a demo out of the default project, name your own: Shell ``` signalflag-demo --demo navigation --project-name "my project" ``` ### Where the data is cached Each demo's bundle is downloaded once and cached under its own key, so switching demos does not evict the other's data. The cache root honours `XDG_CACHE_HOME` and otherwise sits under `~/.cache`: - `~/.cache/resim/sdk-demo/navigation-v1/` - `~/.cache/resim/sdk-demo/mujoco-v4/` - `~/.cache/resim/sdk-demo/session-v1/` Every bundle is pinned by sha256. A download that does not match its expected digest is refused rather than replayed, and the archive is checked for unsafe member paths before anything is extracted. Delete a cache directory to force a fresh download. ### Running without a download `--data-dir` points the demo at an already-extracted bundle — useful on a restricted network, or to re-run repeatedly without touching the cache: Shell ``` signalflag-demo --demo mujoco --data-dir ./extracted-bundle ``` The directory must contain the bundle's `manifest.json` at its root. ### Exit codes | Code | Meaning | | ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | `0` | The demo ran, or a bare invocation listed the demos. | | `1` | The replay data could not be fetched or used, or contact with SignalFlag was lost. Batches already created stay in the app; re-run to start a fresh pair. | | `2` | Bad arguments — an unknown `--demo`, or another flag passed without `--demo`. | ### Calling it from Python Useful when you want the IDs back rather than reading them off the terminal: Python ``` from signalflag.demo import DEMOS, run result = run(demo="navigation") result.project_id # the project it used or created result.batch_ids # {"a": ..., "b": ...} result.dashboard_id # None if the dashboard could not be resolved result.urls # {"batch_a": ..., "batch_b": ..., "compare": ..., "dashboard": ...} DEMOS.keys() # dict_keys(['navigation', 'mujoco', 'session']) ``` `session` has four batches rather than two, so its `result.batch_ids` has four keys — the four session dates. It has no dashboard, so `result.dashboard_id` is always `None` and `result.urls` has no `"compare"` or `"dashboard"` key; it has a `"sessions"` entry instead, pointing at the project's Sessions library. `run()` takes the same options as the command line — `project_name` positionally, then `demo`, `branch`, `data_dir` and `quiet` as keywords, plus a `client` if you would rather authenticate yourself than be sent to a browser. It raises `signalflag.demo.DemoDataError` when the replay data cannot be fetched. ______________________________________________________________________ ## The navigation demo Shell ``` signalflag-demo --demo navigation ``` A mobile robot running errands around a hospital. This is the fuller tour of the two: the source data is dense telemetry, and the config that reads it draws nine of the ten system templates — everything but `artifact` — plus two custom ones. Start here if you want to see what the platform renders. ### What lands in your project | | | | ----------- | --------------------------------------------------------------------- | | Project | `SignalFlag SDK Demo` | | Branch | `sdk-demo` | | Batch A | **Nav stack v2 (baseline)**, build version `nav-v2.0.0`, 34 tests | | Batch B | **Nav stack v3 (candidate)**, build version `nav-v3.0.0`, 34 tests | | Metrics set | `Demo Metrics` — 13 test metrics and 5 batch metrics | | Dashboard | `SDK Demo Trends`, from the `Demo Trends` set, over a rolling 30 days | Each test is one scenario: a route through the hospital, at one of three lighting levels, with or without pedestrians — `Hospital East Hallway Navigation From North Hallway - Bright with Pedestrians`, and so on. The same 34 run in both batches, so every test pairs with its counterpart in the A/B view. Seventeen of them have pedestrians in them, and eleven carry camera footage — the same eleven on both sides, so the media metrics appear on both halves of those pairs. Pass and fail are not copied from the source runs. They are recomputed from the config's status checks against the replayed data, which works out as 16 passed, 9 warned and 9 blocked in Batch A against 15, 8 and 11 in Batch B. Seven scenarios change outcome between the two — four get worse, three get better — and those are the ones that land in the comparison's **Failing on just one batch** group. The rest divide between the groups either side of it, so none of the four comes up empty. ### The data it replays Thirteen topics, declared in the demo's config and emitted per test: | Topic | Fields | What it carries | | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | | `odom_linear_velocity` | `x`, `y`, `z` | Robot velocity from the drive stack. | | `goal_distance` | `goal_name`, `distance_m` | Distance to each named goal, over the run. | | `time_to_goal` | `goal_name`, `time_s` | Time taken to reach each goal. One row per goal actually reached. | | `goal_count` | `count` | How many goals the run was asked to reach. | | `goal_status` | `state` | What the navigation stack was doing, as a discrete state. | | `nearest_human_distance` | `person_name`, `distance_m` | Distance to the nearest tracked person. Only the 17 scenarios with pedestrians emit it. | | `pose_difference` | `position_diff_m` | Gap between wheel odometry and the localizer's pose estimate. | | `localization_uncertainty` | `cov_x`, `cov_xy`, `cov_y`, `cov_yaw`, `position_uncertainty_m`, `yaw_uncertainty_rad` | The localizer's own confidence in that estimate. | | `covariance_accuracy` | `mahalanobis_distance`, `normalized_innovation_squared`, `normalized_x`, `normalized_y`, `normalized_yaw`, `position_error_m`, `within_1_sigma`, `within_2_sigma`, `within_3_sigma`, `yaw_error_rad` | Whether that confidence is honest — true error against reported covariance. | | `robot_trajectory` | `raw_metric` | A Plotly figure the test rendered itself. | | `camera_video` | `camera_name`, `filename` (video) | The onboard camera clip. | | `camera_frame` | `camera_name`, `filename` (image) | A still pulled from that clip. Separate from `camera_video` because image and video columns cannot share a topic. | | `goal_reached` | event: `name`, `description`, `status`, `tags` | One event each time the robot reaches a goal. | ### What you see on a test | Metric | Template | What it shows | | --------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | Robot Speed | line | Ground speed in m/s over the run. | | Speed Distribution | histogram | How much of the run was spent at each speed. | | Time in Speed Band | pie | Share of samples stopped (under 0.05 m/s), creeping (under 0.3 m/s) or cruising. | | Distance to Goal | line | Distance to each goal over time, one line per goal. | | Goal Status | state timeline | The navigation stack's state, as bands along the run. | | Localization Error | line | Odometry against the localizer's estimate, in metres. | | Uncertainty vs Actual Error | line | Predicted uncertainty, observed error and Mahalanobis distance on one set of axes. A localizer whose uncertainty tracks its error is one you can trust. | | Covariance Calibration | table | Sample count, the share of samples inside 1σ, 2σ and 3σ against their targets, and median NIS. | | Nearest-Human Distance | line | Distance to the nearest person. **Warns inside 1 m, blocks inside 0.5 m.** Skipped on the scenarios with no pedestrians. | | Time to Reach Final Goal | scalar (seconds) | Time taken to reach the run's goals, added up. **Blocks when the run does not reach every goal it was given**, and charges 75 s instead. | | Camera Feed | video | The onboard clip, on the 11 tests that carry one. | | Camera Frame | image | The still from that clip. | | Robot Trajectory | custom (`raw.liquid`) | Top-down view of the path the robot took, from the figure the test emitted. | Those two status checks are the whole of pass and fail here: everything else is there to be read. The config is written for runs with any number of goals, but every scenario in this data sets exactly one, so the per-goal charts draw a single line and a run either reaches its goal in 35 to 85 seconds or blocks. The **Events** tab carries a `Goal 1 Reached` event pinned to the moment the robot got there, with a `navigation` tag — on 27 of the 34 tests in Batch A and 24 in Batch B. The **Logs** tab holds the camera clip and the still frame on the eleven tests that recorded them. ### What you see on the batch | Metric | Template | What it shows | | ------------------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------ | | Mean Localization Error by Experience | bar | Average localizer error in each scenario, across the batch. | | Localization Error Spread | custom (`strip.liquid`) | Worst error per scenario, as a strip plot. | | Covariance Calibration Summary | table | Sample count, the 1σ and 2σ shares and median NIS, across every test in the batch. | | Pedestrian Proximity Incidents | bar | Per tracked person, how many scenarios came within 0.5 m (a hit) or 0.5–1 m (too close). At most one count per scenario. | | Total Time to Reach Final Goal | scalar (seconds) | Every scenario's time added up, with the same 75 s charged for a missed goal. | ### What you see on the dashboard `SDK Demo Trends` looks at every test on the branch inside a rolling 30-day window and groups by build version, so it compares versions of the stack rather than snapshotting one run: | Metric | Template | What it shows | | ----------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------- | | Localization Error by Build Version | bar | Mean localizer error per version. A taller bar than the version before it is a regression. | | Test Outcomes by Build Version | bar | How each version's tests turned out, one bar per outcome. Click a bar to open a batch that version ran in. | | Tests Run | scalar | Tests on this branch inside the window. | Run the demo again and those bars take in the new runs rather than multiplying into new points, which is what you want from a dashboard pinned to a branch. ______________________________________________________________________ ## The MuJoCo demo Shell ``` signalflag-demo --demo mujoco ``` Two ALOHA robot arms passing a cube between them, evaluated in MuJoCo. Worth a look once you have toured the navigation demo, because the shape of the data is different: a staged task with a reward ladder rather than dense telemetry, and a question — did this policy configuration get better or worse — rather than a survey of chart types. ### What lands in your project | | | | ----------- | ----------------------------------------------------------------------------- | | Project | `SignalFlag SDK Demo (MuJoCo)` | | Branch | `sdk-demo-mujoco` | | Batch A | **n_heads=16, attention re-partitioned**, build version `aloha-n16`, 20 tests | | Batch B | **n_heads=8, checkpoint default**, build version `aloha-n8`, 20 tests | | Metrics set | `ALOHA Metrics` — 9 test metrics and 5 batch metrics | | Dashboard | `ALOHA Policy Trends`, from the `ALOHA Trends` set, over a rolling 30 days | Each test is one starting placement of the cube on the table. That placement is the only thing that differs between tests, so each is named for it: `Cube start (0.099, 0.446) seed 50`. The same 20 placements run on both sides, which is what pairs every test with its counterpart. The two batches are the same policy checkpoint built two ways, differing in one hyperparameter: the number of attention heads. One matches the value the policy was trained with and the other does not, which is enough to change how often the handover completes — 8 of 20 placements solved on the re-partitioned build against 14 on the checkpoint default, with 8 placements changing outcome between them. That is the question the A/B page answers here. The task has stages rather than a single outcome. The cube gets touched, lifted, carried across, then released, and most of the metrics follow from that ladder: **no contact**, **right gripper contact**, **lifted**, **transfer attempted**, **handover complete**. ### The data it replays Eight topics: | Topic | Fields | What it carries | | ----------------- | -------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | | `summary_metrics` | `overall_success_rate`, `overall_average_sum_reward`, `overall_average_max_reward`, `total_evaluation_time`, `total_regressions` | One row per test, summarising the episode. | | `step_reward` | `reward` | The staged reward, one row per simulation step. | | `task_stage` | `state` | Which rung of the ladder the episode is on, per step. | | `cube_pose` | `x`, `y`, `z` | World position of the cube. The handover counts as complete once `x` crosses -0.10. | | `stage_timing` | `stage`, `seconds_from_start`, `seconds_from_previous`, `regressions` | One row per stage the episode reached. | | `cube_trajectory` | `raw_metric` | A Plotly figure the evaluation drew itself. | | `episode_gif` | `filename` (image) | The whole episode as a looping animation. | | `stage_reached` | event: `name`, `description`, `status`, `tags`, `metrics` | Raised the first time each stage is reached, carrying the timings that explain the transition. | ### What you see on a test | Metric | Template | What it shows | | ----------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Task Stage | state timeline | Which stage the episode was in, so a run that grasps and then drops the cube looks different from one that never grasps it. | | Reward Over Time | line | The staged reward: 1 on contact, 2 lifted, 3 transfer attempted, 4 handover complete. | | Handover Progress | line | How far the cube is past the handover line. Zero is the line; the handover completes once this goes positive. | | Cube Height | line | The cube sits at 0.05 m on the table, so a rise is the lift and a drop back is a lost grasp. | | Episode Summary | table | Handover completed, furthest stage, episode length, sum reward, ladder regressions. **Warns when the handover did not complete.** | | Episode Replay | image | The looping animation of the attempt. | | Cube Path | custom (`raw.liquid`) | Top-down view of the cube's path, coloured by stage. The only chart that shows the shape of the motion rather than one axis of it against time. | | Stage Latency | bar | Simulated seconds from the start of the episode to each stage it reached. A bar rather than a table column so an A/B comparison can overlay two runs on one set of axes. | | Stage Timeline | table | Each stage reached, when, how long the stage before it took, and how many times the episode had fallen back by then. | Completing the handover passes and anything short of it warns. Nothing blocks: a cube placement the policy cannot solve is not a broken build. Every test carries two files on its **Logs** tab. `transfer_cube.mcap` goes up as robotics data, and uploading it as the *kind* of file it is rather than as bytes is what lets it open in the viewer inline instead of only offering a download. `episode.gif` goes up as a generic log, and reaches the page by a different route: the **Episode Replay** metric finds it by the filename the `episode_gif` topic emits. Your own tests attach files the same way; see [Attaching files](../../guides/resim-sdk/#attaching-files). The **Events** tab carries one event per stage the episode first reached — `Cube Contacted`, `Cube Lifted`, `Transfer Attempted`, `Handover Complete` — each one carrying the time to that stage, the time spent in the previous one, and the regressions so far. ### What you see on the batch | Metric | Template | What it shows | | --------------------------- | --------- | ----------------------------------------------------------------------------------------------- | | Mean Time Per Stage | bar | Average simulated seconds each stage took, across the placements that reached it. | | Seeds Reaching Each Stage | bar | How many placements got as far as each stage. | | Furthest Stage Distribution | pie | How far the policy got, as a share of the batch. | | Run Summary | table | Placements evaluated and solved, mean sum reward, mean episode length, mean ladder regressions. | | Reward Distribution | histogram | Spread of total episode reward across the batch. | ### What you see on the dashboard `ALOHA Policy Trends` groups by build version, so each policy configuration becomes one category. Every bar here is click-through: select one to open a batch that build ran in. | Metric | Template | What it shows | | --------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Success Rate by Build Version | bar | Share of placements where the handover completed. The headline number a policy change is trying to move. | | Test Outcomes by Build Version | bar | How each build's tests turned out, one bar per outcome. | | Furthest Stage by Build Version | bar | Where each build's placements ended up on the ladder. A build can hold its pass count while its failures move between stages, and that shift is the more informative signal. | | Time to Handover by Build Version | bar | Mean seconds to complete the handover, counting only the placements that completed it. Separates getting there from getting there quickly. | | Reward by Build Version | bar | Mean total episode reward. A build that drops here has regressed, whatever its pass count says. | | Trend Summary | table | Builds compared, tests run, batches, inside the window. | ______________________________________________________________________ ## The session demo Shell ``` signalflag-demo --demo session ``` Four real field sessions from a legged robot walking outdoors, captured on four different days. This demo is not an A/B pair — there is no build to compare against another — so it answers a different question than the other two: not "did this change help," but "how did today's session compare to the last several." Each session becomes its own batch, all four land on one branch, and the demo tags every session's experience so it shows up in the project's [Sessions](../../guides/sessions/) library alongside its own evaluation. ### What lands in your project | | | | -------------- | ---------------------------------------------------------------------------------------------------------------- | | Project | `SignalFlag SDK Demo (Logs to Insights)` | | Branch | `sdk-demo-logs-to-insights` | | System | `Session Evaluations`, created on first run | | Experience tag | `resim-session`, applied to every session's experience | | Batches | Four, one per session date — `2024-11-04`, `2024-11-14`, `2024-11-15`, `2024-11-18` — each with exactly one test | | Metrics set | `Session Metrics` — 6 test metrics and 3 batch metrics | There is no dashboard here — the [Sessions](../../guides/sessions/) library is this demo's trend view, grouping by session rather than by build version, so a metrics dashboard alongside it would be empty by construction. Every batch's one test is the whole session, not a scenario cut out of it — the same mcap snippets, gif clips and telemetry a real ingested recording carries. Because each batch has exactly one test, the demo prints a direct link to that test's page rather than to the batch as a whole, opened on its log viewer tab. ### The data it replays Thirteen topics per session: | Topic | Fields | What it carries | | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | `mission` | `mission_idx`, `start_s`, `end_s`, `duration_s`, `distance_m`, `net_displacement_m`, `mean_speed_mps`, `max_speed_mps`, `moving_share`, `dlio_distance_m`, `odom_dlio_gap_m`, `gnss_distance_m`, `gnss_odom_gap_m`, `has_gnss`, `gnss_coverage`, `gnss_fix_count`, `altitude_min_m`, `altitude_max_m`, `altitude_gain_m`, `start_lat`, `start_lon`, `foot_slip_share`, `odom_gnss_fit_rmse_m` | One row per mission ReSim's own boundary detector found in the session. | | `motion_phase` | `mission_idx`, `phase_idx`, `kind`, `start_s`, `end_s`, `duration_s`, `distance_m`, `mean_speed_mps`, `max_speed_mps` | Contiguous stopped/moving segments within a mission. | | `movement_summary` | `seq`, `mission_idx`, `t_s`, `kind`, `label`, `clip` (image), `snippet`, `phase_duration_s`, `phase_distance_m`, `phase_mean_speed_mps` | One row per start/stop transition, with the clip that shows it and the raw mcap snippet it was cut from. | | `robot_pose` | `mission_idx`, `series`, `t_s`, `x`, `y`, `z`, `east_m`, `north_m`, `has_enu` | Robot position, in both the local and the ENU frame where available. | | `robot_state` | `mission_idx`, `series`, `t_s`, `feet_in_contact`, `feet_slipping`, `max_foot_force_n`, `max_joint_effort_nm`, `max_joint_velocity_rps`, `speed_mps` | Gait state — how many feet are down, and whether any are slipping. | | `speed_sample` | `mission_idx`, `series`, `t_s`, `speed_mps` | Ground speed. | | `imu_sample` | `mission_idx`, `series`, `t_s`, `accel_mag_mps2`, `gyro_mag_rps` | IMU acceleration and gyro magnitude. | | `gnss_track` | `mission_idx`, `series`, `t_s`, `latitude`, `longitude`, `altitude_m`, `east_m`, `north_m` | Raw GNSS fixes. | | `command_tracking` | `mission_idx`, `series`, `t_s`, `cmd_speed_mps`, `act_speed_mps`, `speed_error_mps`, `cmd_yaw_rps` | Commanded against actual speed. | | `battery_sample` | `mission_idx`, `series`, `t_s`, `state_of_charge`, `cell_temperature_c` | Battery state over the session. | | `session_events` | event: `name`, `description`, `status`, `tags`, `recording_key`, `mission_idx`, `t_s`, `metrics` | Mission boundaries and clip references, one per moment worth marking. | | `session_summary` | `n_missions_detected`, `n_missions_ground_truth`, `detection_correct`, `boundary_error_s`, `total_duration_s`, `active_duration_s`, `total_distance_m`, `total_gnss_distance_m`, `mean_speed_mps` | Headline numbers for the whole session. | | `session_inventory` | `start_ns`, `end_ns`, `files`, `sizes_bytes`, `formats` | What the session's mcap snippets were cut from. | ### What you see on a test | Metric | Template | What it shows | | --------------------- | ----------------------------- | ------------------------------------------------------------------------ | | Speed Over Time | custom (`custom_line.liquid`) | Ground speed over the session. | | IMU Acceleration | line | IMU acceleration magnitude over the session. | | Foot Contact and Slip | table | Gait state over the session — feet down, feet slipping, peak foot force. | | Motion Phases | table | Every stopped/moving segment the session was cut into. | | Movement Snapshots | image | A frame from every start/stop transition. | | GNSS Track | table | Raw GNSS fixes over the session. | The **Events** tab carries one event per mission boundary and transition the session was cut on. The **Logs** tab holds every mcap snippet and gif clip the session produced. ### What you see on the batch | Metric | Template | What it shows | | -------------------- | -------- | ----------------------------------------------------------------------------------- | | Session Summary | table | Missions detected against ground truth, total distance, total duration, mean speed. | | GNSS Coverage | scalar | Mean share of the session with a GNSS fix, across missions. **Warns below 0.5.** | | Raw Source Inventory | table | The source recording this session's snippets were cut from. | ______________________________________________________________________ ## How the three compare | | `navigation` | `mujoco` | `session` | | --------------------------- | ------------------------------------------------------------------- | ---------------------------------------------------------------------- | ----------------------------------------------------- | | Shape | A/B pair | A/B pair | Trended over time, no pair | | System under test | A hospital delivery robot's navigation stack | An ALOHA bimanual manipulation policy | A legged robot's field sessions | | What varies between batches | Two versions of the stack | One hyperparameter of the same checkpoint | The day the session was recorded | | Batches | 2 | 2 | 4 | | Tests per batch | 34 scenarios | 20 cube placements | 1 — the whole session | | Topics | 13 | 8 | 13 | | Metrics | 21 — 13 test, 5 batch, 3 dashboard | 20 — 9 test, 5 batch, 6 dashboard | 9 — 6 test, 3 batch | | Dashboard | Yes, by build version | Yes, by build version | None — the Sessions library is the trend view instead | | System templates covered | Nine of ten — all but `artifact` — plus two custom Liquid templates | Seven of ten — no scalar, video or artifact — plus one custom template | Four of ten, plus one custom Liquid template | | Status checks | Two, both of which can block | One, warn only | One, warn only | | Files per test | Camera clip and still, on 11 of 34 | MCAP and episode animation, on all 20 | Every mcap snippet and gif clip the session produced | | Data to download | ~7 MB | ~110 MB | ~950 MB | None is a subset of the others. The navigation demo is the wider tour of what SignalFlag renders; the MuJoCo demo is the closer look at comparing two builds of one policy; the session demo is the one to run if what you actually have is field recordings rather than a build to compare against another. ______________________________________________________________________ ## Read the config that drives it Everything either demo displays comes from a metrics config and its templates, shipped inside the package. Nothing is hardcoded into the platform, and nothing about these files is special to the demo — this is the same config you would write for your own system: Python ``` from signalflag.demo import config_path, templates_path print(config_path("navigation").read_text()) print(templates_path("navigation")) # directory of the .liquid templates it references ``` `config_path("mujoco")` and `config_path("session")` give you the other two. Three pieces matter, in this order. **Topics** describe the shape of the data your tests emit: config.resim.yml ``` topics: odom_linear_velocity: schema: x: float y: float z: float ``` **Metrics** are SQL queries over that data, each rendered by a template. A metric's `type` decides what it runs against: `test` per test, `batch` across a batch, `dashboard` across every batch in the dashboard's window. config.resim.yml ``` metrics: Robot Speed: type: test description: Ground speed of the robot over the course of the run. query_string: | SELECT 'Speed' AS group_name, timestamp / 1E9 AS "Time (s)", SQRT(POWER(x, 2) + POWER(y, 2)) AS "Speed (m/s)" FROM odom_linear_velocity; template_type: system template: line ``` Batch and dashboard metrics can join against the built-in `metadata` table, which is where the build version, experience name and status of each test live: config.resim.yml ``` metrics: Localization Error by Build Version: type: dashboard query_string: | SELECT 'Mean' AS group_name, m.build_version AS "Build Version", AVG(pd.position_diff_m) AS "Mean Localization Error (m)" FROM pose_difference pd JOIN metadata m ON pd.job_id = m.job_id WHERE m.build_version IS NOT NULL GROUP BY m.build_version ORDER BY m.build_version; template_type: system template: bar ``` **Metrics sets** group metrics so that a batch or a dashboard can run them. Note the key is `metrics sets`, with a space: config.resim.yml ``` metrics sets: Demo Metrics: # run against each batch metrics: - Robot Speed - Speed Distribution # ... Demo Trends: # powers the dashboard, which spans batches metrics: - Localization Error by Build Version # ... dashboards: SDK Demo Trends: metrics_set: Demo Trends refresh: auto day_range: 30 ``` A metric with `template_type: custom` names a `.liquid` file instead of a system template, and that file has to be synced alongside the config — which is why `templates_path()` exists next to `config_path()`. The [metrics guide](../../guides/metrics/) covers topics, every template, status checks and [custom templates](../../guides/metrics/custom-templates/) in full. ______________________________________________________________________ ## Next steps - **Emit your own data.** [Get Your First Metrics in SignalFlag](../first-external-batch/) walks through the same API the demo uses, starting from an empty script. - **Write your own metrics.** Start with the [metrics guide](../../guides/metrics/), and develop them against a debug dashboard before running a batch. - **Reference.** The [SignalFlag SDK guide](../../guides/resim-sdk/) covers the SDK's API surface in full. # Get Your First Metrics in SignalFlag In this tutorial you'll get data into SignalFlag and see real metrics in the dashboard — without Docker, without a container registry, and without running anything in SignalFlag's infrastructure. You'll use the SignalFlag Python SDK to create a batch, emit structured data from two tests, and view the results. **Time:** about 10 minutes **Before you start:** - You have a SignalFlag account. Sign up at [app.signalflag.ai/signup](https://app.signalflag.ai/signup) if you don't have one. - You have Python 3.10+ installed. - You can authenticate in a browser (the script will prompt you with a URL the first time). ______________________________________________________________________ ## What you're building The [resim-sdk-example](https://github.com/resim-ai/resim-sdk-example) repo contains a minimal Python script that: 1. Creates a batch in your SignalFlag project 1. Runs two tests, each emitting a series of `(x, y)` position data points 1. Uploads the data to SignalFlag and triggers metrics processing You'll end up with a batch in the SignalFlag app showing a line chart of `y over time` per test, and a batch-level table of min/avg/max values across both tests. ______________________________________________________________________ ## Step 1: Create a project If you don't have a SignalFlag project yet, create one: Go to [app.signalflag.ai/projects/create](https://app.signalflag.ai/projects/create) and create a project. Shell ``` signalflag projects create --name "my-project" --description "My project" ``` Note the project name — you'll need it in Step 4. ______________________________________________________________________ ## Step 2: Clone the example repo Shell ``` git clone https://github.com/resim-ai/resim-sdk-example.git cd resim-sdk-example ``` ______________________________________________________________________ ## Step 3: Install dependencies Shell ``` pip install -r requirements.txt ``` Or, if you're using `uv`: Shell ``` uv sync ``` This installs `resim-sdk`, the SDK under its pre-rebrand name. It is the same package as `signalflag`, and the example's `resim.*` imports keep working either way. ______________________________________________________________________ ## Step 4: Set your project name Open `main.py` and update `PROJECT_NAME` to match the project you created in Step 1: main.py ``` PROJECT_NAME = "my-project" ``` ______________________________________________________________________ ## Step 5: Look at what you're running Before running, take a look at the two files that matter: **`main.py`** — creates the batch and emits test data: main.py ``` client = DeviceCodeClient() with Batch( client=client, project_name=project_name, branch="metrics-test-branch", metrics_set_name="my metrics", metrics_config_path="resim/config.resim.yml", ) as batch: with Test(client, batch, "test 1") as test: for i in range(10): test.emit("position", {"x": float(i), "y": float(i)}, i) with Test(client, batch, "test 2") as test: for i in range(10): test.emit("position", {"x": float(i), "y": float(i * 2)}, i) ``` **`resim/config.resim.yml`** — defines the data schema and metrics: resim/config.resim.yml ``` version: 1 topics: position: schema: x: float y: float metrics: y over time: type: test query_string: select 'y', timestamp, y from position order by timestamp template_type: system template: line min/avg/max: type: batch query_string: select min(y) as min, avg(y) as avg, max(y) as max from position template_type: system template: table metrics sets: my metrics: metrics: - y over time - min/avg/max ``` The config defines one topic (`position` with `x` and `y` floats), two metrics (a per-test line chart and a batch-level table), and a metrics set that groups them. ______________________________________________________________________ ## Step 6: Run it Shell ``` python main.py # or uv run main.py ``` The first time you run it, you'll be prompted to authenticate in a browser: Output ``` Authenticating by Device Code Please navigate to: https://resim.us.auth0.com/activate?user_code=XXXX-XXXX Created batch rejoicing-aquamarine-starfish with id dc71ebee-... test 1 done test 2 done Batch done. After a few minutes, you can view your metrics here: https://app.resim.ai/projects/.../batches/... ``` Visit the URL, authenticate with your SignalFlag account, and the script will continue automatically. Subsequent runs reuse the cached token. The script exits as soon as the data is uploaded; metrics processing runs in SignalFlag and takes a couple of minutes. ______________________________________________________________________ ## Step 7: View results in the dashboard Open the URL printed by the script, or navigate to your project in [app.signalflag.ai](https://app.signalflag.ai) and find the batch. For each test you'll see: - **y over time** — a line chart of `y` values across the 10 data points At the batch level: - **min/avg/max** — a table comparing the minimum, average, and maximum `y` values across both tests `test 2` has `y = i * 2` (steeper slope) so its values will be higher than `test 1` (`y = i`), which you'll see clearly in the batch table. ______________________________________________________________________ ## What's next You've now pushed data into SignalFlag and seen it as metrics — without any Docker or cloud infrastructure setup. The natural next steps are: - **[Adapt this to your own data](../../guides/resim-sdk/)** — swap out the `position` topic for your own data schema and write SQL metrics that match your system # How-to Guides # Getting Started with Your Own System If you haven't used SignalFlag before, start with the [tutorials](../tutorials/). They fill a demo project with real results and need no Docker or AWS setup. This section covers the same steps with your own system: your Docker images, your experiences, and your metrics. - **Connect your experiences and builds** ______________________________________________________________________ Grant SignalFlag limited access to your data in S3 and your images in ECR. [Guide](resim-data-access/) - **Install the CLI** ______________________________________________________________________ Install the SignalFlag CLI to create resources and trigger batches from your terminal. [Guide](cli/) - **Create a project** ______________________________________________________________________ Create a [project](../core-concepts/#project) to house your work and collaborate with your team. [Guide](projects/) - **Create a system** ______________________________________________________________________ Define a [system](../core-concepts/#system) to run tests against. [Guide](systems/) - **Add experiences** ______________________________________________________________________ Register your own [experiences](../core-concepts/#experience) as inputs for your tests. [Guide](adding-experiences/) - **Build your system image** ______________________________________________________________________ Package your system into a Docker image with the right inputs/outputs contract. [Guide](build-images/) - **Create test suites** ______________________________________________________________________ Create [test suites](../core-concepts/#test-suite) that pair a system with a fixed set of experiences. [Guide](test-suites/) - **(Optional) Set up CI** ______________________________________________________________________ Automatically trigger batches on pull requests using GitHub Actions or GitLab CI. [Guide](ci/) For SignalFlag to run your tests, it needs to be able to access four types of data: [experiences](../../core-concepts/#experience), [assets](../../core-concepts/#asset), [system build images](../../core-concepts/#build), and [metrics build images](../metrics-builds/). - [**Experience Data Sources**](../experience-data-sources/) ______________________________________________________________________ Configure access to experience data stored in AWS S3, Google Cloud Storage, the Foxglove Data Platform, or locally in your build container. - [**Asset Data Sources**](../assets/#prerequisites) ______________________________________________________________________ Assets use the same cloud storage sources as experiences. If you have already configured experience data access, no additional setup is needed. - [**Container Registry Access**](../container-registry-access/) ______________________________________________________________________ Configure access to container images stored in AWS ECR, Docker Hub, GitHub Container Registry, or Google Artifact Registry. ## IAM roles SignalFlag will provide you with an AWS IAM role unique to your organization that is used for various AWS APIs, depending on the features you use. This role is referenced in the setup instructions for [AWS S3](../experience-data-sources/#aws-s3), [Foxglove](../../guides/foxglove-primary-sites/#self-hosted-primary-sites) and [AWS ECR](../container-registry-access/#aws-ecr). The role will look like this: Text ``` arn:aws:iam::083585393365:role/resim-customer-yourorg.ai-prod ``` SignalFlag needs to pull your [build images](../../core-concepts/#build) and [metrics build images](../metrics-builds/) from a container registry. This page describes how to configure access for each supported registry. ## AWS ECR To use images hosted in AWS Elastic Container Registry (ECR) with SignalFlag, you can set up access to an existing ECR repository, or create a new ECR repository. If you're creating a new repository, we recommend creating it in `us-east-1` as that's where our app runs. You can follow [the AWS documentation for creating ECR repositories](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html). The repository needs a policy applied so that SignalFlag components can pull images from it. Use your customer-specific role as described in [IAM Roles](../resim-data-access/#iam-roles). ### New repository, or existing repository without policy JSON ``` { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowSignalFlagToPull", "Effect": "Allow", "Principal": { "AWS": ["arn:aws:iam::083585393365:role/resim-customer-yourorg.ai-prod"] }, "Action": ["ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer"] } ] } ``` ### Existing repository with policy If you have an existing ECR repository with images you would like to test, and that repository already has a policy set, add the below statement to the repository's policy. Check whether you are using a generic role or a customer-specific role as described in [IAM Roles](../resim-data-access/#iam-roles). JSON ``` "Statement": [{ "Sid": "AllowSignalFlagToPull", "Effect": "Allow", "Principal": { "AWS": [ "arn:aws:iam::083585393365:role/resim-customer-yourorg.ai-prod" ] }, "Action": [ "ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer" ] }] ``` ## Docker Hub You can use an existing repository or [create a new one](https://docs.docker.com/docker-hub/repos/create/). Once it's ready, you will need to [set up a new service account](https://docs.docker.com/docker-hub/service-accounts/#creating-a-new-service-account) and share the Docker ID and personal access token (PAT) securely with us. Docker Image Pull Rate We use a mechanism to pull and mirror your container images securely inside our platform. This means image retrieval is quicker, and also means that we only make requests to Docker Hub when you publish images we haven't yet mirrored. Thus the limit of 5000 pulls per day Docker imposes should be more than enough. ## GitHub Container Registry To use SignalFlag with GitHub Container Registry (`ghcr.io`), [create a Personal Access Token (classic)](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-personal-access-token-classic) with access to the relevant repository and the `read:packages` scope. Share the token and your GitHub username with your contact at SignalFlag and we will configure secure storage and automated use of your credentials. To restrict the access this token grants, create a new GitHub account and add it as an [outside collaborator](https://docs.github.com/en/organizations/managing-user-access-to-your-organizations-repositories/managing-outside-collaborators/adding-outside-collaborators-to-repositories-in-your-organization) with access only to the relevant repository/repositories. ## Google Artifact Registry You can use an existing repository or [create a new one](https://cloud.google.com/artifact-registry/docs/docker). Once it's ready, you will need to [set up a new service account](https://cloud.google.com/iam/docs/service-accounts-create) and [generate a key](https://cloud.google.com/iam/docs/keys-create-delete) for it. SignalFlag needs the service account to have `Artifact Reader` access to the repository in question. To grant SignalFlag access, please share a base64 encoded version of the `key.json`, [which can be used to login to the artifact registry](https://cloud.google.com/artifact-registry/docs/docker/authentication#json-key). ## AWS GovCloud or private cloud solutions Please get in touch with SignalFlag if you would like to discuss other, more bespoke, access patterns or if you are a user of AWS GovCloud, which we also support. SignalFlag supports multiple sources for [experience](../../core-concepts/#experience) data. This page describes how to configure access for each supported source. ## AWS S3 You can use an existing bucket where you already have input data, or create a new one for SignalFlag. If you create a new bucket, we recommend creating it in the `us-east-1` region as that's where our app runs. You can follow the [AWS documentation for creating a bucket](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html). We don't require any specific settings except that the data isn't stored in [Glacier archive](https://aws.amazon.com/s3/storage-classes/glacier/). Whether you have an existing bucket, or have created one specifically for use with SignalFlag, you need to give a SignalFlag IAM role access to read from the bucket, as described in [IAM Roles](../resim-data-access/#iam-roles). The IAM role is used by components of the SignalFlag platform if they need to fetch Experience data and looks like this: Text ``` arn:aws:iam::083585393365:role/resim-customer-yourorg.ai-prod ``` ### New bucket, or bucket without existing policy The following policy needs to be applied to your bucket. Make sure you replace the `bucket-name` placeholder value with the name of your bucket, and the `Principal` with your customer-specific role as described above. JSON ``` { "Version": "2012-10-17", "Id": "SignalFlagAccess", "Statement": [ { "Sid": "SignalFlagAccess", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::083585393365:role/resim-customer-yourorg.ai-prod" }, "Action": ["s3:GetObject", "s3:ListBucket"], "Resource": ["arn:aws:s3:::bucket-name", "arn:aws:s3:::bucket-name/*"] } ] } ``` ### Existing bucket with policy If your bucket already has a bucket policy set, update the policy to add the following statement. Make sure you replace the `bucket-name` placeholder value with the name of your bucket, and the `Principal` with your customer-specific role as described above. JSON ``` "Statement": [ { "Sid": "SignalFlagAccess", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::083585393365:role/resim-customer-yourorg.ai-prod" }, "Action": [ "s3:GetObject", "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::bucket-name", "arn:aws:s3:::bucket-name/*" ] } ] ``` ### Using S3 experiences When creating experiences, use the `s3://` prefix for your location: Bash ``` signalflag experiences create \ --project "my-project" \ --name "My S3 Experience" \ --locations "s3://my-bucket/path/to/experience/" ``` Important Any location that points to an S3 bucket must be prefixed with `s3://` rather than the `https://...` form. ## Google Cloud Storage You can use an existing GCS bucket or create a new one for SignalFlag. If creating a new bucket, we recommend using the `us-east1` region for optimal performance. ### Setting up access To grant SignalFlag access to your GCS bucket, you need to create a service account and share its credentials with us. 1. **Create a service account** following the [Google Cloud documentation](https://cloud.google.com/iam/docs/service-accounts-create). 1. **Grant the service account read access** to your bucket. The service account needs the `Storage Object Viewer` role on the bucket containing your experiences. 1. **Generate a key** for the service account following the [Google Cloud documentation](https://cloud.google.com/iam/docs/keys-create-delete). 1. **Share the key with SignalFlag**. Provide the contents of the `key.json` file to your SignalFlag contact. We will configure secure storage and automated use of your credentials. ### Using GCS experiences When creating experiences, use the `gs://` prefix for your location: Bash ``` signalflag experiences create \ --project "my-project" \ --name "My GCS Experience" \ --locations "gs://my-gcs-bucket/path/to/experience/" ``` ## Foxglove Data Platform SignalFlag integrates with the [Foxglove Data Platform](https://foxglove.dev/data-platform), allowing you to use recordings stored in Foxglove as experience data for your tests. ### Setting up access Foxglove access is configured per SignalFlag project using an API key. 1. **Generate an API key** in your Foxglove organization settings. Navigate to your [Foxglove settings](https://app.foxglove.dev/~/settings) and create a new API key with read access to the recordings you want to use. 1. **Share the API key with SignalFlag**. Provide the API key to your SignalFlag contact along with the SignalFlag project you want to associate it with. We will configure secure storage and automated use of your credentials. One API key per project Each SignalFlag project can have one Foxglove API key associated with it. If you need to access recordings from multiple Foxglove organizations, please contact us to discuss your requirements. ### Using Foxglove experiences When creating experiences, use the `foxglove://` prefix with the recording ID: Bash ``` signalflag experiences create \ --project "my-project" \ --name "My Foxglove Experience" \ --locations "foxglove://rec_abc123def456" ``` You can find the recording ID in the Foxglove web app when viewing a recording. ## Local experiences Experience data can also be stored locally within your [build container](../../core-concepts/#build). This is useful when experience data is tightly coupled to changes in your system and lives in the same repository. ### Providing access to local experiences in your container In your [experience build](../build-images/) Dockerfile, copy the files from your repository to your container: Dockerfile ``` COPY //// /experiences/ ``` ### Creating local experiences When creating a local experience, provide the path where the data will be located inside the container: Bash ``` signalflag experiences create \ --project "my-project" \ --name "My Local Experience" \ --locations "/experiences/my-scenario/" ``` ### Programmatically accessing local experiences For local experiences, SignalFlag does not perform any automatic file copying. Instead, the `/tmp/resim/test_config.json` file will contain an `experienceLocation` field that you can use to locate the experience data: Python ``` import json # Read the test_config.json file try: with open("/tmp/resim/test_config.json", "r") as f: test_config = json.load(f) except FileNotFoundError: raise FileNotFoundError("test_config.json not found in /tmp/resim") # Get the experience location experience_location = test_config["experienceLocation"] ``` Cloud vs Local experiences For cloud-based experiences (S3, GCS, Foxglove), SignalFlag automatically copies the experience files into `/tmp/resim/inputs/` before your build runs. For local experiences, files remain at their original location and you must access them directly using the path from `test_config.json`. # Install the CLI SignalFlag has released an [open source repository](https://github.com/resim-ai/api-client) for the SignalFlag Command Line Interface, the `signalflag` command, which can be used to easily access our API endpoints. Follow the [installation](https://github.com/resim-ai/api-client#installation) and [authentication](https://github.com/resim-ai/api-client#authentication) instructions in that repo before continuing to the subsequent articles. The CLI was previously called `resim`. The old command name, `RESIM_*` environment variables, and `~/.resim` config directory keep working for now, with a deprecation warning. [Migrating from `resim`](https://github.com/resim-ai/api-client#migrating-from-resim) lists the new name for each. # API Keys An API key lets a script, a CI pipeline, an external tool or an agent use SignalFlag without signing in as a person. Each key belongs to your organization, so it keeps working when people join or leave, and you can give it only the access it needs. Org admins create and revoke keys in the [web app](https://app.signalflag.ai). Everyone in the organization can see the list of keys. ## Choose the access Every key has one of two access levels: - **Read only** can see everything in your organization and run queries, but cannot change anything. Use it for dashboards, reports and exporting data. - **Read & write** can do what a member of your organization can, such as creating projects, registering builds and launching tests. Use it for CI pipelines. Pick read only unless the job needs to change something. A key cannot create or revoke other keys: that always takes an org admin signed in as themselves. ## Create a key In the web app: 1. Open **Org Settings** and go to the **API Keys** tab. 1. Select **Create API Key**. 1. Give the key a name that says what uses it, for example `nightly-ci` or `grafana-dashboards`. Names must be unique among your organization's active keys. 1. Choose the access and when the key expires: 30, 90 or 365 days, or never. New keys are read & write and expire after 90 days unless you choose otherwise. 1. Select **Create key**. The **Your API key is ready** dialog shows the key. Copy it, then tick **I've saved my key securely and will keep it private.** to enable **Done**. The key is shown only once. SignalFlag stores a fingerprint of it, not the key itself, so if you lose it you have to create a new one. Store it in your CI service's secrets or your tool's credential store, never in source code. Keep it private Don't put a key in public repositories or public-facing interfaces, such as a shared dashboard panel, a notebook you publish or a page served to browsers. Anyone who finds it can use it until it expires or is revoked. If a key is exposed, [revoke it](#revoke-a-key) and create a new one. Keys start with `sfk_`. In the list of keys, the first characters of each key are shown so you can tell them apart. ## Use a key Send the key as a bearer token. There is no token to exchange first. With the API: Bash ``` curl -s https://api.resim.ai/v1/projects \ -H "Authorization: Bearer $SIGNALFLAG_API_KEY" ``` With the [CLI](../cli/) (v1.3.0 or later), set the key as `SIGNALFLAG_API_KEY` or pass it with `--api-key`. The CLI sends it with every request and never saves it to disk. Earlier versions cannot run `metrics sync`, `metrics validate`, `metrics debug` or `dashboards create` with a key, so update the CLI before you use one: Bash ``` export SIGNALFLAG_API_KEY= signalflag projects list ``` You can also save the key as `api-key: ` in `~/.signalflag/signalflag.yaml`. Use a key or older credentials, not both The CLI stops with `ambiguous authentication arguments provided` if it finds an API key and also a client ID and secret, or a username and password. It checks flags, environment variables (including the older `RESIM_` names) and `signalflag.yaml`. When you switch to a key, remove the old credentials from all of them. Keys are created and revoked in the web app, not with the CLI. With our [GitHub Action](https://github.com/resim-ai/action) (v1.9.0 or later), pass a read & write key as the `api_key` input: YAML ``` - uses: resim-ai/action@v1.9.0 with: api_key: ${{ secrets.SIGNALFLAG_API_KEY }} ``` With an agent, add the key as a header when you connect to the [MCP server](../../guides/mcp/server/). This suits agents that run unattended, such as a step in a CI pipeline. Using Claude Code as the example: Bash ``` claude mcp add --transport http signalflag https://bff.resim.ai/mcp \ --header "Authorization: Bearer $SIGNALFLAG_API_KEY" ``` To query your data from Grafana, a notebook or a BI tool, see [Query from External Tools](../../guides/metrics/external-access/). ## Manage keys with an agent An agent connected to the [MCP server](../../guides/mcp/server/) as you can list your organization's keys and propose new ones or revocations, for example while it sets up a CI pipeline for you. It never creates or revokes a key on its own: an org admin approves each proposal in the web app, in the same dialog as creating or revoking a key by hand. When an admin approves a new key, the key is shown to that admin only, never to the agent. Copy it into your CI service's secrets or your tool's credential store yourself. See [Managing API keys](../../guides/mcp/capabilities/#managing-api-keys) for the tools involved. ## Expiry and reminders When a key is about to expire, every org admin gets an email 30 days, 7 days and one day before, naming the key and when it expires. Reminders that would arrive before the key was created are skipped, so a 30-day key only gets the last two. To replace a key, create a new one, switch whatever uses the old key over to it, then revoke the old one. Once a key expires it stops working and cannot be renewed. ## Revoke a key Revoke a key as soon as it is no longer needed, or if it may have been exposed. In the web app, select **Revoke** on the key in the **API Keys** tab, and type the key's name to confirm. A revoked key stops working everywhere straight away, and revoking cannot be undone. Revoked and expired keys stay in the list so you can see what they were used for. The tab shows active keys by default. To see the others, change the **Status** filter above the list to **Expired keys**, **Revoked keys** or **All keys**. The first thing for us to do is to create a [project](../../core-concepts/#project) to work in. As discussed in the Core Concepts, we advise you use a project to reflect an entire stack, but otherwise, the project is arbitrary. ## Creating a project You can create a project using the SignalFlag CLI. Bash ``` signalflag projects create --name "autonomy-stack" --description "Our autonomy stack" ``` ## Using the CLI with projects All further commands will expect you to declare a project, for example: Bash ``` signalflag experiences create --project "autonomy-stack" --name "my experience" --description "My experience description" --locations "s3://..." ``` In order to make this a better user experience, you can set a default project: Bash ``` signalflag projects select "autonomy-stack" ``` Once selected, the previous command can be written: Bash ``` signalflag experiences create --name "my experience" --description "My experience description" --locations "s3://..." ``` To find out what project you have selected and to select another, you can use: Bash ``` signalflag projects list ``` ## Navigating between projects In the [SignalFlag app](https://app.signalflag.ai), the project name is displayed in the top right hand corner. You can select your project via a dropdown. Warning This dropdown is currently not persisted through user sessions: the app will, by default, auto-select the most recently created project. If you have feedback on this feature or requests for more functionality around projects, feel free to reach out to info@signalflag.ai Next, we will create a [system](../../core-concepts/#system) in order to define a particular software stack to test. ## Creating a system You can create a system using the SignalFlag CLI. Bash ``` signalflag systems create --project "autonomy-stack" --name "perception" \ --description "The perception subsystem of our autonomy stack" \ --architecture "amd64" --build-vcpus 4 --build-memory-mib 16384 --build-gpus 0 ``` The above example details some common resource requirements. Sensible defaults are provided for those unspecified. For a full list of available flags and their defaults, run `signalflag systems create --help`. ## Architectures SignalFlag supports both the `amd64` and `arm64` architecture. This can be specified at the system level via the `--architecture` flag. ## Listing systems via CLI To list all the systems in your project: Bash ``` signalflag systems list --project "autonomy-stack" ``` To test our [system](../../core-concepts/#system) we need some [experiences](../../core-concepts/#experience). ## Prerequisites Before creating experiences, you need to configure SignalFlag to access your experience data. See the [Experience Data Sources](../experience-data-sources/) guide for instructions on setting up access to: - [AWS S3](../experience-data-sources/#aws-s3) - [Google Cloud Storage](../experience-data-sources/#google-cloud-storage) - [Foxglove Data Platform](../experience-data-sources/#foxglove-data-platform) - [Local paths](../experience-data-sources/#local-experiences) in your build container ## Experience locations Each experience can have multiple locations. In many cases, a single location is sufficient, but it can be helpful to store MCAPs recorded from different sources in different locations. [Assets](../assets/) that are common across all (or many) experiences are also supported in SignalFlag via a separate path. SignalFlag supports the following location prefixes: | Source | Prefix | Example | | -------------------- | ------------- | ------------------------------------- | | AWS S3 | `s3://` | `s3://my-bucket/experiences/exp_001/` | | Google Cloud Storage | `gs://` | `gs://my-bucket/experiences/exp_001/` | | Foxglove | `foxglove://` | `foxglove://rec_abc123def456` | | Local | None | `/experiences/my-scenario/` | For cloud storage locations (S3, GCS), each location should have a unique prefix containing the input files. Anything contained in that prefix will be treated as the same experience and downloaded into your tasks. We recommend using a prefix structure that represents your SignalFlag projects: Text ``` 📂 . ├── 📂 project_a │ └── 📂 experiences │ └── 📂 experience_56ccce99 │ └── ⚙️ test_file │ └── 📂 project_b └── 📂 experiences └── 📂 experience_679bef80 └── ⚙️ test_file ``` ### How experience files are accessed For cloud-based experiences (S3, GCS, Foxglove), files are copied into `/tmp/resim/inputs/` when the experience build runs. If you use *multiple locations*, all files are copied directly into the `inputs` directory. Take care to ensure there are no file or directory name clashes at the root of the locations. Avoiding file clashes with multiple locations If your experience has two locations with the same directory structure: Text ``` s3://your-bucket/experience1 s3://your-bucket/experience2 └── mcaps └── mcaps └── log.mcap └── log.mcap ``` The `mcaps/log.mcap` file will clash - one will overwrite the other in `/tmp/resim/inputs/`. **Solution:** Change the path or filename to ensure uniqueness. For example, use distinct directory names: Text ``` s3://your-bucket/experience1 s3://your-bucket/config └── mcaps └── params.yaml └── log.mcap ``` This results in: Text ``` /tmp/resim/inputs/ ├── mcaps/ │ └── log.mcap └── params.yaml ``` [Experience caching](../../guides/experience-caching/) is enabled by default, so we only copy files that have been added or changed since the last run. For local experiences, files remain at their original location and you access them using the path from `/tmp/resim/test_config.json`. See [Local Experiences](../experience-data-sources/#local-experiences) for details. ## Experience timeouts Each experience has a timeout. This is the maximum amount of time that a build can run for a given experience. If the build does not finish running before the timeout is reached, it will be sent a SIGTERM and then a SIGKILL after a grace period. The default timeout is 1 hour, but you can specify a different timeout when creating an experience. ## Creating an experience You can create new experiences like so: Bash ``` signalflag experiences create \ --project "my-project" \ --name "Experience_56ccce99" \ --description "In this experience, we test that our robot can navigate to the goal without colliding with any other agents." \ --locations "s3://my-experiences-bucket/project_hal9000/experiences/experience_56ccce99/" \ --systems "perception" "localization" \ --tags "navigation" "collision-avoidance" ``` This command should return a message containing the UUID of the created experience, and it should now be browsable through the [SignalFlag app](https://app.signalflag.ai). The `--systems` flag enables you to specify any [systems](../../core-concepts/#system) that this experience is compatible with. You can specify multiple systems by providing multiple system names or IDs. The `--tags` flag allows you to apply tags to the experience for better organization and filtering. You can specify multiple tags by providing multiple tag names or IDs. Optional flags are: Bash ``` --timeout "1h10m" # the maximum expected duration of the container \ --environment-variable "SYSTEM_CONFIGURATION=Foo" # many allowed \ --environment-variable "AN=other" \ --profile "left-arm" # a docker compose profile to select the subset of compose services to run \ ``` ### Examples with different sources **AWS S3:** Bash ``` signalflag experiences create \ --project "my-project" \ --name "S3 Experience" \ --description "An experience stored in S3" \ --locations "s3://my-bucket/experiences/exp_001/" ``` **Google Cloud Storage:** Bash ``` signalflag experiences create \ --project "my-project" \ --name "GCS Experience" \ --description "An experience stored in GCS" \ --locations "gs://my-gcs-bucket/experiences/exp_001/" ``` **Foxglove:** Bash ``` signalflag experiences create \ --project "my-project" \ --name "Foxglove Experience" \ --description "An experience stored in Foxglove" \ --locations "foxglove://rec_abc123def456" ``` **Local:** Bash ``` signalflag experiences create \ --project "my-project" \ --name "Local Experience" \ --description "An experience stored locally in the build container" \ --locations "/experiences/my-scenario/" ``` ## Updating an experience You can update various aspects of an experience, including its systems and tags: Bash ``` signalflag experiences update \ --project "my-project" \ --experience "Experience_56ccce99" \ --name "Updated Experience Name" \ --description "Updated description" \ --locations "s3://my-experiences-bucket/project_hal9000/experiences/updated_experience/" \ --timeout "2h" \ --systems "perception" "planning" \ --tags "updated-tag" "new-functionality" ``` When updating systems or tags, the provided lists will replace the existing systems and tags associated with the experience. You can also add or remove individual systems from an experience: Bash ``` signalflag experiences add-system \ --project "my-project" \ --system "" \ --experience "Experience_56ccce99" signalflag experiences remove-system \ --project "my-project" \ --system "" \ --experience "Experience_56ccce99" ``` Similarly you can add and remove individual tags: Bash ``` signalflag experiences tag \ --project "my-project" \ --tag "" \ --experience "Experience_56ccce99" signalflag experiences untag \ --project "my-project" \ --tag "" \ --experience "Experience_56ccce99" ``` To share common data across [builds](../../core-concepts/#build) and [experiences](../../core-concepts/#experience), SignalFlag supports [assets](../../core-concepts/#asset). ## Why use assets? Consider a simulation stack that requires a large HD map, 3D environment meshes, and ML model weights. Every experience in your test suite needs this data, but none of it changes between experiences, it only changes when your simulation environment or models are updated. Without assets, you have two options, neither ideal: - **Bake the data into your Docker image** - This can bloat the image, slow down CI builds, and force a full image rebuild every time a map or model is updated even if the code hasn't changed - **Duplicate the data across experience locations** - This can waste storage, make updates error-prone, and increase data transfer costs *Assets* solve this by letting you define shared data once, revision it independently of your code, and mount it into any build at runtime. Your Docker image stays lean, your experiences stay focused on per-test inputs, and your shared data is versioned and cached. ``` flowchart LR Asset["Asset\n(e.g. HD Map)"] -->|"linked to"| Build[Build] Experience["Experience\n(e.g. Scenario)"] -->|"run with"| Test[Test] Build -->|"run in"| Test Test -->|"part of"| Batch[Test Batch] subgraph container ["Container at Runtime"] AssetMount["/tmp/resim/assets/world/"] InputMount["/tmp/resim/inputs/"] end Asset -->|"mounted at"| AssetMount Experience -->|"mounted at"| InputMount ``` ## Prerequisites Assets are stored in cloud blob storage, using the same data sources as experiences. If you have already configured access for your experience data, no additional setup is needed. If not, see the [Experience Data Sources](../experience-data-sources/) guide for instructions on setting up access to: - [AWS S3](../experience-data-sources/#aws-s3) - [Google Cloud Storage](../experience-data-sources/#google-cloud-storage) ## Asset locations Each asset can have multiple locations. SignalFlag supports the same location prefixes as experiences: | Source | Prefix | Example | | -------------------- | ------- | ---------------------------------- | | AWS S3 | `s3://` | `s3://my-bucket/assets/sim-world/` | | Google Cloud Storage | `gs://` | `gs://my-bucket/assets/sim-world/` | | Local | None | `/assets/sim-world/` | For cloud storage locations, each location should have a unique prefix containing the asset files. Anything within that prefix will be synced. We recommend a prefix structure that mirrors your SignalFlag projects: Text ``` 📂 . └── 📂 my-project └── 📂 assets ├── 📂 sim-world │ ├── 🗺️ hd_map.bin │ └── 📂 meshes │ └── 🏙️ urban_env.glb └── 📂 ml-models └── 🤖 perception_v3.onnx ``` ## How asset files are accessed For cloud-based assets, files are synced from cloud storage and mounted **read-only** at `/tmp/resim/assets//` when a build runs. The `mountFolder` is specified when creating the asset and determines where inside the container the files appear. For example, an asset with `mountFolder` set to `world` and location `s3://my-bucket/assets/sim-world/` results in: Text ``` /tmp/resim/assets/world/ ├── hd_map.bin └── meshes/ └── urban_env.glb ``` Your entrypoint script can then read from `/tmp/resim/assets/world/` just as it would from any local directory. If an asset has multiple locations, all files are synced into the same mount directory. Take care to avoid file or directory name clashes at the root of the locations, just as with [experience locations](../adding-experiences/#experience-locations). [Asset caching](../../guides/asset-caching/) is enabled by default, so only files that have been added or changed since the last run are downloaded. Note Because assets are shared across potentially concurrent jobs, the `/tmp/resim/assets//` directory is mounted **read-only**. If your workload needs to modify asset data, copy the files to a writable location first. ## Creating an asset You can create a new asset like so: Bash ``` signalflag assets create \ --project "my-project" \ --name "Simulation World" \ --description "HD map and 3D meshes for urban simulation environment" \ --locations "s3://my-assets-bucket/my-project/assets/sim-world/" \ --mount-folder "world" \ --version "1.0.0" ``` This command returns the UUID and revision number of the created asset. The asset starts at *revision* `0`. Revisions are automatically incremented. | Flag | Required | Description | | ---------------- | -------- | --------------------------------------------------- | | `--name` | Yes | A human-readable name for the asset | | `--description` | Yes | A description of what the asset contains | | `--locations` | Yes | One or more cloud storage locations | | `--mount-folder` | Yes | The subdirectory name under `/tmp/resim/assets/` | | `--version` | Yes | A version string (e.g. `1.0.0`, `v2`, a commit SHA) | | `--cache-exempt` | No | If set, the asset will not be cached between runs | ### Examples with different sources **AWS S3:** Bash ``` signalflag assets create \ --project "my-project" \ --name "ML Models" \ --description "Perception model weights" \ --locations "s3://my-bucket/assets/ml-models/" \ --mount-folder "models" \ --version "v3.1" ``` **Google Cloud Storage:** Bash ``` signalflag assets create \ --project "my-project" \ --name "Calibration Data" \ --description "Sensor calibration parameters" \ --locations "gs://my-gcs-bucket/assets/calibration/" \ --mount-folder "calibration" \ --version "2024-Q4" ``` ## Revising an asset When the underlying data changes (e.g. a new map version or updated model weights), we create a **new revision** of the asset rather than modifying it in place. This preserves an immutable history of every version of the asset data, enabling reproducibility. Bash ``` signalflag assets revise \ --project "my-project" \ --asset "Simulation World" \ --locations "s3://my-assets-bucket/my-project/assets/sim-world-v2/" \ --version "2.0.0" ``` Each revision increments the revision number (0, 1, 2, ...). The `--version` flag is required when revising -- it should reflect the new state of the data (e.g. a semantic version, date, or commit SHA). You can also optionally update the `mountFolder`: Bash ``` signalflag assets revise \ --project "my-project" \ --asset "Simulation World" \ --locations "s3://my-assets-bucket/my-project/assets/sim-world-v2/" \ --mount-folder "world-v2" \ --version "2.0.0" ``` You can list all revisions of an asset: Bash ``` signalflag assets list-revisions \ --project "my-project" \ --asset "Simulation World" ``` ## Updating asset metadata To update an asset's name or description without changing its data: Bash ``` signalflag assets update \ --project "my-project" \ --asset "Simulation World" \ --name "Urban Simulation World" \ --description "HD map and 3D meshes for the urban simulation environment (downtown)" ``` ## Associating assets with builds Assets must be explicitly **linked to a build** before they are available at runtime. This association specifies which asset revision the build should use. ### At build creation time (recommended) The simplest approach is to attach assets when you create the build. The `signalflag builds create` command accepts an `--assets` flag with a comma-separated list of asset references: Bash ``` signalflag builds create \ --image "123456789.dkr.ecr.us-east-1.amazonaws.com/my-sim:abc1234" \ --version "abc1234" \ --name "Autonomy Build" \ --description "Path planning v2.3" \ --branch "my-branch" \ --project "my-project" \ --system "full-stack" \ --auto-create-branch \ --assets "Simulation World:2,ML Models:5" ``` This creates the build and links the specified asset revisions in a single step. Each asset will be mounted at its respective `mountFolder` when the build runs. Each entry in the comma-separated list can take one of four forms where the `uuid` is the revision ID: | Format | Example | Behaviour | | --------------- | -------------------- | ----------------------------- | | `name` | `Simulation World` | Links the **latest** revision | | `name:revision` | `Simulation World:2` | Links a specific revision | | `uuid` | `a1b2c3d4-...` | Links the **latest** revision | | `uuid:revision` | `a1b2c3d4-...:2` | Links a specific revision | When the revision is omitted, the latest revision at the time of build creation is used as the static revision for that build. We recommend pinning explicit revision numbers in CI/CD for reproducibility. ### Adding assets to an existing build If you need to add assets to a build after it has been created, use `signalflag builds add-assets`: Bash ``` signalflag builds add-assets \ --project "my-project" \ --build "" \ --assets "Simulation World:2" ``` ### Listing assets for a build Bash ``` signalflag builds list-assets \ --project "my-project" \ --build "" ``` ### Removing assets from a build Bash ``` signalflag builds remove-assets \ --project "my-project" \ --build "" \ --asset "Simulation World" ``` ### Querying which builds use an asset Bash ``` signalflag assets list-builds \ --project "my-project" \ --asset "Simulation World" ``` ## Archiving assets Assets that are no longer needed can be archived. Archived assets are hidden from default list views but are not deleted. Bash ``` signalflag assets archive \ --project "my-project" \ --asset "Simulation World" ``` To restore an archived asset: Bash ``` signalflag assets restore \ --project "my-project" \ --asset "Simulation World" ``` To include archived assets in a list: Bash ``` signalflag assets list \ --project "my-project" \ --archived ``` ## Recommended CI/CD workflow We recommend associating assets with builds as part of your CI/CD pipeline. This ensures that every build is pinned to specific asset revisions, making test results fully reproducible. A typical workflow: 1. **Create and revise assets independently of your code** - When a map, model, or calibration dataset is updated, create a new asset revision. This can be done manually or in a separate pipeline triggered by changes to your data repository 1. **Pin asset revisions in CI** - When your CI pipeline creates a new build, associate it with the desired asset revisions. Store the asset revision numbers as CI variables or derive them from a configuration file in your repository 1. **Update asset revisions deliberately** - When you want to test against a new map or model, bump the revision number in your CI configuration and let the pipeline pick it up ### GitHub Actions example Extending the [GitHub Actions workflow](../ci/github/), you can pass asset revisions directly when creating the build using the `--assets` flag: YAML ``` - name: Create build with assets and launch batch env: SIGNALFLAG_CLIENT_ID: ${{ secrets.SIGNALFLAG_CLIENT_ID }} SIGNALFLAG_CLIENT_SECRET: ${{ secrets.SIGNALFLAG_CLIENT_SECRET }} run: | signalflag builds create \ --project "my-project" \ --system "full-stack" \ --image "${{ steps.docker_meta.outputs.tags }}" \ --version "${{ github.sha }}" \ --branch "${{ github.head_ref || github.ref_name }}" \ --auto-create-branch \ --assets "Simulation World:${{ vars.SIM_WORLD_REVISION }},ML Models:${{ vars.ML_MODELS_REVISION }}" ``` Store `SIM_WORLD_REVISION` and `ML_MODELS_REVISION` as [GitHub Actions variables](https://docs.github.com/en/actions/learn-github-actions/variables) so they can be updated without changing the workflow file. Tip Separating asset revisions from code changes means you can update your simulation environment without rebuilding your Docker image, and vice versa. This significantly speeds up iteration when only data has changed. ## End-to-end example Here is a complete walkthrough using a simulation world asset shared across many experiences. ### 1. Create the asset Bash ``` signalflag assets create \ --project "my-project" \ --name "Simulation World" \ --description "Downtown urban environment: HD map, 3D meshes, traffic light configs" \ --locations "s3://my-assets-bucket/my-project/assets/sim-world/" \ --mount-folder "world" \ --version "1.0.0" ``` ### 2. Create a build with the asset attached Bash ``` signalflag builds create \ --image "123456789.dkr.ecr.us-east-1.amazonaws.com/my-sim:abc1234" \ --version "abc1234" \ --name "Autonomy Build" \ --description "Path planning v2.3" \ --branch "my-branch" \ --project "my-project" \ --system "full-stack" \ --auto-create-branch \ --assets "Simulation World:0" ``` ### 3. Run a batch Bash ``` signalflag batches create \ --project "my-project" \ --build "Autonomy Build" \ --test-suite "Nightly Regression" ``` When each test in the batch runs, the simulation world data is automatically mounted at `/tmp/resim/assets/world/`. ### 4. Access asset data in your entrypoint Python ``` import pathlib map_path = pathlib.Path("/tmp/resim/assets/world/hd_map.bin") mesh_dir = pathlib.Path("/tmp/resim/assets/world/meshes/") map_data = map_path.read_bytes() meshes = list(mesh_dir.glob("*.glb")) ``` Every experience in the test suite gets the same simulation world without any duplication. In order to run our [experiences](../../core-concepts/#experience) against our [system](../../core-concepts/#system) we need a system [build](../../core-concepts/#build) available as a container image hosted somewhere we can access. ## Prerequisites For your build image to be usable in SignalFlag, it needs to be hosted in an image registry that we are granted permission to access. Uploading the image to a registry is documented below, but you should ensure you have followed [SignalFlag Data Access](../resim-data-access/) to set up an AWS ECR repository to work with SignalFlag. Furthermore, you must have permission to push to that registry. If you're using an IAM user, the easiest way to get the needed permissions is to attach the AWS-managed IAM policy called `AmazonEC2ContainerRegistryPowerUser` to the user. You can do this through the [AWS browser UI](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_change-permissions.html#users_change_permissions-add-console) (see "Adding permissions by attaching policies directly to the user") or using the CLI: Bash ``` aws iam attach-user-policy --policy-arn "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryPowerUser" --user-name ``` If you're using an IAM role instead, it's a [similar operation](https://docs.aws.amazon.com/IAM/latest/UserGuide/roles-managingrole-editing-console.html#roles-modify_permissions-policy). If you'd prefer to be stricter with your permissions, you really only need the permissions from the policy [here](https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-push.html#image-push-iam) rather than all of those in `AmazonEC2ContainerRegistryPowerUser`. If there is a [repository policy](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-policies.html#repository-policy-vs-iam-policy) on the repository already, check it doesn't explicitly deny access by the IAM identity (user or role) you're using. ## Entrypoint The first step in creating a build image is to identify a shell command that you would like to run in order to test your software. If your software test involves multiple different processes, this is fine, but you may want to write a shell script or another piece of software to correctly initialize and run them. For instance, if you are using ros2 with gazebo, you might write a launch file for this and then your test command might be a call to a script containing something like: Bash ``` #!/bin/bash # run_sim_test.sh # Source our ros2 distribution source /opt/ros//setup.bash # Navigate to, build, and source the ros2 package we're building cd colcon build source install/setup.bash # Launch our test sim ros2 launch my_package launch_test_sim.py ``` But really, any script which your docker container can execute will suffice. Once you have identified such a command, your goal is to create a [Dockerfile](https://docs.docker.com/engine/reference/builder/) which builds an image that has everything it needs to run your test command. Then, that command should be denoted as the `ENTRYPOINT` of that Dockerfile. ## Inputs and outputs It is typically desirable to run the same *Build* with a variety of different *Experiences* (sets of input files). Therefore, the SignalFlag worker will mount a volume containing the inputs for each run at `/tmp/resim/inputs/`. Using the ros2 example above, the `launch_test_sim.py` launch file might reference ROS2 Parameter YAML files stored in `/tmp/resim/inputs/`. You would then put these YAML files in an Amazon S3 bucket and add them as experiences as described [here](../adding-experiences/). Again, there's nothing special about using ros2 in this case and any file stored correctly in the experiences bucket will be available there. In addition to experience inputs, any [assets](../../core-concepts/#asset) associated with the build are mounted read-only at `/tmp/resim/assets//`. See the [assets setup guide](../assets/) for details on creating assets and linking them to builds. The SignalFlag platform additionally places a file called `test_config.json` in the `/tmp/resim/` directory. This JSON contains the following fields: JSON ``` { "experienceID": "the unique id of the experience", "experienceName": "the name of the experience", "experienceLocation": "the location of the experience", "branchName": "the name of the branch", "buildVersion": "the version of the build running", "buildID": "the unique id of the build running", "systemName": "the name of the system the build running belongs to", "systemID": "the unique id of the system" } ``` This config file can be helpful for determining the experience location, if the experience is not stored in S3 but within the build image, by reading `/tmp/resim/test_config.json` If custom parameters are used in the test command, they should be stored in the `/tmp/resim/parameters.json` file. When the test command is run, it will produce some sort of valuable outputs that can be accessed through the SignalFlag app. Any such outputs (e.g. console logs or rosbags) should be stored in the `/tmp/resim/outputs/` directory. If this is done correctly, you will be able to download them using a link in the SignalFlag app. If you place files in nested subdirectories beneath `/tmp/resim/outputs/`, SignalFlag will archive those nested directories into `.zip` files before uploading them. If you want log files to remain unarchived, place them in `/tmp/resim/outputs/logs/`. Files in that directory are uploaded as logs without being zipped and are browsable on the web app. There are two exceptions to the zipping of nested subdirectories. First, if a subdirectory contains only a single file, that file is uploaded individually rather than being zipped. Second, any image or video referenced in your emissions file is uploaded individually — with its original path preserved — so that metrics can resolve it by filename; if such a subdirectory contains other files as well, it is still zipped in addition. This means you can reference images and videos in your metrics even when they live in nested subdirectories, without having to place them at the top level of `outputs/` or in `logs/`. To avoid overwhelming uploads, at most 100 emission-referenced media files are uploaded individually per run. It can, however, be the case that you generate logs that you do not wish to upload, but wish to use for computing metrics. If you place any logs in `/tmp/resim/outputs/ignore` these will be made available in the metrics phase, but are not uploaded to the app. If your image exits `0` in the context of a SignalFlag batch, we consider it a successful run and will automatically compute the next, metrics, stage. If your image exits non-zero, we will create an `Error` status on that test and will not run metrics. It is possible to provide a custom error message that will be reported, alongside the exit code, on the SignalFlag web app by leaving a file called `error.txt` in the `/tmp/resim/outputs` folder. ## Developing an image For an example of a very simple build image please refer to [this directory](https://github.com/resim-ai/open-core/tree/main/resim/examples/sim_runner) which contains directions and example scripts to create and test run a build image. In this case, we use SignalFlag's open source simulator to run a simple scripted simulation of two quadcopter drones. The example uses a build script to build our test executable and then uses Docker's `COPY` command in its `Dockerfile` to move the resulting executable into the finished image. The general rule is that the Docker image must contain everything your test needs to run *except* for the the inputs (i.e. the experience). In order to develop a working test image, a good workflow is generally to iterate on it locally. This involves the following steps: ### 1. Inputs and Outputs Create local `inputs/` and `outputs/` folders with the `inputs/` folder containing a set of representative input files. **If you are doing this from within a Docker container**, creating volumes and copying content to them is probably better. Here's how you would do that: Bash ``` # Create a helper container to copy content over docker container create \ --name tmp \ --volume test_inputs:/inputs \ busybox # Copy test data to the volume docker cp path/to/test/inputs tmp:/inputs # Remove the helper container docker rm tmp ``` ### 2. Build Assuming your Dockerfile is in a folder called `runner/`, build your Docker image using: Bash ``` docker build runner/ -t test-runner-image:latest ``` Note that the name `test-runner-image` here is arbitrary. You can use whatever name you would like as long as you're consistent when developing because the image will be re-tagged with `docker tag` before it's pushed. ### 3. Run Try out a run with your Docker image using: Bash ``` docker run \ --volume /absolute/path/to/inputs:/tmp/resim/inputs \ --volume /absolute/path/to/outputs:/tmp/resim/outputs \ test-runner-image:latest ``` The `--volume` flags here ensure that the inputs and outputs are available to the container at `/tmp/resim/inputs` and `/tmp/resim/outputs`. Note that `/absolute/path/to/inputs` and `/absolute/path/to/outputs` are paths on the *host* system. **If you are iterating within a Docker container**, you would use the Docker volumes approach mentioned in step 1. In this case, you would **instead** run: Bash ``` docker run \ --volume test_inputs:/tmp/resim/inputs \ --volume test_outputs:/tmp/resim/outputs \ test-runner-image:latest ``` And getting your outputs back would look like: Bash ``` # Create a helper container to copy content back: docker container create \ --name tmp \ --volume test_outputs:/outputs \ busybox # Copy outputs from the volume docker cp tmp:/outputs . # Remove the helper container docker rm tmp ``` ### 4. Iterate If any step is unsuccessful, make modifications and return to step 2. ## Pushing Once the build image is created and working, the next step is to push it to your AWS Elastic Container Registry (set up according to [SignalFlag Data Access](../resim-data-access/)) like so: Bash ``` docker tag test-runner-image .dkr.ecr..amazonaws.com/test-runner-image: aws ecr get-login-password --region | docker login --username AWS --password-stdin .dkr.ecr..amazonaws.com docker push .dkr.ecr..amazonaws.com/: ``` Note the use of a commit SHA here. This is what we recommend as a unique ID associated with your software version if you're using `git` for version control. You can get a short form of the current commit hash by running: Bash ``` git rev-parse --short HEAD ``` On a successful push, the command will report something like: Text ``` The push refers to repository [.dkr.ecr..amazonaws.com/] a9950558cded: Pushed 29563d2ab359: Pushed aa5d6a7236b9: Pushed ... bce45ce613d3: Pushed latest: digest: sha256:aa47e2d0c6dcc5d48d3c9b8c9c8a57433b2d241c27ef92aa53de885683f06487 size: 7480 ``` If you instead get something like the following, it is an indicator either that the ECR repository URL (account number or repository name) you are trying to push to is incorrect, or that you don't have the required permissions to push to it. Check the [Prerequisites](#prerequisites) for additional info. Text ``` The push refers to repository [.dkr.ecr..amazonaws.com/] a9950558cded: Retrying in 7 seconds 29563d2ab359: Retrying in 7 seconds aa5d6a7236b9: Retrying in 7 seconds ... bce45ce613d3: Waiting EOF ``` You might want to automate these build and push steps by adding them to a new or existing CI pipeline. See our articles on [Pushing Build Images from CI](../ci/) for how. ## External links - [AWS ECR authentication documentation](https://docs.aws.amazon.com/AmazonECR/latest/userguide/registry_auth.html) ## Creating a branch Each build is associated with a branch. The branch represents the particular change you're testing. A build can be thought of as one implementation of that change. A given branch may have many builds associated with it. You can manually create a branch with the CLI: Bash ``` signalflag branches create \ --name "my-branch" \ --type CHANGE_REQUEST \ --project "my-project" ``` It's often easier to use the `--auto-create-branch` flag when creating a build which is the approach taken below. The SignalFlag app supports three types of branch, for three common git workflows: - `CHANGE_REQUEST`: a pull or merge request, a short-lived branch - `MAIN`: a long-lived, protected branch that most change requests will land to - `RELEASE`: a release of a piece of software The `--auto-create-branch` flag will create a `CHANGE_REQUEST` branch, but if the branch is named `main` it will make it a `MAIN` branch. ## Creating a build Now that the build image has been pushed to your elastic container registry, the final step is to formally create the build by informing the SignalFlag app as to its location. This is done using the [SignalFlag CLI](../cli/). We assume that we already have a [project](../projects/) called `my-project`, a [system](../systems/) called `my-system` and a [branch](../../core-concepts/#branch) called `my-branch`. These are required for build creation. After [authenticating](https://github.com/resim-ai/api-client#authentication) we can create a new build like so: Bash ``` signalflag builds create \ --image ".dkr.ecr..amazonaws.com/:" \ --version "" \ --name "Autonomy Build" \ --description "Optimized path planning to avoid unexpected squirrels" \ --branch "my-branch" \ --project "my-project" \ --system "my-system" \ --auto-create-branch ``` The `--project`, `--branch`, and `--system` flags will accept either a name or an ID. When using `--auto-create-branch`, one must also pass a branch name using `--branch`. If you have selected a project via the CLI, you can omit the `--project` for convenience. This command should return a message containing the UUID of the created build, and it should now be browsable through the [SignalFlag app](https://app.signalflag.ai). Note that the image itself requires the full tagged URI, since we allow an arbitrary version to be stored that need not reflect the image tag. ## Multi-container builds You can also submit a [Docker Compose](https://docs.docker.com/reference/compose-file/) file when creating a build, instead of a single build image (`--image`). Bash ``` signalflag builds create \ --build-spec=my-docker-compose.yml [...] ``` See [the guide](../../guides/multi-container-builds/) for more details on how to set up a Compose file to execute your code during the **Experience** phase. When executing multiple containers like this, all containers have access to the `/tmp/resim` directory for inputs and outputs, although it is certainly common for only a subset of containers to actually read/write there as necessary. All images specified in a Compose file must be in an accessible Container Registry as per above. The Compose file used is passed via the API at build creation time and does not need to be hosted anywhere. You may not need this If your emitted data from your experience build does not require post-processing you can skip this step and go straight to [Metrics](../../guides/metrics/). A metrics build is only needed if your workflow requires post-processing of raw experience build outputs before metrics can be computed. This document describes how the SignalFlag platform supports executing metrics builds. ## Metrics in the SignalFlag platform Similar to [builds](../../core-concepts/#build), customers can register a **Metrics Build** with SignalFlag, which will be executed after each test. A metrics build is also a container image, with a similar contract to [builds](../build-images/#1-inputs-and-outputs). After each test, the SignalFlag platform runs the metrics build with the `/tmp/resim/inputs` directory populated with: - a subdirectory, `experience`, which contains any files as part of the experience - a subdirectory, `logs`, which contains any files generated as logs from the execution of the simulation. The metrics build post-processes these and writes its results as emissions with the [SignalFlag SDK](../../guides/resim-sdk/), to a file in `/tmp/resim/outputs` whose name ends in `.resim.jsonl`, such as `emissions.resim.jsonl`. SignalFlag ingests these emissions alongside those from the experience build, and the [metrics config](../../guides/metrics/) synced to the branch computes metrics from both. Any additional files placed in the outputs directory will also be uploaded to the SignalFlag platform as logs. ## Creating metrics builds It is possible to create metrics builds in CI/CD or with the CLI tool: Bash ``` signalflag metrics-builds create \ --project "my-project" \ --name "My Metrics Build" \ --version \ --image \ --systems "perception" "localization" ``` Where, again, if one has a project selected, that parameter can be omitted. Similarly to builds, SignalFlag recommend the set-up of CI/CD workflows to generate metrics builds when the metrics generation code is updated. ## Systems and metrics builds Since metrics are closely tied to the test application which runs, the SignalFlag app enables metrics builds to be aligned to a given system, to enable compatibility checking at test creation time. One can register an existing metrics build against a given system: Bash ``` signalflag metrics-builds add-system \ --project "my-project" \ --system "my-system" \ --metrics-build-id "" ``` and remove them with: Bash ``` signalflag metrics-builds remove-system \ --project "my-project" \ --system "my-system" \ --metrics-build-id "" ``` ## Debugging metrics To check how your metrics render without running a batch, generate an emissions file and pass it to `signalflag metrics debug`, which renders it against a metrics set in a temporary dashboard. See [Adding your first metric](../../guides/metrics/#adding-your-first-metric). If you've gone through all of the previous articles, you are now ready to begin testing your builds with some [experiences](../../core-concepts/#experience) and generating metrics! We do this by creating and running a [**Test Suite**](../../core-concepts/#test-suite). ## Creating a test suite To create a test suite, you need to have a [system](../../core-concepts/#system) in mind, a [metrics set](../../guides/metrics/) and a set of experiences you would like to use. You can create a test suite using the [SignalFlag CLI](../cli/) with this command, assuming you already have a [project selected](../projects/#using-the-cli-with-projects) Bash ``` signalflag suites create \ --name "Perception Nightly Regression" \ --description "A test suite for perception system nightly regression tests" \ --system "perception" \ --metrics-set "" \ --experiences ", , ..." ``` You can `get` or `list` the test suites for that project. For example, the following command displays the latest revision: Bash ``` signalflag suites get \ --test-suite "Perception Nightly Regression" ``` To get a specific revision append the `--revision 1` key. To get a list of all revisions, pass `--all-revisions`. In order to `revise` the test suite, you simply need to pass the elements that you would like to change. For example, to change the experience list, you would use the following command: Bash ``` signalflag suites revise \ --test-suite "Perception Nightly Regression" --experiences ", , ..." ``` Warning You need to specify the exact list of experiences. The CLI will be extended in the near future to support specifying a query to describe the list of experiences. In the short term, the [SignalFlag app](https://app.signalflag.ai) supports query-based test suite creation and building. ## Running a test suite If you have a test suite, you can then run it to create a **Test Batch**: Bash ``` signalflag suites run \ --test-suite "Perception Nightly Regression" --build-id "" ``` If you would like to specify a particular revision, you can pass `--revision 0`. You can list the test batches that have been created from this test suite via: Bash ``` signalflag suites batches \ --test-suite "Perception Nightly Regression" ``` This will list all the test batches from all revisions of the test suite. Simply pass the `--revision` flag to see test batches from a specific test suite revision. ## Tracking a test batch Once you have created a test batch by running a test suite, the CLI lets you track the status of that batch. You can list all of the batch details -- as JSON -- either by passing the friendly name of the batch (e.g. rejoicing-aquamarine-starfish) or its id: Bash ``` signalflag batches get \ --batch-id ``` or Bash ``` signalflag batches get \ --batch-name ``` If you additionally pass the exit status key: Bash ``` signalflag batches get \ --batch-id \ --exit-status ``` The application will return only the exit status, which are: - 0: `Succeeded`: the batch has completed. This does not indicate whether the metrics have passed or failed. - 1: `Internal Error`: the CLI command errored (which is nothing to do with the test batch). - 2: `Error`: the batch has finished with an error. - 3: `Submitted`: the batch is in the submitted state. - 4: `Running`: the batch is still running. - 5: `Cancelled`: the batch has been cancelled. This is commonly used in CI to trigger a failing test. You can also list the individual tests in that batch with: Bash ``` signalflag batches tests \ --batch-name ``` This will return the JSON associated with the test to track the individual status and return their IDs. The IDs are helpful to, for example, list the log files associated with that test: Bash ``` signalflag logs list \ --batch-id \ --test-id ``` The output of this includes pre-signed URLs that would enable you to download logs directly from the command line. In particular, every test contains the `experience-container.log` and `metrics-container.log` files which contain the console logs from your container (`experience-container.log`) and the metrics stage (`metrics-container.log`). ## Ad hoc test suites It is not always desirable to create a test suite: sometimes, you may simply want to try a few experiences on an experimental branch to make sure that you haven't broken everything. For this, the SignalFlag App supports the concept of an ad hoc test suite. That is, an unnamed test suite. You can create this in the CLI as follows: Bash ``` signalflag batches create \ --project "my-project" \ --build-id \ --metrics-build-id \ --experiences ", , ..." \ --experience-tags ", " ``` Use `--experiences` and/or `--experience-tags` to control which experiences are run in the batch. ## Configuration options for running test suites There are several configuration options available when one is running a test suite or creating an ad-hoc batch: - **A custom batch name:** Rather than use the auto-generated friendly name (e.g. `rejoicing-aquamarine-starfish`), you can provide your own. In the CLI, this comes from the `--batch-name ` flag. - **An allowable error rate:** By default, if any tests in the test suite `ERROR` -- that is, have a failure at the execution phase -- the SignalFlag orchestration system will mark the whole test batch as `ERROR` and not compute any batch metrics. In many cases, this is the correct default behaviour, but it can be overridden with `--allowable-failure-percent `. By default, tests which error will not have test metrics associated with them, but if you set `--allowable-failure-percent 100`, SignalFlag will attempt to compute metrics even when a test has errored. - **Parameter overrides:** One can pass key-value parameters to your build to change how it runs via a parameter override flag e.g. `--parameters "key=value"`. ## Rerunning a subset of tests in a test suite It can be frustrating if one or two tests within a test suite has a flaky error or unexpected behavior. The SignalFlag platform makes it easy to re-run just a subset of tests so that the whole suite doesn't need to be run again. In the CLI, this can be achieved with Bash ``` signalflag batches rerun --batch-name --test-ids "," ``` # Metrics SignalFlag Metrics are a flexible and powerful way to collect, plot, and track data from your tests. At their core, Metrics work by ingesting data from various sources in your system; ROS topics, log files, or custom instrumentation, into a centralized data lake. When you emit data during a test run, it's automatically captured and stored in this data lake. After each run completes, the system automatically queries this data lake using SQL queries you've defined to generate metrics, visualizations, and pass/fail status checks. The data lake persists over time, which means you can continue to explore, query, and visualize your test data long after the run has finished, enabling powerful post-hoc analysis and trend tracking across releases. ### Why use Metrics? The data lake architecture provides several key benefits. Because your data persists, you're not limited to viewing only the metrics you defined before the test ran. You can return to the SignalFlag UI days, weeks, or months later to explore the raw data, write new queries, create new visualizations, and answer questions you didn't anticipate when you first ran the test. This makes Metrics ideal for debugging unexpected failures, conducting retrospective analysis, and iterating on your metrics definitions without needing to re-run expensive tests. ### Branch isolation Metrics configurations are tied to specific branches in your project. This means your `main` branch can maintain a stable, well-tested set of metrics and data schemas, while development branches can experiment with new metrics, modify schemas, or test breaking changes without affecting production workflows. Each branch maintains its own independent metrics configuration, allowing engineers to iterate safely and merge changes only when they're ready. ### What you'll create To use Metrics, you'll create a single configuration file (`.resim/metrics/config.resim.yml`) that defines three key components: 1. **Topics** — The schema for data you'll emit from your system (e.g., robot velocity, localization error, goal status). Topics define the structure and types of the data flowing into the data lake. 1. **Metrics** — SQL queries that transform your emitted data into visualizations and scalar values. Metrics can be test-level (computed per individual test run) or batch-level (aggregated across multiple test runs). Metrics can have status checks - optional thresholds attached to metrics that determine pass/fail/warning states. These allow you to automatically flag tests that miss performance requirements. 1. **Metrics sets** — Collections of metrics that are run against a set of tests, helping you to validate performance and learn about robot behavior. The rest of this guide will walk you through each of these components step by step, starting with identifying the data you want to collect. ## Identifying Key Data The first step to adopting SignalFlag's Metrics framework is to identify the key data that you want to collect, plot, and track over time in the SignalFlag Platform. To start with, we'd recommend simple data that you're interested in plotting simply; i.e. your robot's velocity over time. Identify where this data comes from; in our example, we'll be reading it from our robot's `/odom` topic. ## Writing the schema Firstly, we strongly recommend installing the [SignalFlag VSCode Extension](https://marketplace.visualstudio.com/items?itemName=resim-ai.resim) (or from [Open VSX Registry](https://open-vsx.org/extension/resim-ai/resim) for VSCode forks); it provides language support for SignalFlag config files and will help you avoid mistakes when emitting your data! Look at the structure of the data you want to emit to SignalFlag; in our example case, we're looking at the `Odometry.twist.twist.linear` data, which is a `Vector3` representing the velocity of the robot in the x, y and z axis. We can write a SignalFlag config for this like so: YAML ``` # required version header version: 1 topics: odom_linear_velocity: schema: x: float y: float z: float ``` To ease your experience with writing queries, we recommend flattening nested data structures into their own topics. Additionally, we don't support slash characters `/` in topic names (sorry!). Use the content assist from the VSCode extension to explore the available data types. In-depth descriptions are provided by the extension on hover. Some column types don't hold raw data at all: `image`, `video`, and `artifact` columns hold the file names of files written to the job outputs, resolved when the metric renders. See [Image](#image), [Video](#video), and [Artifact](#artifact) under [Metric Templates](#metric-templates) below. Save the config file to `.resim/metrics/config.resim.yml` in your repository. The SignalFlag CLI and the Python SDK both read this path by default. You can save it to another path: pass `--metrics-config-path=` to the CLI, or `metrics_config_path=` to the SDK's `Batch`. Both accept more than one file; the files are merged, and each topic may appear in only one of them. The VSCode extension finds config files through its `resim.configFilePaths` setting, which accepts `.yml` and `.yaml` files. Its default entry is `.resim/metrics/config.resim.yaml`, so if you use the `.yml` default above, add your path to that setting. ## Emitting your data There are two approaches to take here; you can either emit the data live from your stack or post-hoc when your test is complete. We'll discuss both here. The `emit` API is primarily used through the `Emitter` class. You can pass it a `config_path` and an `output_path`. `output_path` is where we will write your emissions file - by default it is `/tmp/resim/outputs/emissions.resim.jsonl`. When `config_path` is both specified and is visible to the application, we will validate the types & shape of the data being emitted to ensure it will be ingested by the SignalFlag platform correctly. See below for an example: Python ``` from resim.metrics.python.emissions import Emitter emitter = Emitter(config_path=".resim/metrics/config.resim.yml") emitter.emit("odom_linear_velocity", {"x": 1.0, "y": 2.0, "z": 3.0}, timestamp=0) emitter.emit("odom_linear_velocity", {"x": 1.1, "y": 1.9, "z": 0.0}, timestamp=500000000) # rejected emitter.emit("odom_linear_velocity", {"x": "left", "y": "right", "z": "up"}, timestamp=1000000000) ``` When validation is on, the `Emitter` rejects a row locally, before anything is uploaded, if: - a field is not in the topic's schema, or a schema field is missing from the row. Every emit must carry every column. If only some rows have a field (for example, a column that a newer logger added), put that field in its own topic, or emit long-format rows such as `(name, value)`. - a value is `None`. There are no optional columns. - a value has the wrong type. `True`/`False` is rejected for `int` and `float` fields (use `1`/`0`). A float such as `1.0` is rejected for an `int` field, and so are numpy integers such as `numpy.int64`; convert them with `int()` or `.tolist()`. An `int` is accepted for a `float` field. - the config uses a type that the `Emitter` does not know. The known types are `boolean`, `int`, `float`, `string`, `status`, `image`, `video`, `string[]` and `metric[]`. A rejected row means the config and the data do not agree. Fix the config or the data; do not turn validation off. Timestamps are integers in nanoseconds. When your data has simulation time, use it: for ROS messages, use `header.stamp`, not the time the message was logged. In a simulation that runs slower than real time, log time stretches the run (at 8% of real time, a 17 s run looks like 205 s). Under the hood, we append these messages to your `output_path`. In this example, the lines would look like this: /tmp/resim/outputs/emissions.resim.jsonl ``` {"$metadata": {"topic": "odom_linear_velocity", "timestamp": 0}, "$data": {"x": 1.0, "y": 2.0, "z": 3.0}} {"$metadata": {"topic": "odom_linear_velocity", "timestamp": 500000000}, "$data": {"x": 1.1, "y": 1.9, "z": 0.0}} ... ``` ### Stack Emissions Here's a more fully fleshed-out code example of a stack-based emission pattern. Continuing with our ROS example, we will create a new node for our stack, the `MetricsEmitter` which will receive messages from the `/odom` ROS topic and emit them to the `odom_linear_velocity` SignalFlag topic. Python ``` from rclpy.node import Node from resim.metrics.python.emissions import Emitter from nav_msgs.msg import Odometry from builtin_interfaces.msg import Time as MsgTime from rclpy.time import Time from typing import Optional class MetricsEmitter(Node): def __init__(self): super().__init__('metrics_emitter') self.emitter = Emitter(config_path=".resim/metrics/config.resim.yml") self.first_timestamp = None self.odom_subscriber = self.create_subscription(Odometry, '/odom', self.odom_callback, 10) def get_relative_timestamp(self, msg_time: Optional[MsgTime] = None) -> Optional[int]: if self.first_goal_received_time is None: return None current_time: Time if msg_time is not None: current_time = Time.from_msg(msg_time) else: current_time = self.get_clock().now() return current_time.nanoseconds - self.first_timestamp.nanoseconds def odom_callback(self, msg: Odometry): if self.first_timestamp == None: self.first_timestamp = Time.from_msg(msg.header.stamp).nanoseconds self.emitter.emit("odom_linear_velocity", { "x": msg.twist.twist.linear.x, "y": msg.twist.twist.linear.y, "z": msg.twist.twist.linear.z }, timestamp=self.get_relative_timestamp(msg.header.stamp)) ``` ### Post-hoc Emissions If you're already recording log files from your simulations, you might want to take advantage of SignalFlag's metrics builds. We can follow much the same pattern, but instead read the data from log files like MCAPs or rosbags. See a developed example below using ROS: Python ``` from resim.metrics.python.emissions import Emitter from rosidl_runtime_py.utilities import get_message import rosbag2_py from pathlib import Path import rclpy.serialization def emit_velocity_data(emitter: Emitter, input_bag: Path): reader = rosbag2_py.SequentialReader() reader.open( rosbag2_py.StorageOptions(uri=str(input_bag), storage_id="mcap"), rosbag2_py.ConverterOptions( input_serialization_format="cdr", output_serialization_format="cdr" ), ) # Create a dictionary mapping topic names to their types topic_type_map = {topic.name: topic.type for topic in reader.get_all_topics_and_types()} odom_topic = "/odom" if odom_topic not in topic_type_map: raise ValueError(f"topic {odom_topic} not in bag") msg_type = get_message(topic_type_map[odom_topic]) while reader.has_next(): topic, data, timestamp = reader.read_next() if topic == odom_topic: # Only emit if enough time has passed since last emission msg = rclpy.serialization.deserialize_message(data, msg_type) emitter.emit('odom_linear_velocity', { 'x': msg.twist.twist.linear.x, 'y': msg.twist.twist.linear.y, 'z': msg.twist.twist.linear.z, }, timestamp=timestamp) if __name__ == "__main__": input_bag = Path("/tmp/resim/inputs/logs/record.mcap") with Emitter(config_path=".resim/metrics/config.resim.yml") as emitter: emit_velocity_data(emitter, Path(input_bag)) ``` ### Series Emissions If you're emitting a series of data from a single call, there is an additional helper function - `Emitter.emit_series`. This will spread the data from this single emit call to multiple emission lines, to aid with query simplicity. For the initial example above, this can be written as: Python ``` emitter = Emitter(config_path=".resim/metrics/config.resim.yml") emitter.emit_series("odom_linear_velocity", { "x": [1.0, 1.1, 1.1, 1.2], "y": [2.0, 1.9, 1.8, 1.7], "z": [3.0, 3.0, 3.0, 3.0] }, timestamps=[0, 500000000, 1000000000, 1500000000]) # Equivalent to emitter.emit("odom_linear_velocity", {"x": 1.0, "y": 2.0, "z": 3.0}, timestamp=0) emitter.emit("odom_linear_velocity", {"x": 1.1, "y": 1.9, "z": 3.0}, timestamp=500000000) emitter.emit("odom_linear_velocity", {"x": 1.1, "y": 1.8, "z": 3.0}, timestamp=1000000000) emitter.emit("odom_linear_velocity", {"x": 1.2, "y": 1.7, "z": 3.0}, timestamp=1500000000) ``` The config file remains the same as the original example, as the resulting emissions match the existing definition of the topic. The function will validate the types of the data as it is emitted & ensure all series are of the same length. ### Event Emissions SignalFlag supports special types of emissions called "events". These cause an event to be registered for your job at the given timestamp, which will appear in the Events tab in the SignalFlag app. Each event refers to a specific point in time - such as reaching a goal, or when a system stop occurs. Metrics can be attached to each event by including them in the emission to help you understand the system state at that time. Events are emitted using the `emitter.emit_event(topic_name, data, timestamp)` method. The topic must have `event: true` in the config, and each event takes exactly one timestamp. See the example below: YAML ``` topics: # ... goal_reached: event: true schema: name: string description: string status: status tags: string[] metrics: metric[] ``` Python ``` emitter = Emitter(config_path=".resim/metrics/config.resim.yml") emitter.emit_event("goal_reached", { "name": "Goal 1 Reached", "description": "Robot successfully reached goal number 1", "status": "PASSED", "tags": ["navigation"], "metrics": [{ "name": "Stereo View", "type": "image", "value": ["goal_1.png"], "status": "PASSED", }], }, timestamp=1750000000) ``` The structure of the `metric[]` object is defined as JSON ``` "metrics": [ { "name": "string", "description": "optional", "status": "optional. PASSED | FAIL_BLOCK | etc.", "type": "scalar | image | plotly | text | video | artifact", "value": "the value of the metric. Changes based on the type.", // examples: // Scalar and text metrics are treated the same way. // "type": "scalar" | "text", // "value": "2.37", // "type": "image", // "value": ["1.jpg", "2.jpg"] // "type": "plotly" // "value": "{ a valid plotly blob}", ie. the output of fig.to_json() // "type": "video", // "value": ["clip.mp4"] // "type": "artifact", // "value": ["trace.mcap", "notes.txt"], // "timestamp": 1773351267250000000 (optional, see "Seeking to a point in time" under Artifact) } ] ``` Each entry in `metrics` must be an object Each entry needs at least `name`, `type` and `value`. Do not send a list of metric names, such as `["Error Over Time"]`. The SDK does not check this, so the upload succeeds but the batch's metrics fail to compute. If an event has no evidence to attach, send `[]` and put the details in `description`. ### Custom emissions API If Python isn't your jam, you're more than welcome to write your own emitter in the language of your choice. The minimal implementation of the `emit` API (without validation) in Python is [here](https://github.com/resim-ai/open-core/blob/538b339550dc8c63c57dfc8a9cee6659bbb5da36/resim/sdk/metrics/emissions.py#L86). If you'd like official support for your language of choice, please reach out to our ProServe team and we'll look into it! ## Metrics development ### Adding your first metric We recommend developing your first couple of metrics using debug dashboards. The first step is to create an empty metrics set at the end of your config file: YAML ``` ... metrics sets: My Metrics: metrics: [] ``` Next, create the debug dashboard using the [SignalFlag CLI](../../setup/cli/) - see the linked docs for installation instructions. Once you've generated an emissions file, it can be ingested using the `signalflag metrics debug` command, invoked like so: Bash ``` signalflag metrics debug --project "metrics-demo" --emissions-file "emissions.resim.jsonl" --metrics-config-path ".resim/metrics/config.resim.yml" --metrics-set "My Metrics" ``` After a short time, this will print a URL to the debug dashboard which is linked to the config and emissions file provided. From here, you can start to develop your metrics. See the video below for a demonstration. \[ Your browser does not support the video tag. \](https://resim-public-assets.s3.us-east-1.amazonaws.com/Adding_your_first_metric.webm) Once you're happy with your metrics, you can export the current state of the dashboard by clicking the "Export Config" button. This will download a zip file containing the config file and any custom templates configured. You can then replace your local config file with this - you may need to do some formatting & reordering to get it how you like it. You can also develop your metrics in the config file directly, and then reusing `signalflag metrics debug` to test them. See the [metric templates](#metric-templates) below for more details. Once you've added a metric in the config file, make sure that it's included in your metrics set: YAML ``` ... metrics: Robot Speed: type: test description: Robot speed over time query_string: | SELECT 'Speed', timestamp / 1E9 AS "Time (s)", SQRT(POWER(x, 2) + POWER(y, 2)) AS "Speed (m/s)" FROM odom_linear_velocity; template_type: system template: line metrics sets: My Metrics: metrics: - Robot Speed ``` And then you can view it in the debug dashboard by running: Bash ``` signalflag metrics debug --project "metrics-demo" --emissions-file "emissions.resim.jsonl" --metrics-config-path ".resim/metrics/config.resim.yml" --metrics-set "My Metrics" ``` #### Image, Video and Artifact Metrics Debug dashboards can resolve image, video and artifact metrics too. Upload each file referenced in your emissions file with a repeatable `--media-file` flag alongside `signalflag metrics debug`: Bash ``` signalflag metrics debug --project "metrics-demo" --emissions-file "emissions.resim.jsonl" --metrics-config-path ".resim/metrics/config.resim.yml" --metrics-set "My Metrics" --media-file "screenshot.png" --media-file "clip.mp4" ``` `--media-file` works the same for artifact files. Each `--media-file` should point to a local file whose name matches a filename referenced by an image, video, or artifact metric's value in your emissions file. #### Status checks You can make a metric affect pass/fail by adding a status block. Status checks run a separate query that is evaluated against threshold values: if the query returns any rows, the metric is marked as blocking (or warning). Under `status` you configure: - **`query_string`** — A SQL query with exactly one `?` parameter. The `?` is replaced with the `block` or `warn` threshold value when the check runs (e.g. `HAVING COUNT(*) < ?` or `WHERE value > ?`). - **`block`** — Threshold value for a blocking failure. If the status query returns any rows when run with this value, the job is marked as failed (blocker). - **`warn`** — Optional. Threshold value for a warning. If the query returns any rows when run with this value, the metric is marked as a warning instead of a pass. Example: require at least 3 goals to be reached; otherwise the metric blocks. The status query returns a row when the count is *below* the threshold, so we use `HAVING COUNT(*) < ?` with `block: 3`: YAML ``` Time to reach final goal: type: test description: Time between receiving first goal and reaching final goal. Blocks if less than 3 goals are reached. query_string: | SELECT CASE WHEN (SELECT COUNT(*) FROM time_to_goal) != 3 THEN 75.0 ELSE sum(time_s) END FROM time_to_goal; template_type: system template: scalar status: query_string: SELECT '1' FROM time_to_goal HAVING COUNT(*) < ? block: 3 ``` How the check runs: - The `block` threshold is tried first. If the query returns no rows, the `warn` threshold is tried next. - The query takes exactly one `?`. To use two different conditions for block and warn, compute a severity code in SQL and compare against it, for example `SELECT 1 FROM (SELECT CASE WHEN err > 2 THEN 2 WHEN err > 1 THEN 1 ELSE 0 END AS severity FROM summary) s WHERE s.severity >= ?` with `block: 2` and `warn: 1`. - The status check runs only when the metric's own query returns data. If the topic emitted nothing in a test, the metric shows `NO_DATA` and the check does not run, so the job can still pass. See [Required and optional data](#required-and-optional-data). #### Required and optional data Each metric can set `skip_if_no_data`. When it is `true`, a metric whose query returns no rows is hidden for that test. Use it for **optional** data, which some tests do not have: a topic that only some test types emit, events, or a camera that only some rigs carry. Without it, these metrics show as `NO_DATA` on every test that does not emit them. For **required** data (the verdict, the values that have status checks, the headline numbers), set `skip_if_no_data: false`. This alone does not fail a test whose data is missing. With a topic that emitted nothing: | Setup | Metric | Job | | ---------------------------------------------------------------------------- | ------------------------------------------------------------ | ------- | | `skip_if_no_data: true` | Hidden | Passed | | `skip_if_no_data: false`, no status check | `NO_DATA` | Passed | | `skip_if_no_data: false`, status check that blocks when data is absent | `NO_DATA` (the status check does not run on an empty result) | Passed | | `skip_if_no_data: false`, query such as `MIN(x)` that returns one `NULL` row | `NO_DATA` | Passed | | `skip_if_no_data: false`, `COUNT(*)` query with a status check on the count | `FAIL_BLOCK` | Blocker | To make missing data fail the test, give each topic that a required metric reads a presence check, built from a `COUNT(*)` query: YAML ``` Run Summary Present: type: test description: Rows in run_summary. Blocks when this test emitted none. query_string: SELECT COUNT(*) AS value FROM run_summary template_type: system template: scalar units: rows skip_if_no_data: false status: query_string: SELECT 1 FROM (SELECT COUNT(*) AS n FROM run_summary) s WHERE s.n <= ? block: 0 ``` If whole groups of metrics apply only to some tests (for example, detection metrics only for perception tests), consider one metrics set per test type instead of one shared set full of optional metrics. Each batch picks its set by name, so each test type can keep its required metrics strict. ### Running your first Metrics batch Once you're happy with your metrics set, you can give your stack its first run in SignalFlag. First step is to register your config with the SignalFlag platform: Bash ``` $ signalflag metrics sync --project "metrics-demo" --branch "metrics-setup" ``` If you have a test suite you want to run your metrics set against, you can update the test suite as so: Bash ``` $ signalflag suite revise \ --project "metrics-demo" \ --test-suite "Nightly Suite" \ --metrics-set "My Metrics" # Now run the test suite: $ signalflag suite run \ --project "metrics-demo" \ --test-suite "Nightly Suite" \ --build-id "dc71ebee-1601-4d98-aab4-d4bdecfafca1" ``` If running a batch directly, the parameters are similar: Bash ``` $ signalflag batches create --project "metrics-demo" --metrics-set "My Metrics" ... ``` **Note**: Each branch in your project has its own copy of the config file, which might result in lots of CLI calls to re-register config files. To help with this, at the time of triggering a batch your config can automatically be synced to your branch with the `--sync-metrics-config` flag: Bash ``` $ signalflag suite run --project "metrics-demo" \ --test-suite "Nightly Suite" \ --build-id "dc71ebee-1601-4d98-aab4-d4bdecfafca1" \ --sync-metrics-config ``` With that, your batch should be running. Wait for it to complete, and the metrics you have configured will be shown automatically in the SignalFlag app. If you want to make more changes, you can simply repeat the process of exporting the config and replacing your local config file. #### Changing your metrics If you make changes to your metrics on a completed batch, the changes will be saved for the instance of metrics you are currently viewing. For example, if you make a change to the metrics for a single job, it will not be reflected on other jobs in the batch or going forward until you synchronise the config file manually. ### Removing topics (archiving or deprecating a topic) If you remove a topic from your config, `signalflag metrics sync` treats this as **removing** that topic - you'll also see this referred to as archiving or deprecating a topic. Removal hides that topic's historical emissions from queries and charts going forward, without deleting them. This is useful for retiring a topic that's no longer relevant without losing the ability to reintroduce a topic of the same name later - reintroducing a topic with a name that was previously removed starts a fresh, independent incarnation of it. Only data emitted after the reintroduction is visible; data from before the removal stays hidden. Because removal hides data other people may be relying on (batch/job metric charts, dashboards), a sync that would remove a topic first previews the impact and asks you to confirm: Bash ``` $ signalflag metrics sync --project "metrics-demo" --branch "metrics-setup" This sync would remove the following topics: - odom_linear_velocity: 128 emission(s) would be removed, 3 batch/job metric chart(s) reference it Affected dashboards: Nightly Overview (3393a727-0de9-4414-83e9-420b24dcceb5) sync would remove topic(s) odom_linear_velocity; re-run with --allow-topic-removal to confirm ``` This is a destructive operation you cannot undo yourself Once you re-run the sync with `--allow-topic-removal` to confirm, there's no flag or command that reverses it. Reintroducing a topic of the same name only makes *new* data visible again - the emissions hidden by the removal stay hidden, and the charts/dashboards called out in the preview cannot be pointed back at that data on your end. If you remove a topic by mistake, reach out to SignalFlag support - don't rely on being able to fix it yourself. Once you've reviewed the impact, re-run the sync with `--allow-topic-removal` to confirm it: Bash ``` $ signalflag metrics sync --project "metrics-demo" --branch "metrics-setup" --allow-topic-removal This sync will remove the following topics: - odom_linear_velocity: 128 emission(s) would be removed, 3 batch/job metric chart(s) reference it Affected dashboards: Nightly Overview (3393a727-0de9-4414-83e9-420b24dcceb5) ``` The batch/job metric charts and dashboards called out in the preview keep showing what was already rendered for them - removal doesn't retroactively clear anything from view. If one of those charts is re-rendered afterwards, though, it will fail, since it queries a topic that's no longer part of the config. Removal is scoped to the branch, [same as the rest of your metrics config](#branch-isolation) - removing a topic on a development branch has no effect on `main` or any other branch. `--allow-topic-removal` is accepted on `main` too. ### Authoring batch metrics When defining a metric in the config file, you may have spotted the `type: test` definition. This helps our metrics system determine where that metric should be displayed - in this case, it will be shown as a test result. The other option is `type: batch`, which will be shown as a batch metric - which are used for creating aggregate metrics across an entire batch. This changes the data which is available to the metric when authoring the query. This allows really easy authoring of high level metrics - such as "What was the average speed of the robot across all jobs in the batch?" which can be defined as: YAML ``` Average Speed: type: batch description: Average speed of the robot across all jobs in the batch. query_string: SELECT AVG(speed) FROM robot_speed template_type: system template: scalar ``` Along with the data you have emitted, you may also want to join against the metadata table to get more human-readable information. See the [metadata schema](#metadata-schema) below for more details. ### Dashboards Dashboards aggregate metrics across many batches over a trailing time window, so you can track how your system, tests, or test suite are performing as a whole. See the [Dashboards guide](dashboards/) for details. ## Metric Templates Each metric uses a **template** that defines how its query results are rendered. The following system templates are available; in all cases the query runs against your emitted topic data, and column order (and for charts, column aliases) determine layout and axis titles. Chart templates also accept a `template_settings` block for axis labels, fixed ranges, series colors and per-chart display options — see [Customizing charts](#customizing-charts). Queries use Trino SQL (for example `ARBITRARY`, `CAST(x AS VARCHAR)` and window functions). Give every column an alias: chart templates use the aliases as axis titles. The columns each template expects, in order: | Template | Columns | | --------------------------------- | ----------------------------------------- | | [Line](#line-chart) | series, x, y | | [Bar](#bar-chart) | series, x, y | | [Table](#table) | any | | [Scalar](#scalar) | one value (first row, first column) | | [Image](#image) | file name, from a column typed `image` | | [Video](#video) | file name, from a column typed `video` | | [Artifact](#artifact) | file name, from a column typed `artifact` | | [State Timeline](#state-timeline) | system, timestamp, state | | [Histogram](#histogram) | value, or series and value | | [Pie Chart](#pie-chart) | label, or label and value | A chart that no system template draws, such as an XY path where both axes are positions, needs a [custom template](custom-templates/). ### Line Chart The line template expects exactly three columns in order: a series identifier, then the x value, then the y value. Each row is `[series_name, x_value, y_value]`. Different `series_name` values produce multiple series on the same chart. The axis titles are taken from the column names at positions 2 and 3, so use descriptive aliases with units (e.g. `"Time (s)"`, `"Speed (m/s)"`). Emitted timestamps are in nanoseconds; divide by `1E9` to show seconds. Example config: YAML ``` Distance to Goal: type: test description: Distance to each goal over time, measured from odometry. Each line represents a different goal. query_string: | SELECT goal_name as group_name, timestamp / 1E9 AS "Time (s)", distance_m as "Distance to Goal (m)" FROM goal_distance; template_type: system template: line ``` ### Bar Chart The bar template uses the same shape as the line template: three columns `[series, x, y]` and rows `[series_name, x_value, y_value]`. It is well suited to aggregated or categorical comparisons (e.g. per experience, per goal). Example config: YAML ``` Maximum Localization Error: type: batch description: Maximum position difference between odometry and AMCL localization across all experiences. query_string: | SELECT 'Maximum', m.experience_name as "Experience Name", MAX(position_diff_m) as "Maximum Localization Error (m)" FROM pose_difference pd JOIN metadata m on pd.job_id = m.job_id GROUP BY m.experience_name ORDER BY m.experience_name; template_type: system template: bar ``` #### Click-through links Bar charts support an optional click-through feature: each bar can link to a specific page within SignalFlag (e.g. a batch, test, or experience). Click-through is most useful in [Dashboards](dashboards/) where you'll be aggregating data from tests over time. To enable click-through, include a `link_path` column in your query. Hovering over a bar will expose the link, and clicking it will navigate to the target page: The `link_path` value must be a path under SignalFlag (third-party URLs are not supported). You are responsible for constructing the path yourself by interpolating the relevant IDs into the query. All the data you need to construct the path is available when running queries: project_id, batch_id, test_id, experience_id, and more. View the `metadata` topic in the app to see what is available. Example config, for the metric seen above: YAML ``` altitude over time: type: batch description: Maximum drone altitude per batch, with click-through to the source batch. query_string: | SELECT 'altitude', timestamp, altitudes, '/projects/' || project_id || '/batches/' || batch_id AS link_path FROM drone_altitude template_type: system template: bar ``` ### Table The table template accepts any number of columns and any number of rows. Column names become the table headers and each row is rendered as a table row. Use it for summary statistics, key-value pairs, or any tabular output. Example config: YAML ``` AMCL Covariance Calibration: type: test description: Evaluates whether AMCL's uncertainty estimates are realistic. query_string: | SELECT "Metric", "Value" FROM ( SELECT 1 as sort_order, 'Total Samples' as "Metric", CAST(COUNT(*) AS VARCHAR) as "Value" FROM covariance_accuracy UNION ALL SELECT 2 as sort_order, 'Within 1σ (target: ~68%)' as "Metric", CONCAT(CAST(ROUND(100.0 * AVG(CASE WHEN within_1_sigma = 1 THEN 1.0 ELSE 0.0 END), 1) AS VARCHAR), '%') as "Value" FROM covariance_accuracy ORDER BY sort_order ); template_type: system template: table ``` ### Scalar The scalar template expects the query to return a single value. The renderer uses the first row and first column. Optional `status` thresholds can block or warn based on a separate query (e.g. checking that a count meets a minimum). You can also provide `units`, which will be displayed after the value. Example config: YAML ``` Time to reach final goal: type: test description: Time between receiving first goal and reaching final goal. query_string: | SELECT CASE WHEN (SELECT COUNT(*) FROM time_to_goal) != 3 THEN 75.0 ELSE sum(time_s) END FROM time_to_goal; template_type: system template: scalar units: "s" status: query_string: SELECT '1' FROM time_to_goal HAVING COUNT(*) < ? block: 3 ``` ### Image The image template expects one column whose values are image identifiers (e.g. filenames or paths) available in the job logs. Each row produces one image in the metric output. Use the `image` type and template for `.png`, `.jpg` and `.gif` files, animated GIFs included. Do not type a GIF as `video`: it syncs, uploads and renders with no error, but the app shows a video player that cannot play it. Note Any image referenced in your emissions file is uploaded individually so that the metric can resolve it by filename, even if you write it to a nested subdirectory beneath `/tmp/resim/outputs/` (which is otherwise zipped on upload). At most 100 emission-referenced media files are uploaded individually per run. See [Build Images](../../setup/build-images/) for details on output handling. Example config: YAML ``` Stereo Camera Feed: type: test description: Camera feed from navigation, sped up 2x, starting after first goal received. query_string: SELECT filename FROM camera_gif template_type: system template: image ``` ### Video The video template expects one column whose values are video identifiers (e.g. filenames or paths) available in the job logs. Each row produces one video in the metric output. Use the `video` type and template only for `.mp4` and `.webm` files. GIFs are images; see [Image](#image). Note As with image metrics, any video referenced in your emissions file is uploaded individually so that the metric can resolve it by filename, even if you write it to a nested subdirectory beneath `/tmp/resim/outputs/`. At most 100 emission-referenced media files are uploaded individually per run. Example config: YAML ``` Stereo Camera Feed: type: test description: Camera feed from navigation, starting after first goal received. query_string: SELECT filename FROM camera_video template_type: system template: video ``` ### Artifact The artifact template expects one column whose values are file names of files in the job outputs. Each row produces one artifact. Each artifact shows its name and size alongside a download button. `.mcap` and `.bag` files also get an "Open in Foxglove" button. Text files — `.txt`, `.log`, `.md`, `.json`, `.yaml`, `.yml`, `.csv`, `.xml`, `.toml` — can be expanded to read their contents inline, up to 1 MB; larger files are download only. A topic backing an artifact metric just needs a column of file names: YAML ``` topics: recordings: schema: filename: artifact ``` JSON ``` {"$metadata": {"topic": "recordings", "timestamp": 0}, "$data": {"filename": "trace.mcap"}} ``` Note As with image and video metrics, any file referenced by an artifact metric in your emissions file is uploaded individually so that the metric can resolve it by filename, even if you write it to a nested subdirectory beneath `/tmp/resim/outputs/`. This counts toward the same 100 emission-referenced media file cap shared with image and video. Example config: YAML ``` Recordings: type: test description: Recording and notes captured during the run. query_string: SELECT filename FROM recordings template_type: system template: artifact ``` #### Seeking to a point in time An artifact metric on an [event](#event-emissions) can set an optional `timestamp`. The artifacts then show it, and the "Open in Foxglove" button opens the recording at that moment. JSON ``` {"name": "recording", "type": "artifact", "value": ["trace.mcap"], "timestamp": 1773351267250000000} ``` `timestamp` accepts: - Epoch nanoseconds, the same clock as MCAP log times, as an integer or a string of digits: `1773351267250000000` or `"1773351267250000000"`. Floats such as `1773351267.25` or `1.77335126725e18` are rejected because they cannot hold epoch nanoseconds exactly. In Python, `time.time_ns()` returns an integer. - An RFC 3339 datetime with a `Z` or `±hh:mm` offset and up to nine fractional digits: `"2026-03-12T21:34:27.25Z"` or `"2026-03-12T18:34:27.25-03:00"`. Every format is stored as a UTC time with nanosecond precision, for example `2026-03-12T21:34:27.250000000Z`. The artifact list shows it to the millisecond, such as "Mar 12, 2026 21:34:27.250 UTC", and the full value on hover. Use the recording's own clock: the timestamp is not derived from the event's timestamp, and it is not checked against the recording's time range. A value in any other format, such as a float or a datetime without an offset, makes that metric an error chart. ### State Timeline The state timeline template shows discrete states over time for one or more systems. The query must return exactly three columns in order: system identifier, timestamp, and state name. Each row is `[system_name, timestamp, state_name]`. Use different `system_name` values to show multiple systems. Consecutive rows with the same state are merged into segments. The y-axis title comes from the alias you give the system column, and each unique state is assigned a color from the SignalFlag palette. The timestamp column may be either nanoseconds counted from the Unix epoch, or a datetime string such as `2026-03-15T00:00:00Z` (`from_unixtime(...)` produces one). The two formats may not be mixed within a single result. Example config: YAML ``` Goal Status: type: test description: Status of the goals over time. query_string: | SELECT 'Navigation' as "System", timestamp, state FROM goal_status; template_type: system template: state_timeline ``` #### Elapsed time or timestamps The x-axis can show either elapsed time or wall-clock time, set with the `time_axis` display setting (see [Customizing charts](#customizing-charts)): | `time_axis` | X-axis | | ----------- | ----------------------------------------------------------------------------------- | | `elapsed` | Seconds since the earliest row, so the axis starts at 0. Titled "Elapsed time (s)". | | `absolute` | Wall-clock timestamps. Titled "Time". | Omit it and the timestamp column decides: a numeric column is drawn as elapsed time, a datetime column as timestamps. Set it explicitly to get the other one — for example, to draw a column of epoch nanoseconds as wall-clock time: YAML ``` Goal Status: type: test description: Status of the goals over wall-clock time. query_string: | SELECT 'Navigation' as "System", timestamp, state FROM goal_status; template_type: system template: state_timeline template_settings: display: time_axis: absolute ``` ### Histogram The histogram template shows the distribution of a single numeric column. The query returns either one column (the values) or two columns `[series, value]` to compare multiple distributions on the same chart; each row is `[value]` or `[series_name, value]`. Different `series_name` values are overlaid with reduced opacity so overlapping distributions stay legible. The x-axis title comes from the alias you give the value column, so use a descriptive one with units (e.g. `"Speed (m/s)"`). Example config: YAML ``` Speed histogram: type: test description: Distribution of drone speeds. Single value column, so the series group is auto-injected. query_string: SELECT speeds AS "Speed (m/s)" FROM drone_speed template_type: system template: histogram ``` Bins are chosen automatically, and the y-axis shows the raw count of values per bin. Both are adjustable from **Customize Chart** on the metric — the chart above is this metric with percent normalization applied: - **Bins** — the maximum number of bins (1–1000). Leave it empty to keep automatic binning. - **Normalization** — what the y-axis measures: `Count` (raw values per bin, the default), `Percent` (each bin's share of the total), or `Density` (count per x-axis unit, useful when comparing distributions of differing sample sizes). The y-axis title follows this setting. ### Pie Chart The pie template shows how a whole divides into parts. The query returns either one column (the labels, each row counted) or two columns `[label, value]`, where the value column is summed per label. Slice names come from the values in the first column. Example config: YAML ``` Speed pie: type: test description: Share of samples in each speed band query_string: > SELECT CASE WHEN speeds > 13 THEN 'fast' WHEN speeds > 8 THEN 'cruising' ELSE 'slow' END AS "Band", count(*) AS "Samples" FROM drone_speed GROUP BY 1 template_type: system template: pie ``` Slices are ordered largest first, labelled with their percentage, and capped at 25 — anything past the cap combines into a single `Other` slice. All three are adjustable from **Customize Chart** on the metric: - **Slice labels** — `Percentage` (the default), `Value`, `Label and percentage`, or `None`. - **Max slices** — how many slices to draw (1–100) before the remainder folds into `Other`. - **Slice order** — `By size` (the default) or `Query order`, which preserves the order your query returned. A pie has no axes, so it takes no `xaxis` or `yaxis` settings and has no gridlines. ### Customizing charts Chart templates read an optional `template_settings` block on the metric. It has four sections, all optional: YAML ``` Distance to Goal: type: test query_string: ... template_type: system template: line template_settings: xaxis: label: Time (s) yaxis: label: Distance (m) min: 0 max: 50 series: - group_name: goal_a color: "#D3FAA3" display: legend: bottom grid: false ``` | Section | Keys | | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `xaxis`, `yaxis` | `label` overrides the column-derived axis title. `min` and `max` fix the axis range; they must be given together, both numeric, with `min` less than `max`. | | `series` | A list of per-series overrides, each with a `group_name` matching a value from the query's series column, and a `color` as a quoted hex string (e.g. `"#FF0000"`). Series with no override keep cycling the default palette. | | `display` | Chart-level options, listed below. | #### Display options | Option | Values | Meaning | | ------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `legend` | `top` (default), `bottom`, `left`, `right`, `hidden` | Where the legend sits, or `hidden` to omit it. | | `grid` | `true` (default), `false` | Show or hide axis gridlines. | | `bar_mode` | `grouped` (default), `stacked` | Bar charts only: group bars side by side or stack them. | | `bins` | 1–1000 | Histograms only: maximum number of bins. Omit to let the chart choose. | | `histnorm` | `count` (default), `percent`, `density` | Histograms only: raw bin counts, each bin's share of the total, or count per x-axis unit. | | `text_info` | `percent` (default), `value`, `label_percent`, `none` | Pie charts only: what each slice is labelled with. | | `max_slices` | 1–100 (default 25) | Pie charts only: how many slices to draw before the remainder folds into a single "Other" slice. | | `sort_slices` | `true` (default), `false` | Pie charts only: sort slices descending by value, or keep the order the query returned. | | `time_axis` | `elapsed`, `absolute` | State timelines only: elapsed seconds since the earliest row, or wall-clock timestamps. See [Elapsed time or timestamps](#elapsed-time-or-timestamps). | #### What each template accepts Settings that a template does not support are rejected when the config is validated, with the offending key named in the error. | Template | `xaxis` | `yaxis` | `series` | `display` | | ------------------------------------- | --------------------- | --------------------- | -------- | -------------------------------------------------- | | Line | `label`, `min`, `max` | `label`, `min`, `max` | `color` | `legend`, `grid` | | Bar | `label`, `min`, `max` | `label`, `min`, `max` | `color` | `legend`, `grid`, `bar_mode` | | Histogram | `label`, `min`, `max` | — | `color` | `legend`, `grid`, `bins`, `histnorm` | | Pie | — | — | `color` | `legend`, `text_info`, `max_slices`, `sort_slices` | | State Timeline | `label` | — | — | `legend`, `grid`, `time_axis` | | Table, Scalar, Image, Video, Artifact | — | — | — | — | Histograms have no `yaxis` section: the chart bins the x values itself, and the y-axis title follows `histnorm`. Pie charts have no axes at all, so neither axis section nor `grid` applies, and `series` overrides key off the slice label rather than a series column. ### Custom templates If the system templates above don't fit, you can author a Plotly chart yourself with a Liquid template. See [Custom Metric Templates](custom-templates/) for the full guide. ## Metadata Schema When you `SELECT *` on your topics, you will notice some additional metadata such as `batch_id` and `job_id` are returned. These can be used to join against a special `metadata` table which contains information about your build, experience, and more. The `metadata` table has one row per job in the batch. Batch metrics (`type: batch`) query across all rows. This allows you to, in something like a batch metric, compute - what was the min, average, and max speed, for each experience in my test set? - how did the performance of this metric vary across sunny, cloudy, and rainy test scenarios? An example batch metric: "How does the min, avg, and max speed vary across each experience?" SQL ``` SELECT m.experience_name, MIN(speed), AVG(speed), MAX(speed) FROM drone_speed d JOIN metadata m on d.job_id = m.job_id GROUP BY m.experience_name; ``` If you want to see all metadata available you can run this query: SQL ``` SELECT * FROM metadata ``` ### Column reference | Column | Type | Description / Observed values | | -------------------------- | ------------- | ---------------------------------------------------------------------------------------------------- | | `org_id` | string | Organisation identifier, e.g. `"resim.ai"` | | `batch_id` | string (UUID) | ID of the batch this job belongs to | | `job_id` | string (UUID) | Unique identifier for the individual job | | `project_id` | string (UUID) | SignalFlag project ID | | `branch_id` | string (UUID) | Branch ID within the project | | `branch_name` | string | Human-readable branch name, e.g. `"main"` | | `build_id` | string (UUID) | ID of the build under test | | `build_name` | string | Human-readable build name | | `build_creation_timestamp` | timestamp | When the build was created | | `experience_id` | string (UUID) | ID of the experience (scenario) for this job | | `experience_name` | string | Human-readable experience name | | `experience_tag_ids` | string[] | UUIDs of the experience tags attached to this job | | `experience_tag_names` | string[] | Names of the experience tags attached to this job | | `test_suite_id` | string (UUID) | ID of the test suite | | `test_suite_name` | string | Human-readable test suite name | | `test_suite_revision` | int | Revision number of the test suite | | `job_status` | string | Raw execution status — e.g.: `'SUCCEEDED'`, `'FAILED'` | | `job_metrics_status` | string | Metrics evaluation status — e.g. `'PASSED'`, `'FAILED'` | | `job_conflated_status` | string | Combined status used for pass/fail decisions — e.g.: `'PASSED'`, `'ERROR'`, `'BLOCKER'`, `'WARNING'` | | `custom_field_keys` | string[] | Custom field names set on the job (may be `[]`) | | `custom_field_values` | string[] | Custom field values, parallel to `custom_field_keys` (may be `[]`) | | `time` | timestamp | When the relevant job started | ### Array column usage `experience_tag_names` and `experience_tag_ids` are Trino arrays. Common patterns: SQL ``` -- Check membership WHERE contains(experience_tag_names, 'my_tag') -- Filter to tags matching a prefix, take the first result (1-based indexing) filter(experience_tag_names, x -> starts_with(x, 'my_prefix_'))[1] -- Conditional count across jobs count_if(job_conflated_status = 'PASSED') -- Group jobs by a tag prefix WITH classified AS ( SELECT filter(experience_tag_names, x -> starts_with(x, 'my_prefix_'))[1] AS group_name, job_conflated_status FROM metadata WHERE contains(experience_tag_names, 'my_tag') ) SELECT group_name, count_if(job_conflated_status = 'PASSED') AS passed FROM classified WHERE group_name IS NOT NULL GROUP BY group_name ``` # Query Data from External Tools Everything your tests emit lands in SignalFlag's datalake, the same data that powers [metrics](../) and [dashboards](../dashboards/). If you want that data somewhere else, for example a Grafana dashboard your team already uses, a BI tool, a notebook or a scheduled job, you can query it directly instead of copying it into another database. You send one SQL query over HTTPS and get the rows back in the same response. API addresses The APIs keep their original `resim.ai` addresses (`api.resim.ai`, `bff.resim.ai`). Use them exactly as shown on this page. ## Before you start You need three things: - **A read-only [API key](../../../setup/api-keys/).** An org admin can create one in the web app. It can read your organization's data and run queries, but cannot change anything. Keep it on the server side of whatever tool uses it, and don't put it in public repositories or public-facing interfaces: anyone who finds it can use it until it expires or is revoked. - **A project ID.** - **A branch ID.** Every query reads exactly one branch: that branch's metrics config decides which topics and columns exist, and only that branch's data is returned. To compare branches, run one query per branch. You can find project and branch IDs in the [web app](https://app.signalflag.ai), with the [CLI](../../../setup/cli/) (`signalflag projects list`, `signalflag branches list`), or through the API with the same key: Bash ``` curl -s https://api.resim.ai/v1/projects//branches \ -H "Authorization: Bearer $SIGNALFLAG_API_KEY" ``` Write and test your SQL first in the [web app's](https://app.signalflag.ai) metrics editor or with your agent (see [Build dashboards with an agent](#build-dashboards-with-an-agent)). The query language and the available topics are the same ones described in [Metrics](../) and [Dashboards](../dashboards/). ## Run a query Send a `POST` request to `https://bff.resim.ai/api/v1/query` with the API key as a bearer token and the query as JSON: Bash ``` curl -s https://bff.resim.ai/api/v1/query \ -H "Authorization: Bearer $SIGNALFLAG_API_KEY" \ -H 'Content-Type: application/json' \ -d '{ "projectId": "", "branchId": "", "sql": "SELECT batch_name, avg(speeds) AS avg_speed FROM drone_speed GROUP BY batch_name", "limit": 1000 }' ``` JSON ``` { "queryId": "4b0a6c1e-0f53-4f0c-9d0e-2a51c1f7e9b2", "status": "SUCCESS", "error": null, "columns": ["batch_name", "avg_speed"], "records": [{ "batch_name": "nightly-1042", "avg_speed": "8.93404" }], "rowCount": 1, "truncated": false } ``` ### Request fields | Field | Required | Description | | ------------ | -------- | -------------------------------------------------------------------------- | | `projectId` | Yes | The project to query. | | `branchId` | Yes | The branch whose metrics config and data the query reads. | | `sql` | Yes | One `SELECT` or `WITH` statement, without a trailing semicolon. | | `batchId` | No | Only rows from this batch. An empty value means no filter. | | `jobId` | No | Only rows from this job (test) of a batch. An empty value means no filter. | | `parameters` | No | Values for `?` placeholders in the SQL. | | `limit` | No | Maximum rows to return, from 1 to 10,000. Defaults to 1,000. | ### Response | Field | Description | | ----------- | -------------------------------------------------------- | | `status` | `SUCCESS`, `FAILED` or `CANCELLED`. | | `error` | The reason a query failed, when `status` is `FAILED`. | | `columns` | Column names, in order. | | `records` | One object per row, keyed by column name. | | `rowCount` | Number of rows returned. | | `truncated` | `true` when more rows exist than `limit` allowed. | | `queryId` | Identifier of the query, useful when contacting support. | Values in `records` arrive as strings, as the query engine returns them. Set the column type (number, time) in the tool that reads them. Give every selected column a unique name (`SELECT a.x AS a_x, b.x AS b_x`): `records` is keyed by column name, so two columns with the same name collapse into one. ## Limits - **Rows:** up to 10,000 per request. If `truncated` is `true`, aggregate in SQL rather than pulling raw rows. - **Time:** a request waits about 55 seconds. A query still running after that is stopped and the request fails with `Query timeout`. Filter by batch or time range, and aggregate, to keep queries short. - **First run:** the first time a query runs after new data arrives it reads from storage and can take tens of seconds. Repeating the same query is usually fast until more data lands. - **Rate:** 120 requests per minute per API key, and 600 per minute for your whole organization, shared with your agents' tool calls. A request over the limit gets HTTP 429 with a `Retry-After` header. Every panel of a dashboard is one request per load, so a 60-panel dashboard can load twice a minute on one key. Refresh dashboards every few minutes, not every few seconds. To raise these limits for your organization, contact [info@signalflag.ai](mailto:info@signalflag.ai). - **Cost:** queries use your organization's credits. If the organization runs out, requests fail with `ORG_SUSPENDED` until credits are added. ## Errors - A result with `status: FAILED` means the query ran and failed. `error` has the reason, usually a SQL problem such as an unknown column. - Any other error is a non-200 response with a body like `{"error": {"code": "invalid_argument", "message": "sql must start with SELECT or WITH"}}`: | Status | `code` | Meaning | | ------ | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | 400 | `invalid_argument` | The request was rejected before running. The message says why, for example a missing field, SQL that is not a `SELECT` or `WITH`, or `Query timeout`. | | 401 | `unauthorized` | The API key is wrong, has expired or was revoked. Create a new one. | | 402 | `ORG_SUSPENDED` | The organization is out of credits. | | 404 | `not_found` | The project or branch does not exist in your organization. | | 429 | `RATE_LIMITED` | Wait for the `Retry-After` header's seconds and retry. | | 5xx | `internal` | A problem on our side. Retry with a backoff. | ## Example: Grafana Grafana reaches the API through the [Infinity data source plugin](https://grafana.com/grafana/plugins/yesoreyeram-infinity-datasource/). Install the [Grafana Image Renderer](https://grafana.com/grafana/plugins/grafana-image-renderer/) as well if you want to export panels as images or let an agent read them through the Grafana MCP server. To start from a working dashboard instead of an empty one, import one of the [dashboard templates](../dashboard-templates/) once the data source below is set up. ### Data source Create a read-only API key first (see [Before you start](#before-you-start)), and name it after the dashboard or Grafana instance that uses it. 1. Install the Infinity plugin and add an Infinity data source. 1. Under **Authentication**, choose **Bearer Token** and paste the key. 1. Under **Allowed hosts**, add `https://bff.resim.ai` and `https://api.resim.ai`. Grafana refuses to send the key anywhere else. Every query below uses the same settings: type **JSON**, parser **Backend**, method **POST**, URL `https://bff.resim.ai/api/v1/query`, root selector `records`, and the request as a raw JSON body. ### Variables Add these dashboard variables so every panel follows the same branch and batch: - `project`: a **Constant** with your project ID. - `branch`: a **Query** variable on the Infinity data source, type **JSON**, URL `https://api.resim.ai/v1/projects/${project}/branches`, root selector `branches`, with columns `name` as `__text` and `branchID` as `__value`. - `batch` (optional): a **Query** variable on the same data source, with this body and columns `label` as `__text` and `batch_id` as `__value`. Batch names are not unique (every run of the same test suite can share one), so the label adds the start of the batch ID, and the newest batch comes first: JSON ``` { "projectId": "${project}", "branchId": "${branch}", "sql": "SELECT concat(batch_name, ' (', substr(batch_id, 1, 8), ')') AS label, batch_id FROM metadata GROUP BY batch_name, batch_id ORDER BY min(time) DESC" } ``` - `job` (optional): the same kind of variable for the tests of the selected batch, with columns `label` as `__text` and `job_id` as `__value`: JSON ``` { "projectId": "${project}", "branchId": "${branch}", "batchId": "${batch}", "sql": "SELECT experience_name AS label, job_id FROM metadata GROUP BY experience_name, job_id ORDER BY experience_name" } ``` Panels pass these as `"batchId": "${batch}"` and `"jobId": "${job}"`. When a variable has no value, Grafana sends an empty string, which the API treats as no filter: the panel reads the whole branch. ### Panels For each panel, use the Infinity data source with the settings above and a body such as: JSON ``` { "projectId": "${project}", "branchId": "${branch}", "batchId": "${batch}", "sql": "SELECT experience_name, avg(speeds) AS avg_speed FROM drone_speed GROUP BY experience_name" } ``` Then, under **Columns**, add each column with its type (`String`, `Number`, `Timestamp`). Without types, Grafana treats every value as text. The backend parser returns columns in alphabetical order, not in the order of your SQL. To set the order of a table or stat panel, add an **Organize fields by name** transformation and arrange the columns there. For a trajectory or any other plot of one column against another, use the **XY chart** panel with automatic series mapping, and select just the two columns, for example `SELECT x, y FROM ego_position ORDER BY timestamp` with `"jobId": "${job}"`. To follow the dashboard's time range, filter on the `time` column in the SQL, wrapping Grafana's variables as epoch seconds: SQL ``` WHERE time >= TIMESTAMP '1970-01-01 00:00:00' + INTERVAL '${__from:date:seconds}' SECOND AND time < TIMESTAMP '1970-01-01 00:00:00' + INTERVAL '${__to:date:seconds}' SECOND ``` The `time` column is in UTC. Grafana formats `${__from:date:}` in the viewer's browser timezone, so a formatted date such as `${__from:date:YYYY-MM-DD HH:mm:ss}` shifts the range by the viewer's UTC offset; epoch seconds do not. Use this form rather than functions such as `from_unixtime` or `from_iso8601_timestamp`: repeated queries are answered from a cache that does not support every query-engine function, and a query the cache cannot run is slower. When a panel shows "no results found" Infinity does not always display the API's error message on the panel. If a panel is empty, open the panel's **Query inspector** and look at the raw response: a SQL error appears in `error`, and a rejected request in the `error` object of the body. ## Build dashboards with an agent A coding agent connected to two MCP servers can do most of this for you: the [SignalFlag MCP server](../../mcp/server/) to explore your data and test SQL, and the [Grafana MCP server](https://github.com/grafana/mcp-grafana) to create the dashboards. ### Connect both servers Using Claude Code as the example: Bash ``` # SignalFlag: sign in through your browser on first use claude mcp add --transport http signalflag https://bff.resim.ai/mcp # Grafana: a service account token with the Editor role claude mcp add grafana \ -e GRAFANA_URL=https://grafana.example.com \ -e GRAFANA_SERVICE_ACCOUNT_TOKEN= \ -- docker run --rm -i -e GRAFANA_URL -e GRAFANA_SERVICE_ACCOUNT_TOKEN mcp/grafana -t stdio ``` Set up the Infinity data source yourself first, as described above. The Grafana MCP server cannot store data source secrets, and an Editor service account cannot change data sources. ### Ask for a dashboard Describe what you want to see, and name the project and the data source: Text ``` Using the SignalFlag MCP, look at the topics on the main branch of project "drone-nav" and draft SQL for: average and max speed per batch, speed over the run for a selected batch, and a per-experience table. Test each query with query_emissions. Then use the Grafana MCP to build a dashboard on the "SignalFlag datalake" Infinity data source, with project, branch and batch variables as described in docs.signalflag.ai/guides/metrics/external-access. ``` The agent typically: 1. Lists your topics and columns with `list_topics`. 1. Writes the SQL and checks each query against real data with `query_emissions`. 1. Reads the `export-data` skill, which explains the query endpoint, its limits and the Grafana setup. 1. Creates the dashboard, its variables and its panels through the Grafana MCP, and runs each panel's query to confirm it returns data. Review the dashboard before you share it. In particular, check that refresh intervals are reasonable, since every panel refresh is a query that uses your organization's rate limit and credits. # Sessions A **session** is a recording of your robot operating in the real world — one or more MCAP files in cloud storage — registered in SignalFlag so the platform can evaluate it. An evaluated session's field data lands in the same data lake as your simulation results, so the same [metrics](../metrics/), events and [A/B comparison](../ab-comparison/) tools apply to it. Getting your recordings into SignalFlag SignalFlag registers your recordings as sessions and runs their evaluations; these pages show the results. To get your recordings connected, talk to us in your shared Slack channel or at [info@signalflag.ai](mailto:info@signalflag.ai). Sessions and their evaluations will then appear in the library automatically. ## The session library Sessions live under **Organize > Sessions**. Each card shows the session's name, description, recording location, creation time and tags, plus the state of its latest evaluation. A session that has never been evaluated reads **Unprocessed**; otherwise the card shows the evaluation's status, such as **Passed** or **Warning**, and its event count. ## The session evaluation page Opening an evaluated session goes straight to its **Session Evaluation** page. A session that has not been evaluated opens a simpler page marked **Not evaluated**. **Recording bounds** — **Start (UTC)**, **End (UTC)** and **Duration** — come from the recording inventory of this evaluation, not from when the job ran. The **event timeline** places the session's events on an elapsed axis from the start of the recording to its end. Hovering a marker shows the event's name, assessment and time; clicking it opens the event. Events too close together to draw apart share a marker, and clicking it lists each of them. Events without a usable recording timestamp are not plotted but remain on the **Events** tab. A session always shows its latest evaluation. ## Comparing two sessions Select two evaluated sessions in the library and choose **Compare**, or choose **Compare** on an evaluation page and pick the other session. **Session Compare** opens the latest evaluation of each, with the **Metrics**, **Merged Metrics**, **Events** and **Details** tabs of the [A/B comparison](../ab-comparison/) view. Unlike ordinary tests, two sessions can be compared even though they are different recordings. Each keeps its own timeline, measured from its own recording start. ## Where to go next - [Play a session recording back](playback/) - [Create session metrics with an agent](agent-metrics/) # Session recording playback SignalFlag opens a [session's](../) MCAP recordings in [Foxglove](https://app.foxglove.dev), so you can see what a metric or event looked like. ## Opening a recording Choose **View in Foxglove** at the top of a session's page. SignalFlag creates a short-lived signed link to the recording and opens it in Foxglove in a new tab. The link expires, so click again whenever you need a fresh one. If the session's folder holds several recordings, a **Recording file** prompt asks for the MCAP file name within that folder. Enter it and choose **Open recording**. ## If playback does not open - **"Allow pop-ups to open this recording, then try again."** Allow pop-ups for the SignalFlag app and click again. - **"Unable to open this recording. Try again to request a fresh link."** The request failed or named a file that is not in the session's folder. Check the file name and click again. ## Streaming large recordings Playback loads the file from cloud storage on demand. To stream large recordings instead, use [Foxglove primary sites](../../foxglove-primary-sites/). # Create session metrics with an agent The interesting question about a [session](../) is often one nobody wrote a metric for. An agent connected to the SignalFlag [MCP server](../../mcp/server/) can take your previously evaluated field session data, propose a metric over it, show you the real chart, and save it once you approve. ## Connecting In Claude Code, install the Signal Flag plugin and add the MCP endpoint under the server name `signal-flag`: Bash ``` claude plugin marketplace add resim-ai/signal-flag-plugin claude plugin install signal-flag@signal-flag-plugins --scope user claude mcp add --scope local --transport http signal-flag https://bff.resim.ai/mcp claude --chrome ``` Authenticate with `/mcp`, connect Chrome with `/chrome`, and start the workflow: Text ``` /signal-flag:explore-field-sessions ``` Local MCP configuration belongs to the directory you launch from, so run these where you intend to work. ## How it works - **It resolves what you mean.** The agent confirms your organization and resolves the project, branch and session from a link, a list, or the page you have open in the web app. - **It inspects real data.** It reads the branch's topics and schemas, the existing metric definitions, and actual rows from the evaluation. When data is missing, it names what is absent and stops that proposal rather than guessing. - **It asks about meaning.** Units, clocks, frames, state values and how to treat gaps are agreed with you, not assumed. - **It proposes new names.** Each proposal uses a metric name not already used anywhere in the branch's metrics configuration, so existing definitions are never rewritten. - **It shows the real chart.** Where your MCP host renders charts, the agent draws one there. Otherwise it uses the **Edit metric** screen in your signed-in browser, which previews without saving. If neither is possible, it says so. ## Approving and saving Nothing is saved until you approve a specific definition for a specific evaluation. Changing either needs a fresh approval. Once approved, the agent adds the metric to the evaluation you are looking at, where it appears on the **Metrics** tab. Other evaluations and existing metrics are unchanged. After saving, the agent reads the result back and reports what was stored. ## Scope and limitations - **Existing evaluations only.** The agent adds metrics to evaluations that already exist. It does not register sessions, run evaluations, inspect local MCAP files or repositories, or author emissions or metrics builds. - **New metrics only.** Editing an existing metric is ordinary [metric authoring](../../metrics/). ## Introduction This document is intended to help you build and push **build images** to an image registry from a CI service so that SignalFlag can use the images to run tests. Currently SignalFlag supports authenticating against, and pulling images from, an AWS ECR, Dockerhub or Google Artifact Registry repository. If you use a different image registry provider and would like SignalFlag to integrate with it, please get in touch. The example workflows provided are for GitLab and GitHub but almost any CI service should be able to push to ECR. If you have a suggested service to add to this list, or that you would like help configuring to push build images, please reach out to SignalFlag. Note If you already have well-established processes for pushing images build in a CI/CD environment, this guide is not required. Instead, follow the [Next Steps](./#next-steps) described below. ## Prerequisites - We recommend (although it's not mandatory) that you have built, pushed and tested an image from a local machine before setting up a CI pipeline to do so. See [Build Images](../build-images/) for guidance. - You need to have set up an image repository that SignalFlag can access, as described in [SignalFlag Data Access](../resim-data-access/). You will need the **repository URI** or: your AWS account number, the AWS region in which the account was created, and the repository name. - Your SignalFlag contact should have provided you with a **client ID** and **client secret**. These are the credentials your CI service will use to authenticate with SignalFlag. - You will need a project in the SignalFlag app with which to associate your builds. See [Projects](../projects/). ## Creating an IAM user with AWS ECR permissions Your CI pipeline will need to authenticate with AWS to push images. A thorough exploration of AWS configuration is outside the scope of this article, but as a starting point if you do not have existing AWS identities that your CI service uses, you can create an IAM user with the required permissions. You will need to create a user, create security credentials for the user, and assign the `AmazonEC2ContainerRegistryPowerUser` managed IAM policy to the user. If you have the AWS CLI installed and configured, we recommend using it rather than the browser UI for this task. See the [Command line interface](#command-line-interface) section below. If you don't have the AWS CLI set up, you can create the user in the AWS browser interface. ### Browser interface (AWS Console) Following along with the [AWS documentation](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html) as required, you need to: 1. [Create a user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html#id_users_create_console), named `ci-user` or any other name you choose. You **do not** need to enable console access for this user. 1. [Create credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html#Using_CreateAccessKey) in the form of an **access key** and **secret access key**. Store these locally in a password manager or other secure location, they are equivalent to a username and password for this CI user. 1. [Assign permissions](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_change-permissions.html#users_change_permissions-add-console) to the user so it can push to ECR. Following the instructions to "add permissions by attaching policies directly to the user", assign the `AmazonEC2ContainerRegistryPowerUser` IAM policy. This policy is managed by AWS. ### Command line interface Create a new user: Bash ``` $ aws iam create-user --user-name ci-user { "User": { "Path": "/", "UserName": "ci-user", "UserId": "AIDAWRXCWKBZSLQOSKX4V", "Arn": "arn:aws:iam:::user/ci-user", "CreateDate": "2023-08-10T18:47:20+00:00" } } ``` Create an access key pair: Note Store the access key and secret access key from the following command somewhere secure - they are static credentials equivalent to a username and password. We will add them to your CI service's secrets configuration later. Bash ``` $ aws iam create-access-key --user-name ci-user { "AccessKey": { "UserName": "ci-user", "AccessKeyId": "AKIAWRXCWKBZVEXAMPLE", "Status": "Active", "SecretAccessKey": "kKEZbvjb6UV/jEFPEED5sdcSiJUGeezDuEXAMPLE", "CreateDate": "2023-08-10T18:47:53+00:00" } } ``` Attach a policy to the new user which will allow it to push to ECR repositories. Bash ``` $ aws iam attach-user-policy --policy-arn "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryPowerUser" --user-name ci-user ``` ### Testing permissions Once you have created a user, generated credentials for it, and assigned permissions to it following one of the above methods, you may wish to test the configuration locally before configuring your CI service. To log in to your ECR repository as the CI user: Bash ``` AWS_ACCESS_KEY_ID= AWS_SECRET_ACCESS_KEY= aws ecr get-login-password --region | docker login --username AWS --password-stdin .dkr.ecr..amazonaws.com ``` Then pull and tag an example image and push it to your repository: Bash ``` docker pull public.ecr.aws/docker/library/hello-world docker tag public.ecr.aws/docker/library/hello-world .dkr.ecr..amazonaws.com/:hello-world docker push .dkr.ecr..amazonaws.com/:hello-world ``` Try pulling the image: Note This will not pull any data because the image already exists locally, but it will confirm that the image exists in the remote repository. Bash ``` docker pull .dkr.ecr..amazonaws.com/:hello-world ``` Log out from ECR in your local environment: Bash ``` docker logout .dkr.ecr..amazonaws.com ``` You have now confirmed that the CI user you've created can manage images in your ECR repository. (For more information about working with ECR images, see https://docs.aws.amazon.com/AmazonECR/latest/userguide/images.html) ## Next steps The next step is to configure your CI system to build and push images and run tests in SignalFlag: - [GitHub](github/) - [GitLab](gitlab/) # GitHub In this example, you have a GitHub repository which contains the application you would like to test. Note that you will need a SignalFlag project. You can [create a project](../../projects/) with the SignalFlag CLI. This example uses [our GitHub action](https://github.com/resim-ai/action). ## Prerequisites Referring to [GitHub's documentation about setting repository secrets](https://docs.github.com/en/actions/security-guides/encrypted-secrets#creating-encrypted-secrets-for-a-repository) as required, navigate to your repository's Settings and go to the "Secrets and variables" page in the Security section. Add the following secrets: - `AWS_ACCESS_KEY_ID` - set the value of this to the access key generated when you [set up your ECR repository for use with SignalFlag](../#creating-an-iam-user-with-aws-ecr-permissions) - `AWS_SECRET_ACCESS_KEY` - set the value of this to the secret access key generated when you [set up your ECR repository for use with SignalFlag](../#creating-an-iam-user-with-aws-ecr-permissions) - `SLACK_WEBHOOK` - set this to a Slack webhook URL (see the [Slack documentation](https://api.slack.com/messaging/webhooks)), if you want nightly summaries Also add a read & write [API key](../../api-keys/) as the `SIGNALFLAG_API_KEY` secret. An org admin creates it in Org Settings; name it after the pipeline, for example `nightly-ci`. The CLI (v1.3.0 or later) and the GitHub Action read it. If SignalFlag gave you a client ID and secret before API keys existed, `SIGNALFLAG_CLIENT_ID` and `SIGNALFLAG_CLIENT_SECRET` keep working in its place. The CLI also accepts them under the older `RESIM_` names, with a deprecation warning. Set either the API key or the client ID and secret, not both. The CLI stops with an `ambiguous authentication arguments` error if it finds both, so delete the old secrets when you switch to a key. Add a variable containing your ECR registry URL: - `ECR_REGISTRY_URL` - for example `123456789.dkr.ecr.us-east-1.amazonaws.com` ## Workflow Now you need to create a GitHub workflow by adding a file to `.github/workflows/` in your repository. Below is an example of a workflow that builds a Docker image, pushes it to an ECR repository and launches a batch in SignalFlag to test it. If you use this example, make sure to replace the following placeholder values: - `` - any commands that need to run before the Docker build, e.g. `bazel build` - `` - replace with the name of the ECR repository, e.g. the name of the image/application - `` - replace with the name of your SignalFlag project - `` - replace with the name of your SignalFlag system - `` - the test suite you want to test against (see [Test Suites](../../test-suites/)) YAML ``` name: build-and-test on: pull_request: push: branches: - "main" schedule: - cron: '0 0 * * *' jobs: build_and_test: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 - name: Build run: - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Log in to ECR uses: docker/login-action@v2 with: registry: ${{ vars.ECR_REGISTRY_URL }} username: ${{ secrets.AWS_ACCESS_KEY_ID }} password: ${{ secrets.AWS_SECRET_ACCESS_KEY }} - name: Prepare Docker metadata id: docker_meta uses: docker/metadata-action@v5 with: images: | ${{ vars.ECR_REGISTRY_URL }}/ tags: | type=sha - name: Build and push image id: docker_build uses: docker/build-push-action@v5 with: context: . file: ./Dockerfile push: true tags: ${{ steps.docker_meta.outputs.tags }} - name: Launch Batch in SignalFlag uses: resim-ai/action@v1.9.0 id: launch_batch with: api_key: ${{ secrets.SIGNALFLAG_API_KEY }} project: system: image: ${{ steps.docker_meta.outputs.tags }} test_suite: # You may use experience names or tags instead # experiences: # experience_tags: metrics-build-id: ## If you would like the action to post a link to the results on PRs: comment_on_pr: true github_token: ${{ secrets.GITHUB_TOKEN }} - name: Fetch SignalFlag CLI if: github.event_name == 'schedule' run: | curl -L https://github.com/resim-ai/api-client/releases/latest/download/signalflag-linux-amd64 -o signalflag chmod +x signalflag - name: Wait for completion and send Slack summary if: github.event_name == 'schedule' env: PROJECT_ID: ${{ steps.launch_batch.outputs.project_id }} BATCH_ID: ${{ steps.launch_batch.outputs.batch_id }} SIGNALFLAG_API_KEY: ${{ secrets.SIGNALFLAG_API_KEY }} SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }} run: | # the default wait time is one hour. If you think your batch will reliably take longer, you may need to edit this ./signalflag batch wait --project "$PROJECT_ID" --batch-id "$BATCH_ID" || exit_status=$? ./signalflag batch get --project "$PROJECT_ID" --batch-id "$BATCH_ID" --slack | \ curl -X POST -H "content-type: application/json" --data @- $SLACK_WEBHOOK exit "${exit_status:-0}" ``` # GitLab In this example, you will configure a GitLab project which contains the test application that you would like to run. Note that you will need a SignalFlag project. You can [create a project](../../projects/) with the SignalFlag CLI. Referring to [GitLab's documentation about CI variables](https://docs.gitlab.com/ee/ci/variables/) as required, navigate to your project's CI/CD Settings and scroll to and expand the Variables section. Add the following variables: - `AWS_ACCESS_KEY_ID` - set the value of this to the access key generated [above](../#creating-an-iam-user-with-aws-ecr-permissions) - `AWS_SECRET_ACCESS_KEY` - set the value of this to the secret access key generated [above](../#creating-an-iam-user-with-aws-ecr-permissions) - `SLACK_WEBHOOK` - if you want to run nightly tests with summaries, add a Slack webhook URL (see the [Slack documentation](https://api.slack.com/messaging/webhooks)) Also add a read & write [API key](../../api-keys/) as the `SIGNALFLAG_API_KEY` variable. An org admin creates it in Org Settings; name it after the pipeline, for example `nightly-ci`. The CLI (v1.3.0 or later) reads it. If SignalFlag gave you a client ID and secret before API keys existed, `SIGNALFLAG_CLIENT_ID` and `SIGNALFLAG_CLIENT_SECRET` keep working in its place. The CLI also accepts them under the older `RESIM_` names, with a deprecation warning. Set either the API key or the client ID and secret, not both. The CLI stops with an `ambiguous authentication arguments` error if it finds both, so delete the old variables when you switch to a key. If you plan to use a merge request workflow, these variables should **not** be `protected` (so that branches can use them to push images and run tests in SignalFlag), or the branches you raise MRs for should be covered by a branch protection rule. If you would like CI pipelines to be able to comment on merge requests, you also need to set a variable containing a [GitLab authentication token](https://docs.gitlab.com/ee/security/token_overview.html), either a personal access token or a project token, with at least the `api` scope. Add a [`.gitlab-ci.yml`](https://docs.gitlab.com/ee/ci/quick_start/#create-a-gitlab-ciyml-file) file to the root of the repository. Below is an example of building and pushing a Docker image to an ECR repository. If you use this example, make sure to replace the following placeholder values: - `` - replace with your AWS account number - `` - replace with the AWS region in which you have deployed your ECR repository, e.g. `us-east-1` - `` - replace with the name of the ECR repository, e.g. the name of the application - `` - replace with the name of your SignalFlag project - `` - replace with the id of your SignalFlag project - `` - the commands you run to build a Docker image containing your application - `` - the name of the Docker image created by your build - `` - the experience(s) you want to test against (see [Adding Experiences](../../adding-experiences/)), comma-separated YAML ``` stages: - build - comment # Optional - configures this workflow to post a results link if it's triggered by an MR - notify # Optional - configures this workflow to send the results of a completed nightly batch to a slack webhook variables: PROJECT_ID: push-image: stage: build # Start a Docker daemon we can use to build images services: - name: docker:dind alias: dockerdaemon # Run this job if this is an MR, a tag, or the default branch rules: - if: $CI_PIPELINE_SOURCE == 'merge_request_event' - if: $CI_COMMIT_TAG - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH variables: DOCKER_HOST: tcp://dockerdaemon:2375/ DOCKER_DRIVER: overlay2 DOCKER_TLS_CERTDIR: "" SYSTEM_NAME: script: # First, you need to build a Docker image containing your application. Put your build commands below. # For example # - docker build . -t :latest # Store our new image's URI as a variable to use later. Make sure you update these placeholder values - IMAGE_URI=.dkr.ecr..amazonaws.com/:$CI_COMMIT_SHORT_SHA # We are using $CI_COMMIT_SHORT_SHA as image tag - this variable is set automatically by GitLab to the first 8 characters of the commit that triggered the run # Using this tag lets us map built images to code (and the inverse) easily - docker tag :latest $IMAGE_URI # Log in to ECR so we can push the image. Make sure you update these placeholder values - aws ecr get-login-password --region | docker login --username AWS --password-stdin .dkr.ecr..amazonaws.com - docker push $IMAGE_URI # Install the latest version of the SignalFlag CLI - curl -L https://github.com/resim-ai/api-client/releases/latest/download/signalflag-linux-amd64 -o signalflag - chmod +x signalflag # Register our new image with SignalFlag as a build - BUILD_ID_OUTPUT=$(./signalflag builds create --system $SYSTEM_NAME --description "A quadcopter simulation" --version "$CI_COMMIT_SHORT_SHA" --project $PROJECT_ID --branch "$CI_COMMIT_REF_NAME" --image "$IMAGE_URI" --auto-create-branch --github) # Run a batch with the new build - BATCH_ID_OUTPUT=$(./signalflag batches create --project $PROJECT_ID --build-id ${BUILD_ID_OUTPUT#build_id=} --experiences "" --github) - echo $BATCH_ID_OUTPUT >> build.env # This passes data to the next job artifacts: reports: dotenv: build.env # To comment a results link for the batch above on an MR, this command uses a GitLab token from the variable $MY_GITLAB_TOKEN. You may need to change the name of this variable here or in your project's settings. comment-on-mr: stage: comment # Configure this job to run only on MRs rules: - if: $CI_PIPELINE_SOURCE == 'merge_request_event' script: # this syntax (a folded block scalar) stops YAML complaining about the colons in this string - > curl --location --request POST "https://gitlab.com/api/v4/projects/$CI_MERGE_REQUEST_PROJECT_ID/merge_requests/$CI_MERGE_REQUEST_IID/notes" \ --header "PRIVATE-TOKEN: $MY_GITLAB_TOKEN" --header "Content-Type: application/json" \ --data-raw "{ \"body\": \"View results on [app.signalflag.ai](https://app.signalflag.ai/projects/$PROJECT_ID/batches/$batch_id)\" }" slack-notify: stage: notify # Run only on a schedule - for nightly tests rules: - if: $CI_PIPELINE_SOURCE == 'schedule' script: # Install the latest version of the SignalFlag CLI - curl -L https://github.com/resim-ai/api-client/releases/latest/download/signalflag-linux-amd64 -o signalflag - chmod +x signalflag # Wait for the job to complete and capture the exit code # the default wait time is one hour. If you think your batch will reliably take longer, you may need to edit this - ./signalflag batch wait --project "$PROJECT_ID" --batch-id "$BATCH_ID" || exit_status=$? # Build the slack payload and post it using curl - > ./signalflag batch get --project "$PROJECT_ID" --batch-id "$BATCH_ID" --slack | \ curl -X POST -H "content-type: application/json" --data @- $SLACK_WEBHOOK # Exit with error code - exit "${exit_status:-0}" # optional - you may want to permit job failure for batch errors allow_failure: exit_codes: - 2 # batch failure - 5 # batch cancelled ``` # Managing your artifacts This tutorial will cover the starting point for managing your tests and other data artifacts within SignalFlag. This is a quick illustration of what those concepts are within the SignalFlag app, and how you might use them for your robot. ## Problem When you begin to scale your offline testing, you begin to generate many artifacts in the form of [experiences](../../core-concepts/#experience), versions of code to test, and metrics you want to collect. Often, you end up with many artifacts that are not relevant or compatible, so managing those artifacts becomes a burden. During development, you want to only see the tests that matter to you and your [system](../../core-concepts/#system), and ensure your metrics are managed correctly. Before you run any tests and waste time and resources doing so, you want to ensure that your [tests](../../core-concepts/#test), [metrics](../../core-concepts/#metrics), and [system build](../../core-concepts/#build) are all compatible. ## Examples This section runs through some examples of the above concepts, applied to an example basic autonomy architecture. ### Systems In this diagram, you see the sensors feed into a perception module, which feeds down into motion planning and ultimately controls. This is a basic representation of the pieces of an autonomy system, but sometimes these modules are combined or there are additional modules. The above example can be defined as its own System, which represents the end to end modules that make up the on-robot system. In the SignalFlag Platform, you could define a set of Systems as follows: **Perception**: A perception system is likely concerned with detecting everything of interest and tracking those objects over time. A perception system is likely to require high fidelity images (either real or simulated), but the metrics you care about are likely to be independent of the motion of the robot. By defining a perception System, you can isolate the tests you run and metrics you generate to only those that apply to a perception system. **Multi-Module Systems**: You can define a System in any way that is relevant to your robot. For example, the motion planner and controller in a robot system are closely tied together, but separating them for testing can still be useful. So you can define Systems for both individual modules, or the combination together to represent more of the realistic interaction of those modules on the robot. ### Metrics In this example autonomy stack, we have defined two main systems: the Perception System and the Multi Module (Motion Planning) System. These two systems would have very different metrics. For example, if you are not processing image data, it doesn't make sense to attempt to compute image processing time. To support efficiently running metrics, you could define Metrics Builds for each of these Systems that capture the types of metrics that are appropriate such as: Perception: - Classification accuracy - Precision & recall - Time to detect Multi-Module Motion Planning: - Robot State and Derivatives such as pose, velocity, acceleration of the robot. - Collision Checking - Planning metrics associated with the plans produced and safety constraints # Re-running partial batches You might have a need to re-run some subset of tests inside a batch. Maybe one experience encountered a transient error. Maybe it has non-deterministic behaviour. But you don't want to re-run all of the tests in a batch, just one or a few problematic ones. ## Limitations The tests will be re-run as if they were being freshly run now. They do not take a snapshot of what the configuration was when they were first run and re-use that data. This means that if you have updated any of the dependencies, including **system**, **image**, **experience data**, etc - then the test will run with the latest definitions of that data. When re-running tests, both the experience and metrics stages for that test will be re-run. The metrics stage will run against only the results from the new run; results from previous runs will be ignored. It is not currently possible to only re-run the metrics stage for a test re-using previously generated experience output. The Batch Metrics stage will always be re-run. It will reuse the output from any test that did not need to be re-run, combining it with the fresh output from any re-run tests, ignoring old output for anything that was superseded. Batch Metrics may also be re-run in isolation, without needing to re-run any tests within the batch. ## CLI instructions There are two ways to re-run batches using the CLI. ### Automated reruns using `batches supervise` The `supervise` command under signalflag batches is responsible for monitoring a batch run until completion, and then re-runs the subset of failed tests automatically for a set number of times. #### Configuration The `supervise` command takes several required and optional parameters. To see full documentation of each, please refer to `signalflag batches supervise --help`. ### Required parameters - `project`: the name or ID of the project to supervise - `max-rerun-attempts`: maximum number of rerun attempts for failed tests (default: 1) - `rerun-max-failure-percent`: maximum percentage of failed jobs before stopping (1-100, default: 50). This is intended to guard against re-running and wasting compute on a faulty version and only to rerun for flakiness of tests. For example, if more than 50% of tests fail, it is more likely that the code under test is failing vs failure due to non-determinism. - `rerun-on-states`: Status of test results to trigger automatic reruns on (e.g. Warning, Error, Blocker) #### Optional parameters - `batch-id`: the ID of the batch to supervise - `batch-name`: the name of the batch to supervise. One of `batch-name` or `batch-id` is necessary. - `poll-every`: interval between checking batch status, expressed in Golang duration string (default: "30s") - `wait-timeout`: amount of time to wait for a batch to finish, expressed in Golang duration string (default: "1h") #### Exit codes The supervise command returns an exit code corresponding to the final batch status: - `0`: Success - `1`: Internal error - `2`: Error - `5`: Cancelled - `6`: Timed out The exit codes can be used on CI pipelines to pass or fail a stage. #### Example Bash ``` signalflag batches supervise \ --project "my-project" \ --batch-name "my-batch-name" \ --max-rerun-attempts 3 \ --rerun-max-failure-percent 30.0 \ --rerun-on-states "Error,Warning" \ --poll-every "1m" \ --wait-timeout "2h" ``` ### Manual re-run using `batches rerun` If there is a need to partially re-run certain tests to test for flaky failures manually, we can use the `rerun` command. To re-run one or more tests: Bash ``` signalflag batches rerun --batch-id={batch id} --test-ids={test id 1, test id 2, ...} ``` Specify the test IDs (aka Job IDs) from the batch in question. Do not use (eg) experience IDs. To re-run just the Batch Metrics stage, simply specify no test IDs: Bash ``` signalflag batches rerun --batch-id={batch id} ``` # A/B Comparison An A/B comparison puts two runs next to each other and shows what changed between them: a new build against the last one that passed, a branch against main, or a single test that behaves differently in two batches. A/B comparisons work at two levels. Comparing two [test batches](../../core-concepts/#test-batch) tells you how a build performed overall. Comparing two [tests](../../core-concepts/#test) — the same [experience](../../core-concepts/#experience) run in two different batches — tells you what happened inside a single scenario. ## What the comparison shows Both runs are summarized in a pair of cards at the top of the page, grouped into **System Under Test** (**System**, **Branch**, **Build Version**) and **Test Suite** (**Name**, **Revision**, **Metrics Build**, **Version**). Any field whose value differs between the two sides is highlighted. Long values such as build versions are truncated, so it is the highlight rather than the value that tells you the two runs differ. ## Metrics: shared and unique Metrics are matched between the two runs **by name**. Metrics present on both sides are paired under **Shared Metrics**, so the same chart from each run sits at the same place on the page. Everything else appears under **Unique Metrics**, in the column of the run that produced it. Because the match is by name, renaming a metric splits the pair into two different entries, and the side-by-side reading of that metric is lost. Stable metric names keep comparisons useful over time. ## Merged Metrics **Merged Metrics** goes a step further and overlays a shared pair onto a single plot, so both runs are drawn on the same axes, and the difference between them is a distance on the chart rather than something you reconstruct across two images. Not every shared pair can be overlaid. A pair qualifies when both sides are of the same chart type and that type has a meaningful overlay. A line chart cannot be drawn onto a bar chart, and scalars, images, videos, tables and state timelines have no sensible overlaid form, so those pairs are left out. ## Comparing test outcomes When you compare two batches, the **Tests** tab holds **Test Performance Comparison**: every experience that ran in both batches, with its status on each side, under the branch and build version of the run it belongs to. The tests are split into four groups: - **Failing on just one batch** — the tests whose outcome actually changed. In a comparison against the last passing build, this is the regression and fix list, and it is normally the fastest read on a new build. - **Failing on both batches** — pre-existing failures, which is what you check to confirm that a change did not fix what it was meant to fix. - **Passing on both batches** — the stable set. - **All tests** — every experience present in both batches. Each row has its own **Compare** action, which opens the test-level comparison for that experience. That takes you from "this test regressed" to the two runs' metrics side by side without going back through the batch list. # SignalFlag HiL Agent ## Introduction An important part of testing embodied AI is hardware-in-the-loop testing or HiL. This is testing that involves communicating with real hardware. HiL testing complements simulation-based testing and is often run when changes are merged to a default branch, or before a release. The SignalFlag Agent is designed to facilitate HiL testing by integrating with your existing suite of tests, allowing HiL tests to be triggered and the results to be analyzed using the same tools as simulation-based testing. The SignalFlag Agent works by polling SignalFlag for tasks so there is no need to open ports or adjust firewall rules to allow inbound traffic. ## Prerequisites The SignalFlag Agent is currently tested against Linux on amd64 and requires Docker (version 27 or later). Note The user running the Agent needs permission to use the Docker API. In some environments this means adding the user to the `docker` group. If you can do `docker run hello-world` you're ready to go. ## Installation Pre-built binaries are available for linux-amd64, linux-arm64, darwin-arm64 (Mac OS): For Linux on AMD64: Text ``` curl -L https://github.com/resim-ai/agent/releases/latest/download/agent-linux-amd64 -o agent chmod +x agent ``` For Linux on ARM64: Text ``` curl -L https://github.com/resim-ai/agent/releases/latest/download/agent-linux-arm64 -o agent chmod +x agent ``` For Mac OS on Apple Silicon/ARM: Text ``` curl -L https://github.com/resim-ai/agent/releases/latest/download/agent-darwin-arm64 -o agent chmod +x agent ``` The Agent is open-source so you can inspect the code before you run it. You can also install the Agent directly using Go: Bash ``` go install github.com/resim-ai/agent ``` ## Configuration The Agent loads configuration from `~/resim/config.yaml`. The minimal configuration you need is as follows: Text ``` name: robot-arm-1 pool-labels: - arm username: password: ``` The name of the agent will be used to identify which agent instance ran a particular job (although uniqueness is not currently enforced.) Setting pool-labels as above will configure the agent to request jobs from SignalFlag that have been put into the pool called `arm`. This is a way to group jobs, for example based on the hardware they require. This value is a list, and the agent will receive jobs with *any* of the configured labels. Info Pool labels that begin with the prefix `resim` are reserved, so please ensure your pool labels do not have this prefix. A username and password for use by your agents will be provided by SignalFlag. Run the binary and it will start polling SignalFlag for work. By default, the agent logs to stdout and to `~/resim/agent.log` ### Network mode By default, your containers will be run as part of the default bridge network, which matches the Docker default. From this network, containers can reach services on the same network (or the internet), but not contact anything else running on the host. If you need to communicate with services running on the same host, set the following option in the agent configuration file: Text ``` docker-network-mode: host ``` This is equivalent to `docker run --net=host`. ### Privileged mode By default, your containers will not be run with elevated privileges, which matches the Docker default. If you would like your containers to be run with elevated privileges, set the following option in the agent configuration file: Text ``` privileged: true ``` This is equivalent to `docker run --privileged`. ### Passing mounts and environment variables It is possible to provide volume or socket mounts and environment variables to your test container by providing additional entries in the config, for example: Text ``` mounts: - /path/on/host:/mounted/path ... environment-variables: - HIL=true ... ``` ### Experience caching As of v1.1.0, the Agent will keep downloaded experience data on disk, avoiding repeat downloads at the start of each test. The two options of importance and their defaults are: Text ``` remove-experience-cache: false experience-cache-dir: /tmp/resim/cache ``` You can set `experience-cache-dir` to a custom path, overriding the default path to ensure the cache folder is kept between reboots of the host system. If `remove-experience-cache` is set to `true`, the Agent will clean up any cached experiences when the agent exits, keeping disk usage down. ### Other options See the [repo README file](https://github.com/resim-ai/agent) for a full list of configuration options. ## Build images The SignalFlag Agent uses the Docker daemon on the host to pull and launch images. If the image repository requires authentication, make sure the host is authenticated before running the agent by running [`docker login`](https://docs.docker.com/reference/cli/docker/login). For automatic authentication, the agent supports the [AWS ECR credential helper](https://github.com/awslabs/amazon-ecr-credential-helper/). To enable its use, ensure credentials/configuration are available in `~/.aws` and that `~/.docker/config.json` is [configured as required](https://github.com/awslabs/amazon-ecr-credential-helper/tree/main?tab=readme-ov-file#docker). ## Launching batches You can now launch batches to be run by the agent, by specifying a matching pool label: Text ``` signalflag batch create --project robot-arm --build-id 4b50f4f9-3b86-49a6-84b2-7813fd4bbcbe --experience-tags hardware-validation --pool-labels arm ``` Note that when creating a batch, the pool labels are used as an `AND`, that is, an agent will only run the batch if it is running with *all* of the labels on the batch. This is to enable selecting agents with certain capabilities, without having to create unique labels for each permutation. The status and results of the batch will be presented in SignalFlag as normal, and you can see which agent ran each batch from [HiL Agent Status](../agent-status/). ### Setting batch priority When launching a batch, you can control the order in which it will be picked up by an agent by passing the `--priority` flag: Text ``` signalflag batch create --project robot-arm --build-id 4b50f4f9-3b86-49a6-84b2-7813fd4bbcbe --experience-tags hardware-validation --pool-labels arm --priority 100 ``` The priority is an integer from `0` to `32767`. **Lower values indicate higher priority**, so a batch with `--priority 0` will be picked up before a batch with `--priority 100`. If the flag is omitted, batches use a default priority of `1000`. This is useful when you have several batches queued for the same pool of agents and you want to ensure that critical or time-sensitive work is run first, while lower-priority work (e.g. nightly regression runs) waits in the queue. ## Monitoring your agents Once your agents are checking in and running batches, you can monitor the whole fleet: which agents are online, what test each agent is running, what's queued for every pool label, and how busy your agents have been. Your HiL agents can be monitored from either the [`signalflag` CLI](../../setup/cli/) (`signalflag agents` and `signalflag pool-labels`) or the SignalFlag web app. See [HiL Agent Status](../agent-status/). ## Designing experiences The workflow we anticipate is that the agent is running on the hardware to be tested, or that the hardware is accessible over the network from the container that will run your experience. The experience container will send commands to the hardware and receive data back which it will process as required and store in preparation for the metrics step. Experience input data is currently expected to be built into the image, or accessible via S3. ## Running in the background Here is an example systemd unit file for running the agent as a systemd service: INI ``` [Unit] Description=SignalFlag Agent After=network-online.target [Service] ExecStart=/usr/local/bin/agent # Or other path as required Restart=always User=ubuntu # Replace with the user that will be running the agent [Install] WantedBy=multi-user.target ``` # SignalFlag SDK ## Introduction SignalFlag's standard workflow runs your sim (i.e. [build](../../core-concepts/#build)) inside our platform so we can manage execution, collect outputs, and generate metrics. However, if you can't or don't want to dockerize your sim, you can still generate metrics for analysis. SignalFlag's SDK allows you to run tests outside of SignalFlag, on your own infrastructure, export the results, and generate metrics for these tests. There are a few different reasons you may want to run tests on your own infrastructure, outside of SignalFlag: - You are just getting started, and want to explore our metrics framework - You want to run tests on actual hardware, and only use SignalFlag as a visualization/analysis tool - Your system is difficult to dockerize, perhaps due to special hardware requirements This guide walks you through how to use SignalFlag's Python SDK. You can run your tests wherever you like, emit structured data from each test, then upload the results to SignalFlag. The tests will appear in the SignalFlag app exactly like any other batch. Metrics required This feature utilizes the metrics framework. It is recommended to familiarize yourself with [Metrics](../metrics/). You need at least a valid metrics config file (by default `.resim/metrics/config.resim.yml`) with topics defined before running batches this way. A small, functional example is provided in the Github repo below to get you started. ## Installation Running batches outside of SignalFlag is supported via our Python SDK: Bash ``` pip install signalflag # or, if you're using uv uv add signalflag ``` Note: The signalflag package requires Python >= 3.10. Coming from `resim-sdk`? `signalflag` is the same SDK under its new name, and installing it over an existing `resim-sdk` is all the upgrade there is. The `resim.*` import paths still resolve to the same modules, so code written against `resim-sdk` runs unchanged. `pip install resim-sdk` also keeps working — see [the rename page](../../rename/) for what else the name change does and does not touch. ## Quickstart The following repository contains a working example that creates a batch with a few tests and generates some metrics: The example in this repo will create a small batch, with a couple of tests, and generate some simple metrics. ## API Documentation Basic usage involves create a `Batch`, with `Test`s inside, and `emit`-ing relevant data under each test. Python ``` from signalflag.sdk.batch import Batch from signalflag.sdk.test import Test # `DeviceCodeClient` will trigger an interactive prompt to authenticate. from signalflag.sdk.auth.device_code_client import DeviceCodeClient client = DeviceCodeClient() # Create a batch, and run the "my metrics" metrics set from your metrics config file with Batch( client=client, project_name="my-project", branch="metrics-test-branch", metrics_set_name="my metrics", # The SDK reads .resim/metrics/config.resim.yml by default. Pass metrics_config_path to use another file. ) as batch: print(f"Created batch {batch.friendly_name} with id {batch.id}") # Create a test, and emit some random data for the "position" topic with Test(client, batch, "test 1") as test: for i in range(10): test.emit("position", {"x": float(i), "y": float(i)}, i) # When finished the emitted data will be uploaded to SignalFlag so metrics processing can begin ``` Branches and versions The Batch constructor accepts a `branch` (required) and an optional `version` string. Common values for `version` include a commit SHA, a semver tag, or a build number. Using these fields can enable longitudinal analysis, such as: - How has metric X changed in my branch versus main? - How has metric Y changed between release versions 2.0 and 3.0? `branch` is required because SignalFlag performs a backwards-compatibility check when syncing a new config, ensuring you don't make destructive changes to your topics - for example, changing an string field to a integer could potentially break queries against historical data. For this reason, we recommend experimenting on a branch other than `main` when getting started. ### `Batch` parameters | Parameter | Type | Description | | --------------------- | --------------------- | ------------------------------------------------------------------------------------------------------- | | `client` | `AuthenticatedClient` | **Required.** Authenticated API client. | | `project_name` | `str` | **Required.** Name of the project to associate this batch with. Provide this or `project_id`, not both. | | `project_id` | `str` | **Required.** UUID of the project to associate this batch with. | | `branch` | `str` | **Required.** Branch name to associate this batch with. | | `metrics_set_name` | `str` | `None` | | `name` | `str` | `None` | | `version` | `str` | `None` | | `metrics_config_path` | `str` | `list[str]` | | `templates_path` | `str` | `None` | | `system` | `str` | `None` | | `test_suite` | `str` | `None` | | `test_suite_revision` | `int` | `None` | ### `Test` parameters | Parameter | Type | Description | | --------- | --------------------- | ------------------------------------------ | | `client` | `AuthenticatedClient` | **Required.** Authenticated API client. | | `batch` | `Batch` | **Required.** The parent `Batch` instance. | | `name` | `str` | **Required.** Name of the test. | **Note:** Each test is tied 1-to-1 with an Experience. The name of a test comes from the experience. This means when you do `Test(name="hello world")`, the SDK will get-or-create an experience with that name. This is mainly an implementation detail, but useful to know if you want to associate any tests with pre-existing experiences. Because of this, the test name is what links a test across batches. Two batches can be compared test by test only where the test names match, so keep test names stable from one run to the next, and put anything that changes between runs (a build, a checkpoint, a parameter) in the batch `version` or in the emitted data instead. Each `Test` writes its emissions to `emissions_.resim.jsonl` in the current working directory before uploading it. To keep these files out of your repository, run from a temporary directory and give `Batch` absolute paths for `metrics_config_path` and `templates_path`. ## Emitting data `test.emit()` writes a data point to the emissions log for that test. Topic names and schemas must match your metrics config file. You do not need to manage the emissions file yourself. The SDK handles creating and uploading it to SignalFlag automatically. The test object supports all emit methods. The metrics guide will cover these in greater depth. Python ``` test.emit(topic_name, data, timestamp) test.emit_series("odom_linear_velocity", { "x": [1.0, 1.1, 1.1, 1.2], "y": [2.0, 1.9, 1.8, 1.7], "z": [3.0, 3.0, 3.0, 3.0] }, timestamps=[0, 500000000, 1000000000, 1500000000]) test.emit_event("goal_reached", {"name": "Goal 1 Reached", ...}, timestamp=1750000000) ``` For more details on emitting data, see [emitting your data](../metrics/#emitting-your-data) ## Attaching files Use `test.attach_log()` to upload a file (such as an image, GIF, or other artifact) and associate it with a test result: Python ``` test.attach_log("run_001.mcap") ``` The file is uploaded to SignalFlag's storage and registered under the test. You can attach any file type — images, logs, MCAPs, videos, etc. `attach_log` also accepts: | Parameter | Type | Description | | ----------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `log_type` | `LogType` | `None` | | `file_name` | `str` | `None` | | `wait` | `bool` | Keyword only. Upload now and return when done, instead of in the background. Use it when you are about to delete or change the file. | Uploads run in the background by default, so keep each file in place and unchanged until the test closes. Closing the test waits for every upload, and raises `LogUploadError` if any of them failed. ### Image and Video metrics For image and video metrics, attaching the file is **required**. Your metric references the image by filename, so the file must be uploaded for the image metric to render: Python ``` test.attach_log("screen_capture_123.png") test.emit("my-image-topic", {"img": "screen_capture_123.png"}, time.time_ns()) ``` The image's filename in the emission must match the filename passed to `attach_log`: use the file's base name, not its path. The metrics engine uses this reference to retrieve and render the image. Here is how the metrics config would look for the above image metric: YAML ``` topics: images: schema: img: image metrics: images: type: test query_string: select img from images template_type: system template: image ``` ## Authentication `DeviceCodeClient` signs you in through your browser. The first time it needs a token, it prints `Please navigate to: ` and then waits until you approve the sign-in in your browser. Run it where you can see that output: in a background job or an upload script, the link reaches no one and the process seems to hang. The token is cached in `~/.signalflag/token.json` (or in `~/.resim/token.json`, if only that directory exists from an earlier install). Later runs reuse it. A token within one hour of its expiry counts as expired, and the next client starts a new sign-in. Do not share or print the cache file; it is a credential. ## Syncing a config without a batch `Batch` syncs your metrics config when it starts. To sync a config without creating a batch, for example to check that a new config is accepted, use `metrics.sync_config`: Python ``` from signalflag.sdk.auth.device_code_client import DeviceCodeClient from signalflag.sdk.bff_client import metrics metrics.sync_config( DeviceCodeClient(), "", "my-scratch-branch", config_path=".resim/metrics/config.resim.yml", templates_path=".resim/metrics/templates", ) ``` Each branch keeps its own config, and the sync checks a new config against the branch's current one. Changing a column's type is refused, and removing a topic hides its history on that branch (see [Removing topics](../metrics/#removing-topics-archiving-or-deprecating-a-topic)). Try new configs on a scratch branch first. ## Systems and test suites `Batch` can attach a batch to a [system](../../core-concepts/#system) and a [test suite](../../core-concepts/#test-suite), by name. Both must exist before the batch is created. A test suite is built from experiences that already exist, and the SDK creates an experience the first time it sees a test name. So the order is: 1. Create the system. 1. Push a first batch without `test_suite`. This creates an experience for each test. 1. Register those experiences on the system and create the test suite from them, with the metrics set it should run. See [Create Test Suites](../../setup/test-suites/). 1. Pass `test_suite=` on later batches, and `test_suite_revision=` to use a specific revision. When the list of tests changes, revise the suite to make a new revision. ## Viewing results Once the `Batch` context exits, and all metrics processing is complete, navigate to your project in the [SignalFlag app](https://app.signalflag.ai) to view the batch, its tests, and generated metrics — the same as any batch run inside SignalFlag. # Set Up SignalFlag with an AI Coding Agent An AI coding agent can help you set up tests in SignalFlag quickly with minimal tokens to onboard and use our platform to its ideal capacity with useful graphs and metrics. You point it at a project that already produces results (simulation runs, test reports, recorded robot logs, data files, model evaluations), and it does the setup work for you. The SignalFlag skills give your agent these functions: - Reviews what your runs produce. - Asks a few questions in plain language. - Writes the code that sends your results to SignalFlag, and picks charts that fit your data. - Sends a small trial first, checks that the numbers match your files, then sends the real results and gives you the links. You don't need to know how SignalFlag is organized to start. This page covers installing the SignalFlag skills, connecting your agent to your SignalFlag account, and what to ask for. **Reading time:** about 6 minutes. **Setup time:** 15 to 45 minutes, depending on how many questions you choose to answer. ## Before you start - **An AI coding agent** that supports skills and remote MCP servers, such as [Claude Code](https://code.claude.com/docs/en/overview), installed and signed in. - **A SignalFlag account**, and ideally the name of the SignalFlag project your results should go into. If you don't remember the name, say so. The agent notes it in the plan and looks it up after you approve, when it signs in. - **Python 3** on your machine. The agent creates a separate Python environment for the upload code, so your project's own packages aren't touched. - **A project with results on disk**, such as a folder of runs, a test suite you run locally, recorded logs, or CSV or Parquet files. ## Step 1: Install the SignalFlag skills Skills teach your agent how to set up and use SignalFlag. They live in the [signalskills](https://github.com/resim-ai/signalskills) repository and cover getting results you already have into SignalFlag. The MCP server also ships its own skills for running tests, diagnosing failures and other day-to-day work, listed in [Agent Capabilities](../capabilities/#skills). In Claude Code, the skills come as a plugin, which also adds the connection to SignalFlag. 1. Open Claude Code in a terminal. 1. Type these two commands, one at a time: Claude Code ``` /plugin marketplace add resim-ai/signalskills /plugin install signalskills@signalskills ``` 1. Close Claude Code and open it again, so the plugin loads. To check it worked, type `/plugin`. You should see `signalskills` in the list, enabled. 1. Clone the repository: Shell ``` git clone https://github.com/resim-ai/signalskills.git ~/signalskills ``` 1. Link the skills into `~/.agents/skills`, the shared skills folder that Codex, Cursor, Devin CLI and Devin Desktop all read: Shell ``` mkdir -p ~/.agents/skills for s in ~/signalskills/skills/signalflag-*; do ln -s "$s" ~/.agents/skills/; done ``` Linking rather than copying lets a later `git pull` update the skills in place. If your agent reads a different folder (see the table below these steps), put that folder in place of `~/.agents/skills` in both lines. 1. Restart your agent so it picks up the new skills. | Agent | Skills folder in your home directory | | ------------------ | ---------------------------------------------- | | Codex | `~/.agents/skills` | | Cursor | `~/.agents/skills` or `~/.cursor/skills` | | Devin CLI | `~/.agents/skills` or `~/.config/devin/skills` | | Devin Desktop | `~/.agents/skills` | | Gemini CLI | `~/.gemini/skills` | | GitHub Copilot CLI | `~/.copilot/skills` | | OpenCode | `~/.config/opencode/skills` | | Windsurf | `~/.codeium/windsurf/skills` | Devin in the cloud reads skills from the repositories it works in, not from your home directory, so this setup doesn't apply to it. ## Step 2: Connect your agent to your SignalFlag account The agent uses the [SignalFlag MCP server](../server/) to read your results back (statuses, numbers, charts) and confirm everything arrived correctly. The server can also set things up, such as projects and metrics configs, but launching, rerunning, canceling, archiving and deleting always come back to you as a draft to approve in the web app. See [Approving consequential actions](../capabilities/#approving-consequential-actions). The plugin added this connection in Step 1. 1. In Claude Code, type `/mcp`. 1. Choose `signalflag` from the list and select **Authenticate**. 1. Your browser opens. Sign in with your SignalFlag account and approve. 1. Back in Claude Code, `signalflag` should now show as connected. 1. Add the SignalFlag MCP server to your agent's MCP configuration, using this URL: Text ``` https://bff.resim.ai/mcp ``` The [MCP server guide](../server/#connect) has the configuration for several agents, including one-click setup for Cursor and VS Code. Any server name works, since the skills find the server by its tools. 1. Start the sign-in from your agent. Your browser opens. Sign in with your SignalFlag account and approve. You only need to do this once. Tip Separately, when the agent first sends results, it may need you to sign in once more for uploads. It will post a link in the chat. Open it, approve, and the agent carries on by itself. If your agent can't run commands in the background, it asks you to run the sign-in command yourself instead. You never need to share a password with your agent. ## Step 3: Start with your project 1. In a terminal, go to the folder of the project that has your results. 1. Start your agent there. 1. Ask for what you want in your own words. See the examples in the next section. You don't need to name the skills or use any special command, because the agent recognizes the request and starts the setup. ## Example prompts Pick the one closest to your situation, and change the details to match yours. | Your situation | Try asking | | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | You run simulations that save a folder per run | "Get our simulation runs into SignalFlag. They're in runs/." | | You have a test suite (for example pytest) you run locally or in CI | "Make my pytest run report its results to SignalFlag." | | You have recorded robot logs (for example ROS bags or MCAP files) | "Put these recordings into SignalFlag and show me how the robot did on each one." | | You have data files (CSV, Parquet, HDF5) | "Upload our drive telemetry to SignalFlag so we can explore it later." | | You train models and evaluate checkpoints | "Hook my checkpoint evaluations up to SignalFlag and rank the checkpoints." | | You want results to upload every time your test script runs | "Wire SignalFlag into `run_suite.py` so every run reports automatically." | | You replay recorded camera or sensor data through your perception stack | "Wire SignalFlag into our perception replay harness. I want to see what got worse per class and range, and scrub to the missed frames." | | You compare model versions on a labeled photo set | "Evaluate each new detector version on our photo set in SignalFlag and show me where it got better or worse." | | Your results already upload, but something looks wrong | "Our tests already upload to SignalFlag but some metrics show errors. Am I organizing this right?" | | It's already set up and you want to improve something | "Tune the controller gain and show me the progress in SignalFlag." | Once your results are in SignalFlag, the [MCP Server](../server/#your-first-run) guide has prompts for running, diagnosing and comparing tests. It helps to mention: - **Your checks after a run**: "I check whether it reached the goal and how far off the path it went." - **Who will use the results**: "My lead wants to see whether we're getting better over time." The agent sizes the charts to the reader, with a few headline numbers for a lead and more depth for an engineer debugging. - **Different kinds of tests**: "These are regression tests, and these are known failures we're tracking", or "same stack, but on sim drives and real drives". The agent keeps each kind in its own test suite so comparisons stay like for like. - **Anything off-limits**: "Don't change `run_tests.sh`." ## FAQ How does setup work after I ask? 1. The agent reads your project and your results before asking anything. 1. It asks how involved you want to be. - **"You decide"**: the agent makes the choices from what it finds, and only asks which SignalFlag project to use. Before anything is sent, it stops once and shows you everything it chose. This suits people new to SignalFlag. - **"Walk me through it"**: the agent asks one question at a time, each with a few options and its recommendation. This suits people who want to understand and shape each decision. 1. It writes a short plan in your project, named after your type of test, for example `docs/signalflag/route-test-brief.md`. It describes your tests, how they map into SignalFlag, and which charts and pass/fail checks it will set up. You can read and edit it. 1. It reads your data and proposes metrics and charts. It adds checks that flag a bad run and point to the likely cause, puts video or a replay first where your runs have them, and keeps everything else available for digging in later. It shows you the plan and waits for your go. Nothing is installed and nothing is signed in to before that. 1. It builds the upload code in your project, in its own Python environment. 1. It sends a small trial first to a separate test area in SignalFlag, and checks that the numbers there match your files. 1. It sends your real results and gives you links to the results page and the dashboard. If your project already sends results to SignalFlag, the agent reads your existing setup first, keeps what you built, answers your question, and fixes only what's wrong. Which files does the agent add to my project? - A plan file for each type of test, `docs/signalflag/-test-brief.md`. - Upload code, usually a small script or a few files, plus a settings file in `.resim/metrics/`. - A separate Python environment (for example `.venv-signalflag/`), which it adds to `.gitignore`. It only changes your existing code if you agree to it, and says exactly what it changed. Nothing is committed for you, so review the changes and commit them when you're happy. How do I keep the skills up to date? We improve the skills regularly. Type these in Claude Code, then close and reopen it: Claude Code ``` /plugin marketplace update signalskills /plugin update signalskills@signalskills ``` Type `/plugin` to see which version you have. Pull the latest version into your clone, then restart your agent: Shell ``` git -C ~/signalskills pull ``` If you copied the skill folders instead of linking them, copy them again after pulling. Which SignalFlag terms will I see? | Word | Meaning | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | Project | Your team's space in SignalFlag. Your admin usually sets it up. | | Branch | A named line of results that get charted together over time, for example all the rounds of one test suite. The agent suggests a name. | | Batch | One upload, for example one round of your test suite. | | Test | One item inside a batch, for example one scenario, one route or one seed. Keeping the same name across rounds lets SignalFlag compare them. | | Metric | A number, chart or video shown for a test or batch, sometimes with a pass/fail check attached. | | Dashboard | Charts across many batches, for example "how is this getting better over time". | The SignalFlag server doesn't show up in my agent Restart your agent after installing the skills or adding the server. In Claude Code, run `/plugin` and check that `signalskills` is enabled, then look for `signalflag` in `/mcp`. In other agents, check that the server URL in your MCP configuration is `https://bff.resim.ai/mcp`. The [MCP Server troubleshooting](../server/#troubleshooting) section explains the error codes the server returns. The sign-in link expired Links last about 15 minutes. Tell the agent "the login link expired" and it will post a new one. The dashboard looks empty or out of date A dashboard set to refresh automatically updates in the background when you open it, so the first view after an upload can show older data. Open it again a little later. A manual dashboard updates only when you click **Refresh data**. With only one round of results, trend charts show a single point until the next round. The agent asks about a run it can't identify If a run is missing information (for example which model checkpoint it used), the agent leaves it out rather than guessing. Tell it what the run was, or let it skip that run. I see extra test areas in my SignalFlag project During setup the agent sends trial uploads to separate areas whose names end in -lowres or -scratch, so your real results stay clean. You can archive them once you're happy. I'm not sure about something the agent chose Ask it, for example "Why did you pick that branch name?" or "Change the warning limit to 5 cm." Every choice is written in the plan file (`docs/signalflag/-test-brief.md`), so you can also edit it there and ask the agent to update the setup. ## Getting help Contact your SignalFlag representative or our support team, and include what you asked the agent and what happened. If your agent can export the conversation, attach that too. In Claude Code, `/export` saves it to a file. # MCP server SignalFlag's MCP server lets an agent operate the platform on your behalf. That might be a coding agent in your repository, a chat client asking about results, or a step in your CI pipeline. There is nothing to install. Your client prompts you to sign in through your browser on first use. For an agent that runs unattended, such as a step in a CI pipeline, connect with an [API key](../../../setup/api-keys/#use-a-key) instead. LLM-friendly docs Pair the MCP server with our LLM-friendly documentation, published as plain markdown following the [llms.txt convention](https://llmstxt.org): - [`/llms.txt`](/llms.txt), a curated index of the docs - [`/llms-full.txt`](/llms-full.txt), the full corpus as a single file - Any page is also available as raw markdown by appending `.md` to its URL (for example [`/setup/cli.md`](../../../setup/cli/)) Point your agent at these alongside the MCP server for full context on the platform. ## Reads, writes, and approvals Your agent can read anything you can read, and it can set things up on its own. That covers creating projects and branches, registering builds and experiences, assembling test suites, pushing metrics configs, and building dashboards. Your agent cannot launch a batch, rerun a job, cancel a run, archive anything, delete anything, change a project's agent instructions, or create or revoke an API key. Those actions produce a draft that you review and submit in the web app. The agent never executes them, no matter how it is prompted. See [Approving consequential actions](../capabilities/#approving-consequential-actions). Every write and every draft is recorded against your account and can be listed at any time. For the full picture of what an agent can do with the server, see [Agent Capabilities](../capabilities/). ## Connect Every client needs the same one thing, the server URL: Text ``` https://bff.resim.ai/mcp ``` If you use Cursor or VS Code, one click does it: [Add to Cursor](cursor://anysphere.cursor-deeplink/mcp/install?name=signalflag&config=eyJ1cmwiOiJodHRwczovL2JmZi5yZXNpbS5haS9tY3AifQ%3D%3D) [Add to VS Code](https://insiders.vscode.dev/redirect/mcp/install?name=signalflag&config=%7B%22type%22%3A%22http%22%2C%22url%22%3A%22https%3A%2F%2Fbff.resim.ai%2Fmcp%22%7D) Your editor asks you to confirm, then prompts for sign-in on first use. The manual steps for every client are below. ### Claude Code Bash ``` claude mcp add --transport http signalflag https://bff.resim.ai/mcp ``` Your browser opens a consent page, then SignalFlag sign-in. Tokens refresh on their own. If you set up SignalFlag with the signalskills plugin, it registers this server for you. See [Set Up SignalFlag with an AI Coding Agent](../coding-agent/). ### claude.ai Go to Settings, then Connectors, then Add custom connector, and enter the server URL. Use this client for asking questions about results rather than working in a repository. It can render charts inline. ### Claude Desktop Open Settings, then Developer, then Edit Config, and add the `signalflag` entry to your `mcpServers`: JSON ``` { "mcpServers": { "signalflag": { "url": "https://bff.resim.ai/mcp" } } } ``` Restart Claude Desktop. You will be prompted to authenticate through your browser on first use. ### Cursor Open Settings, then MCP, and click Add new global MCP server: JSON ``` { "mcpServers": { "signalflag": { "url": "https://bff.resim.ai/mcp" } } } ``` Cursor's callbacks are already registered. ### CI and other unattended agents A pipeline cannot open a browser, so it connects with an [API key](../../../setup/api-keys/). Send the key as a bearer header: Text ``` Authorization: Bearer ``` A read-only key can read and run queries. A read & write key can also set things up and propose drafts. Compared with signing in as yourself, there are a few differences: - A draft proposed with a key has no person behind it, so it must name a reviewer with `reviewer_email`, a member of your organization who submits it in the web app. Your pipeline can prepare a run, but a person still starts it. - Only read & write keys can propose drafts. - Keys cannot see or steer your browser tabs, and cannot list or manage API keys. If SignalFlag gave you a machine credential before API keys existed, it keeps working the same way: request a token with it and send that token instead of a key. ## Scopes On first connection you consent to three scopes: | Scope | Allows | | ---------- | -------------------------------------------------------------------------------- | | `read` | Listing and fetching anything your account can already see | | `write` | Setting up entities: projects, experiences, suites, metrics configs, dashboards | | `ui:steer` | Moving a view in a SignalFlag browser tab you have open, and showing you a toast | `ui:steer` lets an agent navigate a tab you already have open. It cannot submit anything, each tab has a steering toggle you control, and every command is recorded. It is still rolling out, so it may not be available to your organization yet. See [Agent Capabilities](../capabilities/#working-alongside-you-in-the-app). ## Your first run Ask your agent something about your tests and it should just work. There is nothing to configure and no first command for you to run. If you want somewhere to start, pick the row that matches what you have today. | Where you are | Try asking | | ------------------------------------ | ---------------------------------------------------------------------------------------- | | Nothing set up yet | "What projects do I have?" then "Create a project called nav-regression." | | A project, no experiences | "Register the scenarios in `s3://my-bucket/nav/` as experiences and tag them `nav`." | | Experiences and a build, nothing run | "Build a test suite from the `nav` experiences and draft a run against my latest build." | | Tests already running | "How did my last batch do?" or "Why did the failing tests in it fail?" | | Metrics you want to change | "Add a metric tracking median goal distance per test, and validate it before pushing." | Ask the first question whatever stage you are at. It confirms the connection works and tells you what your agent can see. Creating a project, registering experiences and pushing a metrics config all happen immediately. Running the suite does not. That comes back as a draft with a link, and nothing runs until you submit it. If your results already live on disk, such as sim runs, test reports or recorded logs, the [Set Up SignalFlag with an AI Coding Agent](../coding-agent/) guide walks your agent through getting them in. ## Rate limits and budgets | Limit | Value | | --------------------------------------- | -------------- | | Calls per user | 120 per minute | | Calls per organization | 600 per minute | | Data queries per organization | 200 per day | | Log and batch analyses per organization | 100 per day | Exceeding a per-minute limit returns HTTP 429 and a JSON-RPC error. Back off and retry after a short delay. To raise the per-minute limits for your organization, contact [info@signalflag.ai](mailto:info@signalflag.ai). The same limits cover [external metrics queries](../../metrics/external-access/#limits). The per-day budgets cover the tools that run real queries or call a model. Exhausting one returns a `budget_exhausted` error rather than failing quietly. ## Troubleshooting Errors come back with a code your agent can act on. | Code | Meaning | | ------------------------- | ----------------------------------------------------- | | `not_found` | The id does not exist, or is not in your organization | | `invalid_argument` | The arguments do not satisfy the tool's schema | | `insufficient_permission` | Your account cannot perform this operation | | `rate_limited` | Slow down and retry | | `budget_exhausted` | A daily query or analysis budget is spent | | `membership_required` | Your account is not a member of an organization yet | A missing authorization scope comes back as HTTP 403 with a `WWW-Authenticate` header, which compliant clients use to prompt you for consent again. Two things to try when a session goes badly rather than errors outright. If your agent is guessing at project names or calling tools at random, it skipped orienting itself. Tell it to run `whoami` first, then ask again. If it reports that it cannot write anything, check `whoami` for your permissions. An account with read-only permissions sees every read tool and no others. # Agent Capabilities The SignalFlag MCP server gives your agent 129 tools. You do not need to learn them. This page covers what you can ask an agent to do, which tools it will reach for, and where it has to stop and wait for you. Setting up the connection This page assumes your agent is already connected. For Claude Code, Cursor, the claude.ai connector and CI credentials, see [MCP Server](../server/). ## Three kinds of tool Every tool falls into one of three classes, and the class decides whether your agent acts or asks. | Class | What happens | Covers | | ----- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | Read | Runs immediately | 78 tools. Listing and fetching anything, log contents, metrics, analyses, quota | | Write | Runs immediately, and is recorded | 42 tools. Setting things up: projects, branches, builds, systems, experiences, tags, test suites, metrics configs, dashboards, notes | | Draft | Never runs | 8 tools. Launching, rerunning, canceling, archiving, deleting, changing agent instructions, and creating or revoking API keys | One more sits outside the three: `steer_ui_session` moves a view in a browser tab you have open, and is covered under [Working alongside you in the app](#working-alongside-you-in-the-app). Your agent can create an experience or push a metrics config on its own. It cannot launch a batch, rerun a job, cancel a run, archive an experience or delete anything. Those produce a draft that you review and submit in the web app. Every write and every draft is recorded against the account whose token the agent is using, and you can list that history at any time. ## Skills Skills are task instructions the server ships to your agent, so you do not have to explain how SignalFlag works every time. Your agent fetches one with `get_skill` after orienting itself, without being asked. See [MCP Server](../server/#your-first-run) for what that looks like from your side. | Skill | For | | ----------------------- | ---------------------------------------------------------- | | `onboard` | Getting a repository from nothing to a first drafted batch | | `run-tests` | Choosing a build and suite and drafting a run | | `diagnose-batch` | Working a failing batch back to a root cause | | `regression-check` | Comparing a branch against main | | `author-metrics-config` | Writing or fixing a metrics config | | `dashboards` | Building and refreshing dashboards | | `stage-experiences` | Bulk-registering and tagging experiences | | `containerize-sim` | Packaging a simulator into a build image | | `fleet` | Checking hardware agents and queues | | `drafts` | Working with actions that are waiting for a human | | `ui-sessions` | Working alongside you in an open browser tab | The server also ships [dashboard templates](../../metrics/dashboard-templates/) as resources (`resim://examples/