Skip to content
Merged
10 changes: 5 additions & 5 deletions .dialyzer_ignore.exs
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,11 @@
# defensive fallback paired with the 904 clause
{"lib/imp/clients/training.ex", :pattern_match_cov, {1537, 8}},
# defensive error clause on an always-ok internal call
{"lib/imp/optimizer/better_together.ex", :pattern_match, {1287, 8}},
{"lib/imp/optimizer/better_together.ex", :pattern_match, {1288, 8}},
# defensive error clause on an always-ok internal call
{"lib/imp/optimizer/better_together.ex", :pattern_match, {1290, 8}},
{"lib/imp/optimizer/better_together.ex", :pattern_match, {1291, 8}},
# defensive fallback paired with the clauses above
{"lib/imp/optimizer/better_together.ex", :pattern_match_cov, {1302, 8}},
{"lib/imp/optimizer/better_together.ex", :pattern_match_cov, {1303, 8}},
# defensive clause for already-handled pending-validation states
{"lib/imp/optimizer/gepa/engine.ex", :pattern_match_cov, {3020, 7}},
# defensive clause dialyzer pins to the module head (line 1)
Expand Down Expand Up @@ -212,8 +212,8 @@
{"lib/imp/adapter/xml.ex", :pattern_match_cov, {654, 8}},
{"lib/imp/optimizer/artifact.ex", :call_without_opaque, {745, 52}},
{"lib/imp/optimizer/artifact.ex", :call_without_opaque, {909, 53}},
{"lib/imp/optimizer/playbook.ex", :pattern_match_cov, {1014, 8}},
{"lib/imp/optimizer/report.ex", :call_without_opaque, {769, 55}},
{"lib/imp/optimizer/playbook.ex", :pattern_match_cov, {1020, 8}},
{"lib/imp/optimizer/report.ex", :call_without_opaque, {779, 55}},
{"lib/imp/schema.ex", :pattern_match_cov, {440, 8}},
{"bench/imp/benchmark_truth/failure_campaign.ex", :pattern_match_cov, {168, 13}}
]
40 changes: 40 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,46 @@ User-visible changes to Imp are recorded here.

### Fixed

