Exit

Flagsmith

Why it is the core: this is a Flagsmith experiment, not a script with a Flagsmith call in it. Flagsmith decides every arm, records every exposure, measures the outcome and carries the rollout. Take it away and none of the result can be checked.

A task's journey through Flagsmith

Scroll to drive two tasks from the queue to the rollout. Every step below is a Flagsmith feature doing real work.

A task's journey: 1. Queue; 2. Flagsmith picks the lane; 3. The lane runs; 4. Events, same identity; 5. Results; 6. Decision; 7. RollouttaskTask queuehash(identity)controllanes_v1task_costtask_solvedtask_turnstask_secondsResultschance to beatsame flag1234567
  1. Queue

    A task is one real bug from SWE-bench-Live. It waits in the queue as the Flagsmith identity swelive:<instance_id>.

  2. Flagsmith picks the lane

    The runner calls get_experiment_flag("agent_routing") for that identity. Flagsmith hashes it and serves a variant (50/50 split). The runner never chooses an arm.

  3. The lane runs

    The flag value is the routing policy. control sends worker calls to Sonnet 5.5; lanes_v1 sends them to Haiku 5.5. The exposure is recorded at this moment.

  4. Events, same identity

    After grading, the runner sends task_cost, task_turns, task_seconds and, only on a solve, task_solved, all with the identity that was exposed.

  5. Results

    Flagsmith joins the events to the exposures in its warehouse and reports, per metric, the chance each variant beats control.

  6. Decision

    The rule written before the first task reads those numbers. All three checks pass, or control stays.

  7. Rollout

    End the experiment, set the winner's value on the same flag, and the next batch of tasks gets it with no deploy.

Illustration

Move the split yourself

Flagsmith does not toss a coin per task. It hashes the task's identity to a number from 0 to 100, and the split decides which lane each number takes. Drag the divider, or focus it and use the arrow keys.

lanes_v1: 13 taskscontrol: 19 tasks010203040506070809010050

This is the registered split, 50 / 50: 13 of 32 tasks take lanes_v1, 19 take control. Drag the divider.

  1. md5("feature-state,env-key_floci-io__floci-1837")5d49fcaa4eb4b86ed8a54b6b3882a824
  2. as a number, mod 9999, scaled to 0–10092.26
  3. at or above the split of 50control lane

Real task ids from the exp1 pool (tasks/pools/exp1.txt) and Flagsmith's bucketing maths, the same as integrity/verify_assignment.py. The key is a stand-in: in the run it also holds the environment key and the feature-state id, so the lanes here are not the lanes the tasks ran in.

Experiment 1 · decided

Play the decision

When experiment 1 ended, it was stopped in Flagsmith and the winner's value was served on the same flag. Play it back, or play the outcome the rule would have given had a condition failed.

control

Frontier everywhere

Experiment 1, per task$0.0784 per task in experiment 1
Solved
34 of 76
lanes_v1

Small delegate

Experiment 1, per task$0.0340 per task in experiment 1
Solved
28 of 69

Both lanes are open, as they were while the run went on. Pick an outcome above.

Experiment 1 figures from analysis/out/numbers.json. The cars are an illustration.

What Flagsmith does in this experiment

Each job, with the file in the repo that does it.

  1. Flagsmith alone decides each arm

    For every task the runner calls get_experiment_flag("agent_routing", identifier=identity) and runs whatever policy comes back. There is no random() in the runner and no arm argument on the command line.

  2. The split is a hash anyone can recompute

    Bucketing is a deterministic hash of the identity and the experiment segment. From a saved environment document, every arm is recomputed offline with Flagsmith's own flag-engine 11.1.2, and it must match what the run recorded.

  3. Exposure is recorded where the policy is used

    The exposure is sent at the moment the policy is applied, then flushed before anything else, so a task is counted in its arm only if it really ran that arm.

  4. Events carry the same identity

    Cost, turns, seconds and solves go to Flagsmith with the identity that was exposed. Flagsmith counts only events at or after the first exposure.

  5. The warehouse gives chance to beat control

    Flagsmith's managed warehouse joins exposures to events and reports, per metric, the lift, its interval and the chance each variant beats control. That number is rule 1 of the decision.

  6. A kill switch that keeps the data clean

    routing_kill is read without an exposure. When it is on, a task runs control, sends no exposure and no events, and the ledger notes why.

  7. End the experiment, then roll out on the same flag

    The winner's value becomes the flag's value. The next batch of tasks gets it with no code change and no deploy.

  8. An agent proposes, a person approves, Flagsmith rolls out

    An agent reads Flagsmith's results through the kit's MCP tools, applies the registered rule and writes the End Experiment request as a proposal. Nothing is sent to Flagsmith until a person approves that exact proposal.

  9. The policy is remote config

    The flag's value is a JSON routing policy: models per lane, token limits, caps. The two values differ only in the worker's model, which the harness checks before it runs.

  10. Flags described as code, checked for drift

    The flags, the variant and the experiment's segment override are written as Terraform. A read-only plan must report no changes.

  11. Signed webhooks feed the flag history

    Every change to the routing flag reaches the live board as a signed Flagsmith webhook, so any edit during the run would show up in public.

  12. Feature health that cannot peek

    The runner reports the flag's health to Flagsmith from infrastructure errors and budget only. It never reads an outcome metric.

  13. Runs anywhere Flagsmith runs

    The kit works with remote and local evaluation, through the Edge Proxy, through OpenFeature, and on self-hosted Flagsmith 2.295.2.

