Skip to content

add explain api#1003

Open
sauraww wants to merge 1 commit into
mainfrom
visualize-api
Open

add explain api#1003
sauraww wants to merge 1 commit into
mainfrom
visualize-api

Conversation

@sauraww
Copy link
Copy Markdown
Collaborator

@sauraww sauraww commented May 13, 2026

Problem

We don't have a way to show cascading behavior of resolve api

Solution

Adding layers and per_key_history in resolve , if include_trace is true, you will get back the entire trace.

Copilot AI review requested due to automatic review settings May 13, 2026 19:25
@sauraww sauraww requested a review from a team as a code owner May 13, 2026 19:25
@semanticdiff-com
Copy link
Copy Markdown

semanticdiff-com Bot commented May 13, 2026

Review changes with  SemanticDiff

Changed Files
File Status
  crates/cac_client/src/eval.rs  17% smaller
  crates/frontend/src/pages/home.rs  0% smaller

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 13, 2026

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8dc43b0e-bbd2-4bdb-b465-9f5b49f36fd9

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Walkthrough

This PR extends CAC config evaluation to support detailed reasoning traces. A new eval_cac_with_explanation API computes and emits per-override and per-key value history alongside the existing metadata. The feature is integrated into the resolve endpoint via an explain query parameter, with schema updates across Smithy and types.

Changes

CAC Evaluation Explanation Trace Support

Layer / File(s) Summary
Type contracts and transition helpers
crates/cac_client/src/eval.rs
Introduces KeyTransitions and ReasoningHook type aliases, and implements merged_value computation and build_key_transitions helper to track previous/next values for each key.
Override hook infrastructure
crates/cac_client/src/eval.rs
Updates get_overrides to accept an optional reasoning hook and compute key transitions during override application; initializes the hook for reasoning-enabled evaluation paths.
Reasoning evaluation and trace construction
crates/cac_client/src/eval.rs
Implements eval_cac_with_reasoning_inner function that builds legacy metadata plus optional trace structures; defines the override-selection hook that records detailed layers and per-key history when trace is enabled.
Public API and validation tests
crates/cac_client/src/eval.rs
Finalizes trace emission by conditionally inserting metadata_trace, adds new eval_cac_with_explanation wrapper (trace enabled) alongside eval_cac_with_reasoning (trace disabled), and updates tests to verify both behaviors.
Public library re-export
crates/cac_client/src/lib.rs
Re-exports eval_cac_with_explanation from the eval module at the library level.
API request schema and types
smithy/models/config.smithy, crates/superposition_types/src/api/config.rs
Adds optional explain query parameter to ResolveConfigQuery type and to GetResolvedConfig operation in Smithy schema.
Endpoint integration and evaluation dispatch
crates/context_aware_config/src/api/config/helpers.rs
Imports eval_cac_with_explanation and integrates it into the resolve endpoint: when explain is enabled, dispatches to explanation evaluation; otherwise uses existing paths.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested reviewers

  • knutties
  • Datron
  • mahatoankitkumar

Poem

🐰 Traces bloom where overrides dance,
Each key records its value's prance,
From merge to replace, the logic flows,
Explanations rich where reasoning grows,
A rabbit's gift of clarity! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'add explain api' directly and clearly describes the main change—adding a new explain API for the configuration resolution endpoint. It is concise and specific enough for scanning history.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch visualize-api

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@sauraww sauraww changed the title explain api add explain api May 13, 2026
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
smithy/models/config.smithy (2)

206-208: ⚡ Quick win

Add documentation for the explain query parameter.

The new explain parameter lacks an @documentation annotation explaining its purpose and how it differs from show_reasoning. API consumers will benefit from clear guidance on when to use each option.

📝 Suggested documentation
+        `@documentation`("When true, includes detailed reasoning trace with merge strategy, per-layer override details, and per-key value history in the response. Provides more comprehensive debugging information than show_reasoning.")
         `@httpQuery`("explain")
         `@notProperty`
         explain: Boolean
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@smithy/models/config.smithy` around lines 206 - 208, Add an `@documentation`
annotation to the explain Boolean member to describe its purpose and how it
differs from show_reasoning; update the explain field (symbol: explain) with a
short docstring explaining that explain toggles inclusion of a machine-generated
explanation of results (e.g., why items matched) while show_reasoning controls
whether the model's internal chain-of-thought or stepwise reasoning is returned,
and include usage examples or expected output shape if possible to guide API
consumers.

202-208: ⚡ Quick win

Clarify the relationship between explain and show_reasoning.

Both explain and show_reasoning can be set simultaneously. Based on the implementation in helpers.rs (line 179), explain takes precedence. This behavior might be unexpected for API consumers.

Consider either:

  1. Documenting that explain supersedes show_reasoning when both are true, or
  2. Adding validation to make them mutually exclusive if that's the intended design.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@smithy/models/config.smithy` around lines 202 - 208, The model exposes two
