Repository navigation
Redact reports, checkpoints, results and saved programs before converting them - #240
Merged
Merged
Conversation
…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.
…vert # Conflicts: # .dialyzer_ignore.exs
…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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 asredact/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 fromredact/2in two ways:datais redacted, as the old convert-then-redact pass did.:"[REDACTED]". The old pass redacted the atom's encoded text.These apply in both modes, and to
drop_credentials/1and Saving'sredact_dump: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 madeImp.Optimizer.Parameterrefuse input keys["api_key", "question"].["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 besidelist_pair?/1, in the CHANGELOG, and asserted byredaction_differential_test.exs.redact_term_except/2keeps map entries under named keys as they are. The ACP session store uses it for the provider's reasoning continuation.drop_credentials/1runsredact_termfirst 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/1is 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_termbeforedump_toolsencodes them. Before, they were redacted after encoding, when a retriever in a schema was already a plain map.Loading in a fresh VM
"[REDACTED]"atom marker through its table of portable atoms, soReport.load!/1andGRPO.Checkpoint.load!/1read it withoutImp.Redactionloaded. The reviewer suggestedCode.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.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
Report.dump/1,json_safe/1,json_projection/1redact_term, then convertExperiment.Result.to_map/2,write!/3Evaluate.Result.redacted_output_rows/1; errors throughjson_safeEvaluate.Result.save_as_json/2,save_as_csv/2redacted_output_rows/1(redact_term, thenoutput_rows)Experimentoptions,Experiment.Bootstrap, BetterTogether job summary,GRPO.Callback, Optimize AnythingBestOutputWriterjson_safe/json_projectionbootstrap_diagnosticsReport.dump+json_safe; the second pass over converted output is removedGRPO.Checkpoint.save!/3,checkpoint_safe_batchesredact_term, then encodeOptimizer.Artifactmap report / metadatajson_safe/drop_credentials, then sanitizeSaving: Predict demos and metadata, KNN trainset,Retrieve.Memorydocs, Avatardump_portable_value!redact_term, then encode, thenredact_dumperrors,proposal_errors, a row'serror/errors)Optimize.Anything.Result.to_map/1candidatesandcheckpointSessionStore.persist/5redact_term_except(reasoning_content,reasoning_detailskept); transcript throughredact_termResume 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:
InferRules candidates are compared without their
errors, which carry the redacted failure reasons.These are left unredacted:
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.StructuredCandidate. Not a writer.encode_component!is the engine's in-memory representation of the candidate it evaluates, andto_map/1of the codec holds a type schema, not values.run_dir, ComBeeload_reportand 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.Imp.Optimizer.GEPA.Failureredacts 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._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.SessionStoreand the:session_storeoption doc now say that anything a host puts in_metais persisted. (SessionStoreis@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.exbuilds the probe:Retrievers.HTTPwith anX-Subscription-Tokenheader, a custom header and a?key=URL;Retrievers.HTTPwith a?token=URL;Imp.MCP.OAuth.store;{:api_key, v},{:note, sk},[sk]and a retriever.test/redaction_writers_test.exs(24 tests) writes it through every writer above, and checks:with_inputs([:api_key, :question])and metadata lists[:api_key, :question]/["token", "question"]survivessave!/read!, an artifact candidate and a KNN save;"examples" => [["api_key", v]]is saved as["api_key","[REDACTED]"]. Saving's finalredact_dumppass is the only redaction a ReAct tool schema gets, so its list-pair branch is reachable and stays;headers:are not saved.drop_headers' list clause is reachable through Saving's[name, value]config and stays;Imp.Examples. Plainredactindump_portable_value!turns them into tagged maps;redact/1,redact_term,drop_credentials,json_safe,json_projection,Report.dumpandSaving.dump:[["api_key", v]],headers: [["X-Api-Key", v]],[["password", v], ["model", "gpt"]](model kept), and Jason-decodedreq_http_options→headers→[["authorization", v]];redact/1,redact_termanddrop_credentials, and thatParameter.validate_value!accepts input keys["api_key", "question"];"required" => ["api_key", "query"]survives save and load;elixirVM.test/redaction_differential_test.exsadds every case from the review'srev240_pairs.exs, compared against the frozen 0.5.0 rules (MainRedaction):redact,redact_termanddrop_credentials;[["token","the"],["session","keynote"]]) is redacted after save and load, the same as main.test/mipro_v2_resume_test.exsadds a fresh-VM resume: the checkpoint is written in the test VM and resumed in a separateelixirprocess 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:
requiredtest, api_key testwalkignoring list pairsdrop_credentialsignoring list pairs"[REDACTED]")redact_dump's list-pair branchdrop_headers' list-pair clauseredactdump_portable_value!back to plainredact"[REDACTED]"portable atomnot an already existing atom)demo_set_index)The checkpoint resume tests fail on
origin/main's checkpoint code withJason.EncodeErroron the raw OAuth store key.Checkpoint.dumpitself crashes the run.On the first commit, resetting
lib/toorigin/mainfailed 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/mainand on this branch. Before the merge oforigin/main(ff778c2), every digest was byte-identical:examples/deployment/*.json, in-memory programs and reports, artifact candidates, a GRPO checkpoint and an experiment result.OA Result.to_map;After merging
origin/main(now 6e8dfbf) and the pair rule, all 40 digests are identical except the experiment result. Its only differences are"clean": falseagainsttruein the artifact's git provenance, and the checksums over it. That happens because the comparison checks out main'slib/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.Trajectoryrefused a non-atom, non-string map key with a message that printed the key, secret included. It now names the key by type throughImp.FieldMap.describe/1("a tuple of 2 elements"). The trajectory writer test refuses%{{:api_key, secret} => 1}and asserts the message holds no secret; revertingtrajectory.exfails it.Gates
mix format --check-formatted: cleanmix compile --warnings-as-errors --force: cleanmix dialyzeron the merged tree:Total errors: 143, Skipped: 143, Unnecessary Skips: 0, passed. Pins:report.ex779,playbook.ex1020,better_together.ex1288/1291/1303; main'sengine.expin (3020) still matches.redaction_differential_test.exs,documentation_contract_test.exs,public_api_manifest_test.exsanddoctest_test.exs:59 doctests, 6 properties, 746 tests, 0 failures (1 excluded)59 doctests, 9 properties, 3578 tests, 15 failures, 13 skipped (147 excluded). 14 are the known environment failures. The 15th isCampaignBudgetTest"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.