What would break without it

The same study, hand-rolled. Each row is something a reader could no longer check.

ConcernWith FlagsmithHand-rolled
Who picks the armFlagsmith hashes the identity. The runner cannot choose.A random() call in the runner. Nobody can show it was not re-rolled.
Proof of the splitRecompute every arm offline from the saved environment document.Trust the log file the same script wrote.
Changing the routingEdit the flag value. The next task gets it.Change code, rebuild, redeploy the workers.
Counting who was in the testExposure recorded at the point of use, same identity as the events.Join two log files by hand and hope the ids line up.
Reading the resultChance to beat control per metric, from the warehouse.A notebook, written after the data is in.
Stopping a bad armFlip routing_kill. Killed tasks carry no exposure.Kill the process and clean the data afterwards.
Rolling out the winnerEnd the experiment, serve the winner on the same flag.Another deploy, another untested path.
Showing nobody touched itSnapshots, a drift-free Terraform plan and signed webhooks.A promise.

Every Flagsmith feature used, with code

Part 2

Every Flagsmith feature used

Every Flagsmith feature this project uses, in the order a task meets them, each with the code or command from the repo. Snippets are read from the files when the site is built.

An experiment with four metrics

One multivariate flag, one keyed variant, four metrics, one experiment.

The flag agent_routing (feature 306193) holds the control policy as its value and lanes_v1 as a keyed variant. The experiment body sets the split and the metrics with their expected direction. task_cost is the primary metric; task_solved is the guardrail.

flagsmith/experiment-1.json:6Source: flagsmith/experiment-1.json
"metrics": [
  {"metric": "@metric_id:task_cost", "expected_direction": "decrease"},
  {"metric": "@metric_id:task_solved", "expected_direction": "not_decrease"},
  {"metric": "@metric_id:task_turns", "expected_direction": "not_increase"},
  {"metric": "@metric_id:task_seconds", "expected_direction": "not_increase"}
],
"experiment_rollout": {
  "enabled": true,
  "rollout_percentage": 100,
  "feature_state_value": {"type": "string", "value": "@policy:control"},
  "multivariate_feature_state_values": [
    {"multivariate_feature_option": "@variant_id:agent_routing:lanes_v1", "percentage_allocation": 50}
  ]
}
flagsmith/metrics.json:11Source: flagsmith/metrics.json
"name": "task_cost",
"event": "task_cost",
"aggregation": "mean",
"direction": "down",
"expected_direction": "decrease",
"role": "primary",
"description": "US dollars per task, sent for every exposed task including capped and failed ones. Lower is better."

Starting it is one Admin API call through the Flagsmith CLI. The flag is locked while the experiment runs.

flagsmith/start_experiment.sh:16Source: flagsmith/start_experiment.sh
fs_api POST "api/v1/environments/$ENV/experiments/$1/start/" | jq '{id, name, status, started_at}'

Exposure at the point of use

The exposure is recorded where the policy is applied, once per task.

get_experiment_flag records the exposure with the variant key as its value. The runner flushes it before tracking anything else, because the SDK drops the oldest buffered event when a second one arrives too soon (DECISIONS.md D9). An invalid value fails closed to control.

