Skip to content

Redact reports, checkpoints, results and saved programs before converting them - #240

Merged
deepfates merged 8 commits into
mainfrom
claude/051-redact-convert
Sep 28, 2026
Merged

deepfates merged 8 commits into
mainfrom
claude/051-redact-convert

Conversation

@deepfates

@deepfates deepfates commented Sep 28, 2026 •

Copy link
Copy Markdown
Owner

Closes #235

Problem

Several writers turned structs into plain maps and redacted afterwards. Imp.Redaction's clauses for connection structs and MCP OAuth structs never saw the struct. Header values, URL query secrets and an OAuth store's derived key were written to reports, results, checkpoints, exports and saved programs.

Change

Redaction

Imp.Redaction.redact_term/2 (@doc false) redacts a term before a writer converts it. It walks the same clauses as redact/2, but keeps every struct's type. The converters still recognise examples, code, images, reports and URIs, so a value with nothing to hide converts exactly as it did before. It differs from redact/2 in two ways:

  • Image data. An image's data is redacted, as the old convert-then-redact pass did.
  • Atoms. An atom that spells a credential becomes :"[REDACTED]". The old pass redacted the atom's encoded text.

These apply in both modes, and to drop_credentials/1 and Saving's redact_dump:

  • Pairs (list_pair?/1). A two-element list with a string or atom first is a key-value pair when it is an element of a list, whatever its siblings are, as JSON writes config, headers, options and tool results: [["api_key", key], ["model", "gpt"]], [["api_key", key], "note"], a ragged [["x","y"], ["api_key", key], ["z"]]. A tuple with a name first is always a pair, and so is an entry or two-element tuple the codec tagged. A two-element list held directly as a field or map value is data: an example's input keys [:api_key, :question], a schema's "required" => ["api_key", "query"], labels ["token", "question"]. On main, any two-element list with a name first was a pair, which corrupted such lists in saved programs and made Imp.Optimizer.Parameter refuse input keys ["api_key", "question"].
    • Recorded divergence from 0.5.0: a flat ["api_key", key] held directly as a value, under a key that is not itself a credential name, is not redacted, since it has the shape of a list of two names. This is written beside list_pair?/1, in the CHANGELOG, and asserted by redaction_differential_test.exs.
  • String keys. A string map key shaped like a credential is replaced whole; its name is not treated as a secret.
  • Other keys. A map key that is not an atom or a string (a tuple, a list, a struct) is walked like a value. When two keys redact to the same term, one entry is kept; which value survives is arbitrary, and neither key's secret remains.
  • redact_term_except/2 keeps map entries under named keys as they are. The ACP session store uses it for the provider's reasoning continuation.

drop_credentials/1 runs redact_term first and then drops credential pairs under the same rule, so saved config, headers and options (JSON pair lists, nested ones included) still lose their credentials on dump and on load. drop_headers/1 is unchanged from main; it already reads a two-element list as a pair only as a list element.

Avatar tool schemas are redacted with redact_term before dump_tools encodes them. Before, they were redacted after encoding, when a retriever in a schema was already a plain map.

Loading in a fresh VM

  • The report codec decodes the "[REDACTED]" atom marker through its table of portable atoms, so Report.load!/1 and GRPO.Checkpoint.load!/1 read it without Imp.Redaction loaded. The reviewer suggested Code.ensure_loaded!(Imp.Redaction); the portable-atom table is the codec's existing mechanism for exactly this, and it covers every loader that decodes through the codec.
  • The MIPROv2 checkpoint loader loads the modules whose atoms it decodes (MIPROv2, its upstream bootstrap and proposer, InstructionProposer, DemoCandidates) before decoding. It failed on main with "not an already existing atom" (proposal_lm_error, demo_set_index, rounds) even with no probe present.

Writers