query flags, explain and show_reasoning, but the runtime currently makes explain
take precedence; change this by adding server-side validation in the code path
that parses/validates the explain and show_reasoning query params so that if
both are true you return a 400 validation error (with a clear message that the
flags are mutually exclusive), and also update the smithy model comments for the
explain and show_reasoning fields to document that they are mutually exclusive
(or alternatively, if you prefer to keep current precedence, update the docs to
state that explain supersedes show_reasoning); reference the explain and
show_reasoning symbols when making these changes and update any tests exercising
this behavior.
crates/cac_client/src/eval.rs (1)

220-226: ⚡ Quick win

Silent failure on malformed transition could hide bugs.

The code silently skips transitions that lack a "key" field via continue. While defensive, this could mask data corruption or logic errors upstream in build_key_transitions.

Consider logging a warning when a transition is missing the "key" field to aid debugging.

📝 Suggested improvement
                    let Some(key) = transition
                        .get("key")
                        .and_then(Value::as_str)
                        .map(ToOwned::to_owned)
                    else {
+                       log::warn!("Skipping transition without 'key' field: {:?}", transition);
                        continue;
                    };
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/cac_client/src/eval.rs` around lines 220 - 226, The code currently
silently skips transitions missing a "key" in the block using
transition.get("key").and_then(Value::as_str)...else { continue; }, which can
hide upstream bugs; update this branch to emit a warning including the offending
transition (and any contextual identifiers) before continuing — e.g., replace
the else { continue; } with a log warning (using the project's logging/tracing
macro such as log::warn! or tracing::warn!) that includes the transition value
and mentions build_key_transitions/transition so the malformed data is visible
in logs for debugging.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@crates/cac_client/src/eval.rs`:
- Around line 220-226: The code currently silently skips transitions missing a
"key" in the block using transition.get("key").and_then(Value::as_str)...else {
continue; }, which can hide upstream bugs; update this branch to emit a warning
including the offending transition (and any contextual identifiers) before
continuing — e.g., replace the else { continue; } with a log warning (using the
project's logging/tracing macro such as log::warn! or tracing::warn!) that
includes the transition value and mentions build_key_transitions/transition so
the malformed data is visible in logs for debugging.

In `@smithy/models/config.smithy`:
- Around line 206-208: Add an `@documentation` annotation to the explain Boolean
member to describe its purpose and how it differs from show_reasoning; update
the explain field (symbol: explain) with a short docstring explaining that
explain toggles inclusion of a machine-generated explanation of results (e.g.,
why items matched) while show_reasoning controls whether the model's internal
chain-of-thought or stepwise reasoning is returned, and include usage examples
or expected output shape if possible to guide API consumers.
- Around line 202-208: The model exposes two query flags, explain and
show_reasoning, but the runtime currently makes explain take precedence; change
this by adding server-side validation in the code path that parses/validates the
explain and show_reasoning query params so that if both are true you return a
400 validation error (with a clear message that the flags are mutually
exclusive), and also update the smithy model comments for the explain and
show_reasoning fields to document that they are mutually exclusive (or
alternatively, if you prefer to keep current precedence, update the docs to
state that explain supersedes show_reasoning); reference the explain and
show_reasoning symbols when making these changes and update any tests exercising
this behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0ec097c6-d129-42a1-9d5d-bf528b320ead

📥 Commits

Reviewing files that changed from the base of the PR and between f5121d8 and 51396d1.

📒 Files selected for processing (5)
  • crates/cac_client/src/eval.rs
  • crates/cac_client/src/lib.rs
  • crates/context_aware_config/src/api/config/helpers.rs
  • crates/superposition_types/src/api/config.rs
  • smithy/models/config.smithy

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds an explain option to the resolved-config API to return a richer “explanation/trace” of how overrides were applied (in addition to the existing legacy show_reasoning metadata).

Changes:

  • Extend Smithy model + Rust query types to accept explain as a query parameter.
  • Route explain=true requests to a new CAC client evaluation path that includes metadata_trace in the resolved config.
  • Add CAC client internals for collecting per-layer and per-key transition history, plus unit tests.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
smithy/models/config.smithy Adds explain query parameter to GetResolvedConfig input model.
crates/superposition_types/src/api/config.rs Adds explain: Option<bool> to ResolveConfigQuery.
crates/context_aware_config/src/api/config/helpers.rs Uses explain to select eval_cac_with_explanation vs legacy reasoning vs normal evaluation.
crates/cac_client/src/lib.rs Re-exports eval_cac_with_explanation.
crates/cac_client/src/eval.rs Implements trace/explanation capture (metadata_trace) and adds unit tests.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread smithy/models/config.smithy Outdated
show_reasoning: Boolean

@httpQuery("explain")
@notProperty
Comment on lines +105 to +109
let key_transitions = build_key_transitions(
&required_overrides,
overriden_value,
merge_strategy,
);
Comment on lines +343 to +353
#[test]
fn eval_cac_with_reasoning_adds_trace_without_breaking_metadata() {
let config = base_config();
let query = Map::from_iter([
("clientId".to_string(), json!("android")),
("country".to_string(), json!("IN")),
]);

let resolved = eval_cac_with_explanation(&config, &query, MergeStrategy::MERGE)
.expect("reasoning config should resolve");

Comment thread smithy/models/config.smithy Outdated
Comment on lines +206 to +209
@httpQuery("explain")
@notProperty
explain: Boolean

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.

2 participants