- Optimizer reports (`Imp.Optimizer.Report.dump/1`, `json_safe/1`,
`json_projection/1`), experiment results, `Imp.Evaluate.Result.save_as_json/2`
and `save_as_csv/2`, BetterTogether's bootstrap diagnostics, optimizer
artifact candidates, GRPO session checkpoints, Optimize Anything results,
ACP session records and saved programs (a Predict's demos and metadata, KNN
examples, memory retriever documents) redact a term before converting it.
They converted first, so a client, retriever or MCP OAuth store in them was
written with its header values, URL query secrets or store key, and a
secret in a map key that is a tuple, a list or a struct was written as it
was. The SIMBA, MIPROv2, InferRules and random-search checkpoints redact
their failure reasons the same way; the instructions, demos and scores a
resumed run continues from are kept. `Imp.Redaction.drop_credentials/1`
redacts such structs too. Output that holds no secret is unchanged.
- An ACP session store redacts the history and transcript it writes, except
the provider's `reasoning_content` and `reasoning_details`. A resumed session
therefore replays a user message or tool result that held a credential as
`"[REDACTED]"`, both to the client and in the model's history. The session's
`_meta` is stored as sent; Imp never reads it.
- A saved program whose example has an input named like a credential
(`with_inputs([:api_key, :question])`), or whose metadata holds such a list,
loads back as it was. Saving and `Imp.Redaction.drop_credentials/1` read
every two-element list whose first item was a name as a key and its value,
and replaced or dropped the second item. A two-element list with a name
first is now a pair when it is an element of a list, as JSON writes config,
headers and tool results (`[["api_key", key], ["model", "gpt"]]`); held
directly as a field or map value, it is data. This also stops
`Imp.Redaction.redact/1` from rewriting an Avatar tool schema's
`"required" => ["api_key", "query"]` and `Imp.Optimizer.Parameter` from
refusing input keys `["api_key", "question"]`. One divergence from 0.5.0
follows: 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.
- A map key that is a string shaped like a credential is redacted.
`Imp.Optimizer.Trajectory` names a key it refuses (one that is not an atom
or a string) by its type; it printed the key, credential included.
- `Imp.Optimizer.Report.load!/1` and `Imp.Optimizer.GRPO.Checkpoint.load!/1`
read the `"[REDACTED]"` atom marker in a VM that has not loaded
`Imp.Redaction`, and a MIPROv2 checkpoint resumes in a fresh VM: its loader
loads the modules whose atoms it decodes. It failed with "not an already
existing atom".
- A reply that answers none of the requested outputs is a parse error in
`Imp.Adapter.Chat`, `Imp.Adapter.JSON` and `Imp.Adapter.XML`: an
`Imp.AdapterParseError` of kind `:missing_fields` naming every output, so
Expand Down
6 changes: 5 additions & 1 deletion lib/imp/acp/options.ex
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,11 @@ defmodule Imp.ACP.Options do
type: {:custom, __MODULE__, :validate_session_store, []},
doc:
"A directory that keeps each session's history and transcript, which " <>
"enables `session/load`, `list`, `resume` and `delete`."
"enables `session/load`, `list`, `resume` and `delete`. Each session is " <>
"one owner-readable JSON file. History and transcript are redacted with " <>
"`Imp.Redaction`, except the provider's reasoning continuation; the " <>
"session's `_meta` is stored as sent, so anything the host puts there " <>
"is persisted."
],
permission_policy: [
type: {:or, [{:in, [:client, :unrestricted]}, {:fun, 1}, {:fun, 2}]},
Expand Down
26 changes: 24 additions & 2 deletions lib/imp/acp/session_store.ex
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
defmodule Imp.ACP.SessionStore do
@moduledoc false

# One JSON file per session, mode 0600 in a 0700 directory. The history and
# transcript are redacted when written, except the provider's reasoning
# continuation, so a resumed session replays a message or tool result that
# held a credential as "[REDACTED]". The session's `_meta` is stored as the
# client sent it: Imp puts nothing there and never reads it, only the host's
# program factory does, so anything a host puts in `_meta` is persisted.

@version 1
@session_id ~r/\Aimp_[A-Za-z0-9_-]{24}\z/

Expand Down Expand Up @@ -32,8 +39,8 @@ defmodule Imp.ACP.SessionStore do

def persist(root, session_id, metadata, history, transcript) do
with {:ok, existing} <- read(root, session_id),
{:ok, dumped_history} <- dump_history(history),
{:ok, transcript} <- transcript(transcript) do
{:ok, dumped_history} <- history |> redact_history() |> dump_history(),
{:ok, transcript} <- transcript |> Imp.Redaction.redact_term() |> transcript() do
record =
existing
|> Map.put("cwd", metadata.cwd)
Expand Down Expand Up @@ -202,6 +209,21 @@ defmodule Imp.ACP.SessionStore do
defp stored_meta(%{"meta" => meta}) when is_map(meta), do: meta
defp stored_meta(_record), do: %{}

# History is redacted as it is, before it is dumped, except the provider's
# reasoning continuation: a resumed session sends `reasoning_content` and
# `reasoning_details` back to the provider, which needs them unmodified.
@reasoning_continuation [
:reasoning_content,
"reasoning_content",
:reasoning_details,
"reasoning_details"
]

defp redact_history(%Imp.History{} = history),
do: Imp.Redaction.redact_term_except(history, @reasoning_continuation)

defp redact_history(history), do: history

defp dump_history(%Imp.History{} = history), do: {:ok, Imp.History.dump(history)}
defp dump_history(nil), do: {:ok, nil}
defp dump_history(_history), do: {:error, :unsupported_session_history}
Expand Down
17 changes: 13 additions & 4 deletions lib/imp/evaluate.ex
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,11 @@ defmodule Imp.Evaluate.Result do
Writes the per-example rows to `path` as a JSON array of flat objects.

Mirrors DSPy `Evaluate(save_as_json=...)`: one object per devset row with
the example fields, the prediction fields, and the score.
the example fields, the prediction fields, and the score. Credentials in the
rows are redacted with `Imp.Redaction`.
"""
def save_as_json(%__MODULE__{} = result, path) when is_binary(path) do
rows = output_rows(result)
rows = redacted_output_rows(result)
File.write!(path, Jason.encode!(rows))
:ok
end
Expand All @@ -44,7 +45,7 @@ defmodule Imp.Evaluate.Result do
The file is RFC 4180 CSV with CRLF line endings, and every field holding a
comma, a quote or a line break is quoted, so `Imp.Datasets.csv/3` reads it
back unchanged. Saving an empty result raises: an empty file with no header would be a
silent failure.
silent failure. Credentials in the rows are redacted with `Imp.Redaction`.
"""
def save_as_csv(%__MODULE__{rows: []}, _path) do
raise ArgumentError,
Expand All @@ -53,7 +54,7 @@ defmodule Imp.Evaluate.Result do
end

def save_as_csv(%__MODULE__{} = result, path) when is_binary(path) do
rows = output_rows(result)
rows = redacted_output_rows(result)

header =
rows
Expand All @@ -70,6 +71,14 @@ defmodule Imp.Evaluate.Result do
:ok
end

@doc false
# The rows as a writer exports them. They are redacted as they are, before
# `output_rows/1` turns examples, predictions and other structs into plain
# maps, so a client, retriever or OAuth struct in them is still a struct when
# redacted.
def redacted_output_rows(%__MODULE__{rows: rows} = result),
do: output_rows(%{result | rows: Imp.Redaction.redact_term(rows)})

@doc false
# One flat map per row, upstream `_prepare_results_output` semantics.
def output_rows(%__MODULE__{rows: rows}) do
Expand Down
29 changes: 14 additions & 15 deletions lib/imp/experiment/result.ex
Original file line number Diff line number Diff line change
Expand Up @@ -324,20 +324,26 @@ defmodule Imp.Experiment.Result do
}