Writer Now
Report.dump/1, json_safe/1, json_projection/1 redact_term, then convert
Experiment.Result.to_map/2, write!/3 rows through Evaluate.Result.redacted_output_rows/1; errors through json_safe
Evaluate.Result.save_as_json/2, save_as_csv/2 redacted_output_rows/1 (redact_term, then output_rows)
Experiment options, Experiment.Bootstrap, BetterTogether job summary, GRPO.Callback, Optimize Anything BestOutputWriter fixed through json_safe / json_projection
BetterTogether bootstrap_diagnostics Report.dump + json_safe; the second pass over converted output is removed
GRPO.Checkpoint.save!/3, checkpoint_safe_batches redact_term, then encode
Optimizer.Artifact map report / metadata json_safe / drop_credentials, then sanitize
Saving: Predict demos and metadata, KNN trainset, Retrieve.Memory docs, Avatar dump_portable_value! redact_term, then encode, then redact_dump
SIMBA, MIPROv2, InferRules, random-search checkpoints failure reasons only (errors, proposal_errors, a row's error/errors)
Optimize.Anything.Result.to_map/1 everything except candidates and checkpoint
ACP SessionStore.persist/5 history through redact_term_except (reasoning_content, reasoning_details kept); transcript through redact_term

Resume checkpoints

A resumed run reads back its instructions, demos and scores, and the checkpoint's integrity hash covers them. Redacting them would change what the run evaluates. So the SIMBA, MIPROv2, InferRules and random-search checkpoints redact only failure reasons, which a resumed run only reports.

Each checkpoint has a test that:

  1. writes a checkpoint while the task fails with a reason holding the probe;
  2. checks that no secret is in the JSON;
  3. resumes, and gets the same candidates, best score and trial or evaluation records as an uninterrupted run.

InferRules candidates are compared without their errors, which carry the redacted failure reasons.

These are left unredacted:

  • Fast-Slow checkpoint. Its prompts, rollouts and digests are the resume state. Its state builder already refuses structs and credential-named keys, so no client, retriever or OAuth struct can reach it. Credential-shaped text in a prompt or rollout is written as it is. The moduledoc now says the file is sensitive.
  • Playbook checkpoint. Its trajectories are already redacted by Trajectory.dump/1, which also refuses unknown structs and non-atom, non-string keys. Its playbooks are the restore state and are covered by the checkpoint hash. write_checkpoint!/2's doc now says the file is sensitive.
  • Optimize Anything StructuredCandidate. Not a writer. encode_component! is the engine's in-memory representation of the candidate it evaluates, and to_map/1 of the codec holds a type schema, not values.
  • Not verified in a fresh VM: the GEPA run_dir, ComBee load_report and Playbook checkpoint loaders. GEPA resume in a fresh VM is Resuming a parallel GEPA run from a pending batch fails on a trace in prediction metadata #241.
  • GEPA engine state, ComBee and the GEPA evaluation disk cache. Not changed by this PR. GEPA reports proposals that failed when raise_on_exception is false #238's Imp.Optimizer.GEPA.Failure redacts GEPA and ComBee failure reasons when they are recorded and documents GEPA checkpoints as sensitive resume state; candidates and the cache are kept as they are.
  • The ACP session record's _meta. Stored as the client sent it, in the session's 0600 file. Imp puts nothing there and never reads it; only the host's program factory does. SessionStore and the :session_store option doc now say that anything a host puts in _meta is persisted. (SessionStore is @moduledoc false, so the host-facing statement is in the option doc, and a comment sits in the module.)

A resumed ACP session replays a user message or tool result that held a credential as "[REDACTED]", to the client and in the model's history. That follows the whole-string rule; the CHANGELOG says so.

Tests

test/support/redaction_probe.ex builds the probe:

  • a Retrievers.HTTP with an X-Subscription-Token header, a custom header and a ?key= URL;
  • a Retrievers.HTTP with a ?token= URL;
  • a ReqLLM client with a custom header;
  • an Imp.MCP.OAuth.store;
  • a map keyed by {:api_key, v}, {:note, sk}, [sk] and a retriever.

test/redaction_writers_test.exs (24 tests) writes it through every writer above, and checks:

  • that no secret is written and the non-secret fields remain;
  • that colliding redacted keys keep one entry;
  • that image data is redacted;
  • that a program with demos with_inputs([:api_key, :question]) and metadata lists [:api_key, :question] / ["token", "question"] survives save! / read!, an artifact candidate and a KNN save;
  • that an ACP session keeps its reasoning continuation byte for byte while the rest of the record is redacted;
  • that a ReAct tool schema holding "examples" => [["api_key", v]] is saved as ["api_key","[REDACTED]"]. Saving's final redact_dump pass is the only redaction a ReAct tool schema gets, so its list-pair branch is reachable and stays;
  • that a Predict's config headers: are not saved. drop_headers' list clause is reachable through Saving's [name, value] config and stays;
  • that an Avatar tool schema holding the probe retriever is saved without its header value or URL key, and that the Avatar actor's demos load back as the same Imp.Examples. Plain redact in dump_portable_value! turns them into tagged maps;
  • that four JSON-style pairs are redacted by redact/1, redact_term, drop_credentials, json_safe, json_projection, Report.dump and Saving.dump: [["api_key", v]], headers: [["X-Api-Key", v]], [["password", v], ["model", "gpt"]] (model kept), and Jason-decoded req_http_options → headers → [["authorization", v]];
  • that flat name lists are unchanged by redact/1, redact_term and drop_credentials, and that Parameter.validate_value! accepts input keys ["api_key", "question"];
  • that an Avatar tool schema's "required" => ["api_key", "query"] survives save and load;
  • that a credential-shaped string key is redacted;
  • that a report and a GRPO checkpoint holding the redacted atom load in a fresh elixir VM.

test/redaction_differential_test.exs adds every case from the review's rev240_pairs.exs, compared against the frozen 0.5.0 rules (MainRedaction):

  • every input 0.5.0 redacts is still redacted by redact, redact_term and drop_credentials;
  • the flat-list case is asserted as the one divergence;
  • a demo answer that is a table of rows ([["token","the"],["session","keynote"]]) is redacted after save and load, the same as main.

test/mipro_v2_resume_test.exs adds a fresh-VM resume: the checkpoint is written in the test VM and resumed in a separate elixir process that loads no Imp module ahead of time. It matches the uninterrupted run's status, best score and candidate count.

Falsification

For each change, I reverted that change alone and ran the tests:

Reverted Failing tests
key walking 11 of the (then 16) writer tests
Evaluate redaction exports test, experiment test
image data image test
Optimize Anything, session history, session transcript, session reasoning preservation the matching test each
a flat two-element list read as a pair again (walk) divergence test, flat-name-list test, Avatar required test, api_key test
walk ignoring list pairs differential list-pair test, JSON-style pairs test
drop_credentials ignoring list pairs JSON-style pairs test (the pair must be dropped, not kept as "[REDACTED]")
redact_dump's list-pair branch ReAct tool schema test
drop_headers' list-pair clause config headers test
Avatar schema back to main's post-encoding plain redact Avatar schema test (header value written)
Avatar dump_portable_value! back to plain redact Avatar test (demos no longer load as examples)
string keys not checked string key test
the "[REDACTED]" portable atom fresh-VM report/GRPO test (not an already existing atom)
the MIPROv2 loader's module loading fresh-VM MIPROv2 test (demo_set_index)
each of the four checkpoint files its resume test

The checkpoint resume tests fail on origin/main's checkpoint code with Jason.EncodeError on the raw OAuth store key. Checkpoint.dump itself crashes the run.

On the first commit, resetting lib/ to origin/main failed every writer test that existed then, and reverting each file failed its test.

Output with no secrets is unchanged

I compared warm runs on origin/main and on this branch. Before the merge of origin/main (ff778c2), every digest was byte-identical:

  • 32 digests, as before: the react_v2 0.5.0 saved-program fixture, every program and report in examples/deployment/*.json, in-memory programs and reports, artifact candidates, a GRPO checkpoint and an experiment result.
  • 8 more for the newly redacted writers:
    • Evaluate JSON and CSV exports;
    • OA Result.to_map;
    • random-search and InferRules checkpoints written with task failures;
    • an ACP session's history and transcript.

After merging origin/main (now 6e8dfbf) and the pair rule, all 40 digests are identical except the experiment result. Its only differences are "clean": false against true in the artifact's git provenance, and the checksums over it. That happens because the comparison checks out main's lib/ into this worktree, which leaves the tree dirty.

The #226 save round trip (redaction_differential_test.exs) passes. The existing resume tests for all four optimizers, Fast-Slow, playbooks, GRPO, saving_*, ACP and history pass.

Trajectory refusal message

Imp.Optimizer.Trajectory refused a non-atom, non-string map key with a message that printed the key, secret included. It now names the key by type through Imp.FieldMap.describe/1 ("a tuple of 2 elements"). The trajectory writer test refuses %{{:api_key, secret} => 1} and asserts the message holds no secret; reverting trajectory.ex fails it.

Gates

  • mix format --check-formatted: clean
  • mix compile --warnings-as-errors --force: clean
  • mix dialyzer on the merged tree: Total errors: 143, Skipped: 143, Unnecessary Skips: 0, passed. Pins: report.ex 779, playbook.ex 1020, better_together.ex 1288/1291/1303; main's engine.ex pin (3020) still matches.
  • Touched tests plus redaction_differential_test.exs, documentation_contract_test.exs, public_api_manifest_test.exs and doctest_test.exs: 59 doctests, 6 properties, 746 tests, 0 failures (1 excluded)
  • Full suite, with no other test VM running: 59 doctests, 9 properties, 3578 tests, 15 failures, 13 skipped (147 excluded). 14 are the known environment failures. The 15th is CampaignBudgetTest "concurrent public wrappers record only their own provider telemetry", which got {:campaign_budget_exhausted, :output_tokens} for its second call. It touches no changed code, and passed 13 of 13 runs alone (5 of the whole file, 8 of the single test with random seeds). I read it as a concurrency flake in the full run. All 14 are the expected environment failures: missing pinned DSPy/GEPA sources and Python venv, and the deployment examples run without deps. None is in a touched area.

…ting them

Writers converted structs to plain maps before redacting, so the struct-aware
clauses in Imp.Redaction never saw a client, retriever or MCP OAuth store, and
header values, URL query secrets and the store key were written out.
Imp.Redaction.redact_term/2 redacts the original term and keeps struct types;
Report.dump/json_safe/json_projection, the experiment result rows, the GRPO
checkpoint, the optimizer artifact's map report and Saving's Predict demos and
metadata, KNN examples and memory documents call it before encoding.
drop_credentials/1 redacts the term before removing entries.

Closes #235
…ore converting

Map keys that are not atoms or strings are walked like values. Evaluate's JSON
and CSV exports redact their rows, and an image's data is redacted when it is
written. A two-element list is a pair only as a tuple or a codec-tagged entry,
so an input named api_key survives saving. The SIMBA, MIPROv2, InferRules and
random-search checkpoints and ComBee reports redact failure reasons and keep
the state a resumed run continues from; Optimize Anything results redact all
but their candidates and checkpoint; ACP session history is redacted except
the provider's reasoning continuation. Fast-Slow and playbook checkpoints are
documented as sensitive.
…point atoms in a fresh VM

A pair written as a list, as JSON writes config and headers, is redacted again
by redact_term, redact/1, drop_credentials and Saving, while a flat list of
names such as [:api_key, :question] or a schema's required list is data. A
string map key shaped like a credential is redacted. The report codec decodes
the redaction marker atom without Imp.Redaction loaded, and the MIPROv2
checkpoint loader loads the modules whose atoms it decodes. The ACP session
store documents what it redacts and that _meta is stored as sent.
…element

A credential pair written as a list is redacted whatever its siblings are, as
0.5.0 did; a two-element list held directly as a value stays data, the one
recorded divergence. The differential test covers list-written pairs. Avatar
tool schemas are redacted before they are encoded, and tests show the paths
Saving's pair branch and drop_headers' list clause cover.
@deepfates
deepfates merged commit cf1ce2f into main Sep 28, 2026
10 checks passed
@deepfates
deepfates deleted the claude/051-redact-convert branch September 28, 2026 10:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Reports, checkpoints and saving convert structs before redacting them

1 participant