harness/policy.py:79Source: harness/policy.py
def assign(client: FlagsmithLike, identity: str, traits: dict[str, object], control: RoutingPolicy) -> Assignment:
    kill = client.get_identity_flags(identity, traits).get_flag(FLAG_KILL)
    if kill.enabled:
        log.warning("routing_kill is on: %s runs control without exposure", identity)
        return Assignment("control", control, "kill_switch")

    flag = client.get_experiment_flag(FLAG_ROUTING, identifier=identity, traits=traits)
    # With max_buffer_items=1 the SDK drops the oldest buffered event when a second is tracked
    # before the first is sent, so the exposure is flushed before anything else is tracked.
    client.flush_events()
    variant = flag.variant or "control"
    try:
        policy = parse_policy(flag.value)
    except (ValidationError, json.JSONDecodeError, TypeError) as exc:
        log.error(
            "invalid %s value for %s (variant %s): %s; failing closed to control", FLAG_ROUTING, identity, variant, exc
        )
        return Assignment(variant, control, "fail_closed")
    return Assignment(variant, policy, "experiment")

Events with the same identity

Every exposed task sends its cost, turns and seconds; a solve sends task_solved.

harness/events.py:22Source: harness/events.py
sent: list[tuple[str, float | int]] = [
    (EVENT_COST, round(rec.usd, 6)),
    (EVENT_TURNS, rec.turns),
    (EVENT_SECONDS, round(rec.seconds, 3)),
]
if rec.solved:
    sent.append((EVENT_SOLVED, 1))
lines: list[dict[str, object]] = []
for name, value in sent:
    client.track_event(name, identifier=rec.identity, value=value)
    client.flush_events()  # one event in flight at a time; see harness/policy.py

The kill switch

A second flag, read without an exposure.

When routing_kill is on, a task runs the control policy, sends no exposure and no events, and is written to the ledger as kill_switch. The experiment's data never holds a task the runner forced into an arm.

infra/flagsmith/main.tf:20Source: infra/flagsmith/main.tf
resource "flagsmith_feature" "routing_kill" {
  project_uuid    = var.project_uuid
  feature_name    = "routing_kill"
  type            = "STANDARD"
  description     = "On: every task runs the control policy and records no exposure"
  default_enabled = false
  is_archived     = false
}

End the experiment, then roll out on the same flag

The decision is applied with Flagsmith, not with a deploy.

Ending an experiment takes a rollout decision. The winning variation's value becomes the flag's value, and a fresh batch of tasks runs on the same flag with no code change. The call below is the one the smoke test used to finish its own throwaway experiment.

flagsmith/smoke_test.sh:114Source: flagsmith/smoke_test.sh
flagsmith api api/v1/environments/<env>/experiments/$EXP_ID/complete/ -X POST -F rollout_decision=control

Every arm recomputed with the flag-engine

Same code path as the SDK's local evaluation, run offline.

integrity/verify_assignment.py loads a saved environment document and evaluates every identity with flagsmith-flag-engine 11.1.2. Any task whose recorded variant differs fails the check. CI runs it on every committed run.

integrity/verify_assignment.py:141Source: integrity/verify_assignment.py
result = engine.get_evaluation_result(context=context)["flags"][flag]
integrity/verify_assignment.py:11Source: integrity/verify_assignment.py
Usage: python -m integrity.verify_assignment --run runs/exp1 [--env FILE] [--out FILE]

Flags as Terraform, with zero drift

Described as code, checked with terraform plan against the live project, never applied.

An apply mid-run would publish new feature-state versions on the flag the experiment is splitting, so the CLI scripts stay the only writers. make flags-drift runs a read-only plan that must report no change.

infra/flagsmith/main.tf:10Source: infra/flagsmith/main.tf
resource "flagsmith_feature" "agent_routing" {
  project_uuid    = var.project_uuid
  feature_name    = "agent_routing"
  type            = "MULTIVARIATE"
  description     = "Routing policy JSON for the agent's main and delegate lanes. exp1 (experiment 822): registered prereg-exp1 sha256 44d715bd6bd7; rule shipped lanes_v1, rolled out. exp2 (experiment 1423): registered prereg-exp2 sha256 a04a2e207ed7; rule kept control (the lanes_v1 policy), applied by analysis/decide.py. Record: github.com/Prashant-thakur77/fork-in-the-bill"
  default_enabled = true
  initial_value   = local.control_policy
  is_archived     = false
}
infra/flagsmith/README.mdSource: file on GitHub
make flags-drift
{"drift":false,"resources":6,"plan_sha256":"e2c7...","live_versions":true}

Signed webhooks into the board

Every change to the flag reaches the public flag history.

The board's Worker takes Flagsmith's environment and audit-log webhooks, checks X-Flagsmith-Signature, and stores one row per change with no author and no raw values. The live board draws them as mileposts.