if include_rows? do
Map.merge(summary, %{
"rows" => result |> EvaluationResult.output_rows() |> Imp.Optimizer.Report.json_safe(),
"errors" =>
result.errors
|> Imp.Redaction.redact()
|> Imp.Optimizer.Report.json_safe()
})
Map.merge(summary, row_detail(result))
else
summary
end
end

defp evaluation_map(nil, _include_rows?), do: nil

# Rows and errors are redacted as they are, before they are turned into
# plain maps and encoded.
defp row_detail(%EvaluationResult{} = evaluation) do
%{
"rows" =>
evaluation
|> EvaluationResult.redacted_output_rows()
|> Imp.Optimizer.Report.encode_term(),
"errors" => Imp.Optimizer.Report.json_safe(evaluation.errors)
}
end

defp repetition_map(%{count: _count} = summary, include_rows?) do
%{
"count" => summary.count,
Expand Down Expand Up @@ -405,14 +411,7 @@ defmodule Imp.Experiment.Result do
}

if include_rows? do
Map.merge(summary, %{
"rows" =>
evaluation |> EvaluationResult.output_rows() |> Imp.Optimizer.Report.json_safe(),
"errors" =>
evaluation.errors
|> Imp.Redaction.redact()
|> Imp.Optimizer.Report.json_safe()
})
Map.merge(summary, row_detail(evaluation))
else
summary
end
Expand Down
12 changes: 11 additions & 1 deletion lib/imp/optimize/anything/result.ex
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,20 @@ defmodule Imp.Optimize.Anything.Result do
Map.get(candidate, :refiner_prompt, Map.get(candidate, "refiner_prompt"))
end

@doc "Converts the result to a JSON-safe schema-versioned map."
# The result is redacted before it is encoded, except the candidates and the
# engine checkpoint: they are the optimized artifacts and the state a run
# resumes from, and are kept as they are.
@doc """
Converts the result to a JSON-safe schema-versioned map.

Credentials outside the candidates and the checkpoint are redacted with
`Imp.Redaction`.
"""
@spec to_map(t()) :: map()
def to_map(%__MODULE__{} = result) do
result
|> Imp.Redaction.redact_term()
|> Map.merge(Map.take(result, [:candidates, :checkpoint]))
|> Map.from_struct()
|> Map.update!(:instance_frontier, &dump_frontier/1)
|> Map.update!(:objective_frontier, &dump_frontier/1)
Expand Down
2 changes: 1 addition & 1 deletion lib/imp/optimizer/artifact.ex
Original file line number Diff line number Diff line change
Expand Up @@ -722,7 +722,7 @@ defmodule Imp.Optimizer.Artifact do
defp normalize_report(%Report{} = report), do: report |> Report.dump() |> sanitize()

defp normalize_report(report) when is_map(report),
do: report |> Report.encode_term() |> sanitize()
do: report |> Report.json_safe() |> sanitize()

defp normalize_report(report) do
raise ArgumentError,
Expand Down
3 changes: 2 additions & 1 deletion lib/imp/optimizer/better_together.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1266,6 +1266,8 @@ defmodule Imp.Optimizer.BetterTogether do
{:error, failure.reason, diagnostics}
end

# `Report.dump/1` and `Report.json_safe/1` each redact their term before
# converting it, so the diagnostics are not redacted again.
defp bootstrap_diagnostics(program, failure) do
report =
case Report.fetch(program) do
Expand All @@ -1278,7 +1280,6 @@ defmodule Imp.Optimizer.BetterTogether do
"failure" => Report.json_safe(failure),
"report" => report
}
|> Imp.Redaction.redact()
end

defp cancellation_deadline(request),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ defmodule Imp.Optimizer.BootstrapFewShotWithRandomSearch.Checkpoint do

@spec dump(map(), map()) :: map()
def dump(compatibility, state) when is_map(compatibility) and is_map(state) do
# Failure reasons are redacted before they are encoded: a resumed run only
# reports them, and a client, retriever or OAuth struct in one is still a
# struct here. The instructions, demos, scores and hashes the run continues
# from are kept as they are.
state = Map.update!(state, :errors, &Imp.Redaction.redact_term/1)