board/worker/src/app.ts:153Source: board/worker/src/app.ts
async function flagWebhook(request: Request): Promise<Response> {
  const rawBody = await readCapped(request, MAX_WEBHOOK_BYTES);
  if (rawBody === null) return json({ error: "body too large" }, 413);
  const verdict = await verifyFlagsmithSignature({
    secret: opts.flagsmithSecret ?? "",
    signatureHeader: request.headers.get("X-Flagsmith-Signature"),
    rawBody,
  });
  if (!verdict.ok) return json({ error: verdict.reason }, verdict.status);

Feature health, infrastructure only

Unhealthy on infra errors or budget, never on outcomes.

runner/health.py posts to Flagsmith's Feature health webhook when the share of infra_error tasks or the budget crosses a line. It never reads solve rates or costs per arm, so it cannot become a way to peek.

runner/health.py:4Source: runner/health.py
python -m runner.health runs/exp1 --window 20 --max-infra-rate 0.25 --budget-warn 0.9

Four evaluation modes and the Edge Proxy

Same flag, four places to read it from.

kit/forkbill/client.py:3Source: kit/forkbill/client.py
| mode         | flags come from                                  | key            |
|--------------|--------------------------------------------------|----------------|
| `remote`     | the core API, one `POST /identities/` per read  | any SDK key    |
| `local`      | the environment document, evaluated in process   | server-side    |
| `edge`       | an Edge Proxy, one `POST /identities/` per read  | any proxy key  |
| `edge-local` | the environment document served by an Edge Proxy | server-side    |

Local evaluation records exposures because the environment document carries the experiment metadata. The Edge Proxy 2.24.0 serves the right value but no variant, so edge serves flags without running an experiment, and edge-local keeps the experiment working through the proxy. The kit checks that every mode serves the same policy to the same identities.

Through OpenFeature

The official Flagsmith provider behind the kit's client interface.

kit/forkbill/openfeature.py:8Source: kit/forkbill/openfeature.py
from flagsmith import Flagsmith
from forkbill.openfeature import OpenFeatureFlagsmith

flagsmith = Flagsmith(environment_key=..., enable_events=True)

The policy is resolved as a string flag, the exposure is sent with OpenFeature track(), and every evaluation and event uses the task's identity as the targeting key.

On self-hosted Flagsmith

The kit's experiment, run end to end on your own machine.

Open-source Flagsmith 2.295.2 with experimentation on, the Flagsmith database as the warehouse, and the same flag, metrics, exposures and events as Cloud. The loop is a deterministic fake, so no model is called and no money is spent.

selfhost/README.md:92Source: selfhost/README.md
selfhost/bootstrap.sh   # bring up, initialise, create env + keys + warehouse, bind the CLI
selfhost/demo.sh        # forkbill init + start experiment, forkbill demo, refresh, print results
selfhost/demo.sh all    # the same experiment in the four evaluation modes below

Toggle the live site from Flagsmith

Two flags drive what this site shows, with no deploy.

The site_notice flag holds the notice text at the top of the home page, and agent_routing tells the routing badge which policy is live. Turn the notice off or change its text in Flagsmith, and the change reaches open pages in about ten seconds: the Worker reads the flags with the client-side key, and Flagsmith's signed webhook tells it to read again at once.

# what the site reads (cached about 30 s, refreshed at once on Flagsmith's webhook)
curl -s https://forkbill.prashantthakur.dev/site/flags
curl -s https://forkbill.prashantthakur.dev/badge/routing.json

MCP: Flagsmith's own server and ours, side by side

Flagsmith's server reads and inspects; ours decides and waits for a person.

In example 11 one MCP client talks to two servers. Flagsmith's official MCP server reads the project, the agent_routing flag, its variants and the experiments, and after the rollout reads the experiment back as completed. Our forkbill-mcp registers the decision rule while the experiment is still created, evaluates it on Flagsmith's results, proposes the exact End Experiment request, refuses to apply it until a person approves at a terminal, then applies it. It was recorded read-only on this study's Flagsmith Cloud project, and the full flow runs on self-hosted Flagsmith on a clean GitHub runner whenever that example changes, and weekly.

# one plugin starts both MCP servers and adds the Flagsmith skill
/plugin marketplace add Prashant-thakur77/fork-in-the-bill
/plugin install flagsmith-experiments@fork-in-the-bill

Example 11 and its recorded runs · The approval, recorded with a person · The plugin