payload = %{
"compatibility" => compatibility,
"state" => state |> dump_state() |> Report.encode_term()
Expand Down
2 changes: 1 addition & 1 deletion lib/imp/optimizer/grpo.ex
Original file line number Diff line number Diff line change
Expand Up @@ -681,8 +681,8 @@ defmodule Imp.Optimizer.GRPO do

defp checkpoint_safe_batches(batches) do
batches
|> Imp.Redaction.redact_term()
|> Imp.Optimizer.Report.encode_term()
|> Imp.Redaction.redact()
|> Imp.Optimizer.Report.decode_term()
end

Expand Down
2 changes: 1 addition & 1 deletion lib/imp/optimizer/grpo/checkpoint.ex
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ defmodule Imp.Optimizer.GRPO.Checkpoint do
"type" => "imp_grpo_session_checkpoint",
"schema_version" => 1,
"phase" => Atom.to_string(phase),
"data" => data |> Imp.Optimizer.Report.encode_term() |> Imp.Redaction.redact()
"data" => data |> Imp.Redaction.redact_term() |> Imp.Optimizer.Report.encode_term()
}

artifact = %{
Expand Down
18 changes: 18 additions & 0 deletions lib/imp/optimizer/infer_rules/checkpoint.ex
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,16 @@ defmodule Imp.Optimizer.InferRules.Checkpoint do

@spec dump(map(), map()) :: map()
def dump(compatibility, state) when is_map(compatibility) and is_map(state) do
# Failure reasons are redacted before they are encoded: a resumed run only
# reports them, and a client, retriever or OAuth struct in one is still a
# struct here. The instructions, demos, scores and hashes the run continues
# from are kept as they are.
state =
state
|> Map.update!(:proposal_errors, &Imp.Redaction.redact_term/1)
|> Map.update!(:candidates, &Enum.map(&1, fn row -> redact_failure(row) end))
|> Map.update!(:evaluated, &Enum.map(&1, fn row -> redact_failure(row) end))

payload = %{
"compatibility" => compatibility,
"state" => state |> dump_state() |> Report.encode_term()
Expand Down Expand Up @@ -60,6 +70,14 @@ defmodule Imp.Optimizer.InferRules.Checkpoint do
raise ArgumentError, "invalid InferRules resume state: #{inspect(value)}"
end

defp redact_failure(row) do
Enum.reduce([:error, :errors], row, fn key, row ->
if Map.has_key?(row, key),
do: Map.update!(row, key, &Imp.Redaction.redact_term/1),
else: row
end)
end

defp dump_state(state) do
state
|> Map.update!(:baseline, &dump_optional_program/1)
Expand Down
19 changes: 18 additions & 1 deletion lib/imp/optimizer/mipro_v2/checkpoint.ex
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ defmodule Imp.Optimizer.MIPROv2.Checkpoint do
@spec dump(map(), map(), map()) :: map()
def dump(compatibility, artifacts, state)
when is_map(compatibility) and is_map(artifacts) and is_map(state) do
# Failure reasons are redacted before they are encoded: a resumed run only
# reports them, and a client, retriever or OAuth struct in one is still a
# struct here. The instructions, demos, scores and hashes the run continues
# from are kept as they are.
payload = %{
"compatibility" => compatibility,
"artifacts" => Report.encode_term(artifacts),
Expand All @@ -22,7 +26,7 @@ defmodule Imp.Optimizer.MIPROv2.Checkpoint do
"full_evaluations" => dump_records(state.full_evaluations),
"next_study_number" => state.next_study_number,
"evaluation_calls" => state.evaluation_calls,
"errors" => Report.encode_term(state.errors)
"errors" => state.errors |> Imp.Redaction.redact_term() |> Report.encode_term()
}
}

Expand All @@ -34,6 +38,17 @@ defmodule Imp.Optimizer.MIPROv2.Checkpoint do
}
end

# The modules that name the atoms a checkpoint's trial records, proposal
# artifacts and errors hold. A resumed run in a fresh VM skips the work that
# would load them, so the loader loads them before decoding.
@run_modules [
Imp.Optimizer.MIPROv2,
Imp.Optimizer.MIPROv2.UpstreamBootstrap,
Imp.Optimizer.MIPROv2.UpstreamProposer,
Imp.Optimizer.InstructionProposer,
Imp.Optimizer.DemoCandidates
]

@spec load!(map(), map()) :: %{artifacts: map(), state: map()}
def load!(checkpoint, expected_compatibility)

Expand All @@ -57,6 +72,8 @@ defmodule Imp.Optimizer.MIPROv2.Checkpoint do
raise ArgumentError, "MIPROv2 resume state checksum does not match its payload"
end

Enum.each(@run_modules, &Code.ensure_loaded!/1)

unless compatible?(schema_version, compatibility, expected_compatibility) do
raise ArgumentError,
"MIPROv2 resume state does not match the program runtime, datasets, or search configuration"
Expand Down
Loading
Loading