Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(autoresearch): type model_explanation so feature importances render (#112610)

posthog[bot]fc59f674d66a
diff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.py
index d6753da1db9b..c60670d1e548 100644
--- a/products/autoresearch/backend/facade/api.py
+++ b/products/autoresearch/backend/facade/api.py
@@ -49,6 +49,11 @@ from ..models import (
)
from ..query import measure_queries
from ..training import artifacts as artifact_store
+from ..training.explanation import (
+ MAX_TOP_FEATURES as _MAX_TOP_FEATURES,
+ FeatureDirection as _FeatureDirection,
+ normalize_model_explanation,
+)
from ..training.recipe_validation import RecipeValidationError, feature_sql_hints, validate_feature_sql, validate_recipe
from ..training.shadow_set import shadow_set_ids
from .contracts import (
@@ -174,7 +179,7 @@ def _model_to_contract(row: AutoresearchModel, *, in_shadow_set: bool) -> Model:
role=row.role,
recipe_hash=row.recipe_hash,
model_recipe=row.model_recipe or {},
- model_explanation=row.model_explanation or {},
+ model_explanation=normalize_model_explanation(row.model_explanation),
holdout_score=row.holdout_score,
realized_score=row.realized_score,
calibration_error=row.calibration_error,
@@ -1638,3 +1643,5 @@ SUGGESTION_STATUS_CHOICES = AutoresearchSuggestion.Status.choices
SUGGESTION_SOURCE_CHOICES = AutoresearchSuggestion.Source.choices
RUN_TYPE_CHOICES = AutoresearchRun.RunType.choices
RUN_STATUS_CHOICES = AutoresearchRun.Status.choices
+FEATURE_DIRECTION_CHOICES = _FeatureDirection.choices
+MAX_TOP_FEATURES = _MAX_TOP_FEATURES
diff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.py
index e8be41cc1ea3..a63b2f7555d0 100644
--- a/products/autoresearch/backend/presentation/views/serializers.py
+++ b/products/autoresearch/backend/presentation/views/serializers.py
@@ -47,6 +47,10 @@ AGENT_DESCRIPTION_MAX_LENGTH = 2000
OBJECT_JSON_MAX_BYTES = 64 * 1024
MODEL_SPEC_MAX_BYTES = 4 * 1024
OUTPUT_PERSON_PROPERTY_MAX_LENGTH = 255
+MAX_TOP_FEATURES = api.MAX_TOP_FEATURES
+FEATURE_DIRECTION_CHOICES = api.FEATURE_DIRECTION_CHOICES
+FEATURE_NAME_MAX_LENGTH = 200
+EXPLANATION_TEXT_MAX_LENGTH = 500
# The target event is interpolated into the sandboxed training agent's prompt brief, so reject
# characters that could break out of it (control chars incl. newlines, backticks, template braces)
@@ -347,18 +351,61 @@ class ModelRecipeField(serializers.JSONField):
pass
-@extend_schema_field(
- {
- "type": "object",
- "description": (
- "Global feature importance bundle: top features by gain, directionality "
- "(positive/negative impact on predicted probability), stability across runs, "
- "and leakage warning annotations."
- ),
- }
-)
-class ModelExplanationField(ObjectJSONField):
- pass
+class FeatureImportanceSerializer(serializers.Serializer):
+ name = serializers.CharField(
+ max_length=FEATURE_NAME_MAX_LENGTH,
+ help_text="Feature column name, as returned by the feature SQL.",
+ )
+ importance = serializers.FloatField(
+ min_value=0,
+ help_text="Non-negative importance, for example the mean holdout AUC drop when the feature is shuffled.",
+ )
+ direction = serializers.ChoiceField(
+ choices=FEATURE_DIRECTION_CHOICES,
+ help_text="'positive' if a higher value raises the predicted probability, 'negative' if it lowers it.",
+ )
+
+ def validate_importance(self, value: float) -> float:
+ if not math.isfinite(value):
+ raise serializers.ValidationError("Must be a finite number.")
+ return value
+
+
+class ModelExplanationField(serializers.Serializer):
+ """Global feature importances for the model card."""
+
+ top_features = serializers.ListField(
+ child=FeatureImportanceSerializer(),
+ max_length=MAX_TOP_FEATURES,
+ required=False,
+ default=list,
+ help_text=f"At most {MAX_TOP_FEATURES} features, strongest first.",
+ )
+ method = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ max_length=EXPLANATION_TEXT_MAX_LENGTH,
+ help_text="Short description of how the importances were computed, e.g. 'permutation importance on holdout'.",
+ )
+ note = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ max_length=EXPLANATION_TEXT_MAX_LENGTH,
+ help_text="Optional caveat shown under the chart.",
+ )
+
+ def to_internal_value(self, data: Any) -> Any:
+ # DRF drops unknown keys, so an older list key would otherwise store an empty explanation and return 200.
+ if isinstance(data, dict) and "top_features" not in data:
+ legacy_key = next((key for key in ("features", "feature_importances") if key in data), None)
+ if legacy_key is not None:
+ raise serializers.ValidationError(
+ {"top_features": [f"Send the features as 'top_features', not '{legacy_key}'."]}
+ )
+ return super().to_internal_value(data)
+
+ def validate_top_features(self, value: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ return sorted((dict(f) for f in value), key=lambda f: f["importance"], reverse=True)
@extend_schema_field(
diff --git a/products/autoresearch/backend/training/AGENTS.md b/products/autoresearch/backend/training/AGENTS.md
index 437a64f2ca63..f8bb92fb5f12 100644
--- a/products/autoresearch/backend/training/AGENTS.md
+++ b/products/autoresearch/backend/training/AGENTS.md
@@ -41,6 +41,9 @@ The other half is `../inference/`, which consumes what this package produces and
The rollback changes nothing when the candidate is no longer the champion. A scoring run that started with the candidate fails in `_require_still_champion()` before it emits.
A recipe-only champion is not checked.
A champion whose scheduled scoring runs failed with a repeatable `failure_kind` on the last two prediction dates, with no success after the first of them, is unscorable (`find_unscorable_champion()` in `../inference/failures.py`). Any candidate replaces it whatever the margin, with `promotion_reason` `replaced_unscorable` in the model metrics, and the fit and the scorability check still roll back a candidate that cannot score either. The brief tells the agent the failure kind and the onset date.
+- `explanation.py`
+ The `model_explanation` contract: `top_features` (at most `MAX_TOP_FEATURES`, each a `name`, a non-negative `importance` and a `direction` of `positive` or `negative`), plus an optional `method` and `note`. The `complete` serializer enforces it and sorts the features strongest first, and the brief states it.
+ Champions written before the contract stored other shapes (`features` or `feature_importances` lists, a `feature` key, `auc_drop_when_shuffled` or `gain` for the importance, prose directions such as `higher -> less likely`). The rows are not backfilled. `normalize_model_explanation()` maps them on read in the facade and drops entries it cannot read, so the API always returns the typed shape.
- `shadow_set.py`
`shadow_set(pipeline)` computes the models worth scoring side by side. Nothing stores the set.
It holds the champion, the previous champion (the newest archived bundle-backed row with `promoted_at` set), and up to `SHADOW_CHALLENGER_LIMIT` (3) fitted bundle-backed challengers. No two members share a `recipe_hash`.
diff --git a/products/autoresearch/backend/training/explanation.py b/products/autoresearch/backend/training/explanation.py
new file mode 100644
index 000000000000..878e0a321edc
--- /dev/null
+++ b/products/autoresearch/backend/training/explanation.py
@@ -0,0 +1,72 @@
+"""The `model_explanation` shape the model card reads, and the reader for rows written before it existed."""
+
+import re
+import math
+from typing import Any
+
+from django.db import models
+
+MAX_TOP_FEATURES = 30
+
+
+class FeatureDirection(models.TextChoices):
+ POSITIVE = "positive"
+ NEGATIVE = "negative"
+
+
+# Champions written before the serializer was typed store their list under other keys.
+_LEGACY_LIST_KEYS = ("top_features", "features", "feature_importances")
+_LEGACY_IMPORTANCE_KEYS = ("importance", "auc_drop_when_shuffled", "gain")
+_POSITIVE_WORDS = {"positive", "+", "up", "raises", "increases"}
+_NEGATIVE_WORDS = {"negative", "-", "down", "lowers", "decreases"}
+
+
+def _direction(value: Any) -> FeatureDirection | None:
+ if not isinstance(value, str):
+ return None
+ text = value.strip().lower()
+ if text in _POSITIVE_WORDS:
+ return FeatureDirection.POSITIVE
+ if text in _NEGATIVE_WORDS:
+ return FeatureDirection.NEGATIVE
+ # Prose such as "higher -> less likely; lower -> more likely". Each clause pairs a value side with a
+ # likelihood, so read the clauses one by one and drop the entry when they disagree.
+ raises: set[bool] = set()
+ for clause in re.split(r"[;,]", text):
+ more, less = "more likely" in clause, "less likely" in clause
+ if not (more or less):
+ continue
+ higher, lower = bool(re.search(r"\bhigher\b", clause)), bool(re.search(r"\blower\b", clause))
+ if (more and less) or (higher and lower):
+ return None
+ raises.add(less if lower else more)
+ if len(raises) != 1:
+ return None
+ return FeatureDirection.POSITIVE if raises.pop() else FeatureDirection.NEGATIVE
+
+
+def _feature(raw: Any) -> dict[str, Any] | None:
+ if not isinstance(raw, dict):
+ return None
+ name = raw.get("name", raw.get("feature"))
+ importance = next((raw[key] for key in _LEGACY_IMPORTANCE_KEYS if key in raw), None)
+ direction = _direction(raw.get("direction"))
+ if not isinstance(name, str) or not name or direction is None:
+ return None
+ if isinstance(importance, bool) or not isinstance(importance, int | float) or not math.isfinite(importance):
+ return None
+ return {"name": name, "importance": abs(float(importance)), "direction": direction.value}
+
+
+def normalize_model_explanation(raw: Any) -> dict[str, Any]:
+ """Map a stored explanation to `{top_features, method?, note?}` and drop entries it cannot read."""
+ if not isinstance(raw, dict):
+ return {"top_features": []}
+ items: Any = next((raw[key] for key in _LEGACY_LIST_KEYS if isinstance(raw.get(key), list)), [])
+ features = [f for f in (_feature(item) for item in items) if f is not None]
+ features.sort(key=lambda f: f["importance"], reverse=True)
+ result: dict[str, Any] = {"top_features": features[:MAX_TOP_FEATURES]}
+ for key in ("method", "note"):
+ if isinstance(raw.get(key), str) and raw[key]:
+ result[key] = raw[key]
+ return result
diff --git a/products/autoresearch/backend/training/runner.py b/products/autoresearch/backend/training/runner.py
index 715a9d270746..637593fff8ec 100644
--- a/products/autoresearch/backend/training/runner.py
+++ b/products/autoresearch/backend/training/runner.py
@@ -46,6 +46,7 @@ from products.autoresearch.backend.models import (
AutoresearchSuggestion,
AutoresearchTrainingRun,
)
+from products.autoresearch.backend.training.explanation import MAX_TOP_FEATURES
from products.tasks.backend.facade import (
api as tasks_facade,
cancellation as tasks_cancellation,
@@ -660,6 +661,10 @@ def build_agent_description(
- `recommended_next`: concretely what a future run should try next given what you found.{notebook_field}
The backend derives the rest of the summary (the kept ladder and dead-ends) from your
recorded iterations, so keep these two fields to judgment only — do not restate the ladder.
+ Also pass `model_explanation`, which the model card charts. Use exactly this shape:
+ `{{"method": "<how you computed importance, one short line>", "top_features": [{{"name": "<feature column>", "importance": <number >= 0>, "direction": "positive" | "negative"}}]}}`.
+ List at most {MAX_TOP_FEATURES} features of the winning iteration, strongest first. `direction` is
+ "positive" when a higher value raises the predicted probability, else "negative". Other keys are dropped.
**Honesty note**: holdout_auc is checked against realized outcomes after inference. An
AUC of 0.55 that reflects real data beats a fabricated 0.80 — the realized gate is unfakeable.
diff --git a/products/autoresearch/backend/training/test_agent_recorded_training.py b/products/autoresearch/backend/training/test_agent_recorded_training.py
index 24ff54fe2be4..54c98cd1783a 100644
--- a/products/autoresearch/backend/training/test_agent_recorded_training.py
+++ b/products/autoresearch/backend/training/test_agent_recorded_training.py
@@ -641,11 +641,51 @@ class TestAgentWriteSerializers(SimpleTestCase):
assert not serializer.is_valid()
assert error_key in serializer.errors, serializer.errors
- def test_complete_rejects_a_non_object_explanation(self) -> None:
- serializer = CompleteTrainingRunSerializer(data={"model_explanation": ["top_features"]})
+ @parameterized.expand(
+ [
+ ("list_shaped", ["top_features"]),
+ ("legacy_features_list", {"features": [{"name": "a", "importance": 0.1, "direction": "positive"}]}),
+ (
+ "legacy_feature_importances_list",
+ {"feature_importances": [{"name": "a", "importance": 0.1, "direction": "positive"}]},
+ ),
+ ("legacy_feature_key", {"top_features": [{"feature": "a", "importance": 0.1, "direction": "positive"}]}),
+ ("prose_direction", {"top_features": [{"name": "a", "importance": 0.1, "direction": "up"}]}),
+ ("negative_importance", {"top_features": [{"name": "a", "importance": -0.1, "direction": "negative"}]}),
+ ("nan_importance", {"top_features": [{"name": "a", "importance": "NaN", "direction": "positive"}]}),
+ (
+ "too_many_features",
+ {"top_features": [{"name": f"f{i}", "importance": 0.1, "direction": "positive"} for i in range(31)]},
+ ),
+ ]
+ )
+ def test_complete_rejects_explanation(self, _name: str, explanation: Any) -> None:
+ serializer = CompleteTrainingRunSerializer(data={"model_explanation": explanation})
assert not serializer.is_valid()
assert "model_explanation" in serializer.errors
+ def test_complete_orders_explanation_features_strongest_first(self) -> None:
+ serializer = CompleteTrainingRunSerializer(
+ data={
+ "model_explanation": {
+ "method": "permutation importance",
+ "top_features": [
+ {"name": "weak", "importance": 0.1, "direction": "negative"},
+ {"name": "strong", "importance": 0.4, "direction": "positive"},
+ ],
+ "extra": "dropped",
+ }
+ }
+ )
+ assert serializer.is_valid(), serializer.errors
+ assert serializer.validated_data["model_explanation"] == {
+ "method": "permutation importance",
+ "top_features": [
+ {"name": "strong", "importance": 0.4, "direction": "positive"},
+ {"name": "weak", "importance": 0.1, "direction": "negative"},
+ ],
+ }
+
class _InMemoryStorage:
"""In-memory object_storage stand-in for bundle round-trips in tests."""
diff --git a/products/autoresearch/backend/training/test_explanation.py b/products/autoresearch/backend/training/test_explanation.py
new file mode 100644
index 000000000000..80dc8ed28d42
--- /dev/null
+++ b/products/autoresearch/backend/training/test_explanation.py
@@ -0,0 +1,87 @@
+from typing import Any
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.autoresearch.backend.training.explanation import MAX_TOP_FEATURES, normalize_model_explanation
+
+
+class TestNormalizeModelExplanation(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "typed_shape",
+ {"method": "m", "top_features": [{"name": "a", "importance": 0.2, "direction": "positive"}]},
+ {"method": "m", "top_features": [{"name": "a", "importance": 0.2, "direction": "positive"}]},
+ ),
+ (
+ "legacy_features_key_and_arrow_prose",
+ {
+ "features": [
+ {"feature": "a", "importance": 0.01, "direction": "higher -> less likely"},
+ {"feature": "b", "importance": 0.05, "direction": "higher = more likely"},
+ ]
+ },
+ {
+ "top_features": [
+ {"name": "b", "importance": 0.05, "direction": "positive"},
+ {"name": "a", "importance": 0.01, "direction": "negative"},
+ ]
+ },
+ ),
+ (
+ "prose_read_per_clause",
+ {
+ "top_features": [
+ {"name": "a", "importance": 0.3, "direction": "higher -> less likely; lower -> more likely"},
+ {"name": "b", "importance": 0.2, "direction": "more likely at lower values"},
+ {"name": "c", "importance": 0.1, "direction": "higher -> more likely; lower -> more likely"},
+ ]
+ },
+ {
+ "top_features": [
+ {"name": "a", "importance": 0.3, "direction": "negative"},
+ {"name": "b", "importance": 0.2, "direction": "negative"},
+ ]
+ },
+ ),
+ (
+ "legacy_feature_importances_key_and_signs",
+ {
+ "feature_importances": [
+ {"feature": "a", "importance": 0.3, "direction": "down"},
+ {"feature": "b", "auc_drop_when_shuffled": 0.2, "direction": "+"},
+ ]
+ },
+ {
+ "top_features": [
+ {"name": "a", "importance": 0.3, "direction": "negative"},
+ {"name": "b", "importance": 0.2, "direction": "positive"},
+ ]
+ },
+ ),
+ (
+ "unreadable_entries_dropped",
+ {
+ "top_features": [
+ "a",
+ {"name": "b", "importance": 0.1, "direction": "sideways"},
+ {"name": "c", "direction": "positive"},
+ {"name": "d", "importance": 0.1, "direction": "lowers"},
+ ]
+ },
+ {"top_features": [{"name": "d", "importance": 0.1, "direction": "negative"}]},
+ ),
+ ("not_an_object", ["a"], {"top_features": []}),
+ ("empty", {}, {"top_features": []}),
+ ]
+ )
+ def test_normalizes(self, _name: str, raw: Any, expected: dict[str, Any]) -> None:
+ assert normalize_model_explanation(raw) == expected
+
+ def test_caps_the_feature_count(self) -> None:
+ raw = {"top_features": [{"name": f"f{i}", "importance": i, "direction": "positive"} for i in range(40)]}
+ features = normalize_model_explanation(raw)["top_features"]
+ assert len(features) == MAX_TOP_FEATURES
+ assert features[0]["name"] == "f39"
diff --git a/products/autoresearch/frontend/generated/api.schemas.ts b/products/autoresearch/frontend/generated/api.schemas.ts
index 231f2c5d9e8a..db2f383c44cf 100644
--- a/products/autoresearch/frontend/generated/api.schemas.ts
+++ b/products/autoresearch/frontend/generated/api.schemas.ts
@@ -315,14 +315,59 @@ export const AutoresearchModelRoleEnumApi = {
} as const
/**
- * Portable recipe artifact. Feature SQL, transforms, model class, params, and metadata.
+ * * `positive` - Positive
+ * * `negative` - Negative
*/
-export type AutoresearchModelApiModelRecipe = { [key: string]: unknown }
+export type FeatureDirectionEnumApi = (typeof FeatureDirectionEnumApi)[keyof typeof FeatureDirectionEnumApi]
+
+export const FeatureDirectionEnumApi = {
+ Positive: 'positive',
+ Negative: 'negative',
+} as const
+
+export interface FeatureImportanceApi {
+ /**
+ * Feature column name, as returned by the feature SQL.
+ * @maxLength 200
+ */
+ name: string
+ /**
+ * Non-negative importance, for example the mean holdout AUC drop when the feature is shuffled.
+ * @minimum 0
+ */
+ importance: number
+ /** 'positive' if a higher value raises the predicted probability, 'negative' if it lowers it.
+ *
+ * * `positive` - Positive
+ * * `negative` - Negative */
+ direction: FeatureDirectionEnumApi
+}
/**
- * Global feature importance and directionality. Used to explain top drivers on the model card.
+ * Global feature importances for the model card.
*/
-export type AutoresearchModelApiModelExplanation = { [key: string]: unknown }
+export interface ModelExplanationFieldApi {
+ /**
+ * At most 30 features, strongest first.
+ * @maxItems 30
+ */
+ top_features?: FeatureImportanceApi[]
+ /**
+ * Short description of how the importances were computed, e.g. 'permutation importance on holdout'.
+ * @maxLength 500
+ */
+ method?: string
+ /**
+ * Optional caveat shown under the chart.
+ * @maxLength 500
+ */
+ note?: string
+}
+
+/**
+ * Portable recipe artifact. Feature SQL, transforms, model class, params, and metadata.
+ */
+export type AutoresearchModelApiModelRecipe = { [key: string]: unknown }
/**
* Extended metrics bundle: Brier score, precision/recall at thresholds, lift@k, base rate, row counts.
@@ -345,7 +390,7 @@ export interface AutoresearchModelApi {
/** Portable recipe artifact. Feature SQL, transforms, model class, params, and metadata. */
model_recipe: AutoresearchModelApiModelRecipe
/** Global feature importance and directionality. Used to explain top drivers on the model card. */
- model_explanation: AutoresearchModelApiModelExplanation
+ model_explanation: ModelExplanationFieldApi
/**
* AUC on the held-out test split at training time. Preliminary signal before online labels mature.
* @nullable
@@ -895,11 +940,6 @@ export interface StoredArtifactApi {
sha256: string
}
-/**
- * Global feature importance / directionality bundle for the champion model card.
- */
-export type CompleteTrainingRunApiModelExplanation = { [key: string]: unknown }
-
/**
* Input for finalizing a training run. The backend selects/promotes the champion.
*/
@@ -910,7 +950,7 @@ export interface CompleteTrainingRunApi {
*/
best_iteration_id?: string | null
/** Global feature importance / directionality bundle for the champion model card. */
- model_explanation?: CompleteTrainingRunApiModelExplanation
+ model_explanation?: ModelExplanationFieldApi
/**
* What a future run should try next, given what this run learned. Stored in the run summary so the next run reads it during orientation. Keep it short and concrete; max 2000 characters.
* @maxLength 2000
diff --git a/products/autoresearch/frontend/generated/api.zod.ts b/products/autoresearch/frontend/generated/api.zod.ts
index 751f48e3d8b3..690aeaf6ad80 100644
--- a/products/autoresearch/frontend/generated/api.zod.ts
+++ b/products/autoresearch/frontend/generated/api.zod.ts
@@ -242,6 +242,16 @@ export const AutoresearchTrainingRunsArtifactsUploadCreateBody = /* @__PURE__ */
* Finalize a training run. The backend selects the kept iteration with the highest holdout score, decides champion vs challenger via the promotion ladder, and persists the model. best_iteration_id is advisory: it breaks a tie at the top score and is otherwise logged and ignored. Agents cannot set the champion directly, because promotion is server-side.
* @summary Complete a training run
*/
+export const autoresearchTrainingRunsCompleteCreateBodyModelExplanationOneTopFeaturesItemNameMax = 200
+
+export const autoresearchTrainingRunsCompleteCreateBodyModelExplanationOneTopFeaturesItemImportanceMin = 0
+
+export const autoresearchTrainingRunsCompleteCreateBodyModelExplanationOneTopFeaturesMax = 30
+
+export const autoresearchTrainingRunsCompleteCreateBodyModelExplanationOneMethodMax = 500
+
+export const autoresearchTrainingRunsCompleteCreateBodyModelExplanationOneNoteMax = 500
+
export const autoresearchTrainingRunsCompleteCreateBodyRecommendedNextDefault = ``
export const autoresearchTrainingRunsCompleteCreateBodyRecommendedNextMax = 2000
@@ -259,7 +269,49 @@ export const AutoresearchTrainingRunsCompleteCreateBody = /* @__PURE__ */ zod
'Advisory nomination. The server promotes the kept iteration with the highest holdout_score; this id only breaks a tie at that score, and a lower-scoring nomination is logged and ignored.'
),
model_explanation: zod
- .looseObject({})
+ .object({
+ top_features: zod
+ .array(
+ zod.object({
+ name: zod
+ .string()
+ .max(
+ autoresearchTrainingRunsCompleteCreateBodyModelExplanationOneTopFeaturesItemNameMax
+ )
+ .describe('Feature column name, as returned by the feature SQL.'),
+ importance: zod
+ .number()
+ .min(
+ autoresearchTrainingRunsCompleteCreateBodyModelExplanationOneTopFeaturesItemImportanceMin
+ )
+ .describe(
+ 'Non-negative importance, for example the mean holdout AUC drop when the feature is shuffled.'
+ ),
+ direction: zod
+ .enum(['positive', 'negative'])
+ .describe('\* `positive` - Positive\n\* `negative` - Negative')
+ .describe(
+ "'positive' if a higher value raises the predicted probability, 'negative' if it lowers it.\n\n\* `positive` - Positive\n\* `negative` - Negative"
+ ),
+ })
+ )
+ .max(autoresearchTrainingRunsCompleteCreateBodyModelExplanationOneTopFeaturesMax)
+ .optional()
+ .describe('At most 30 features, strongest first.'),
+ method: zod
+ .string()
+ .max(autoresearchTrainingRunsCompleteCreateBodyModelExplanationOneMethodMax)
+ .optional()
+ .describe(
+ "Short description of how the importances were computed, e.g. 'permutation importance on holdout'."
+ ),
+ note: zod
+ .string()
+ .max(autoresearchTrainingRunsCompleteCreateBodyModelExplanationOneNoteMax)
+ .optional()
+ .describe('Optional caveat shown under the chart.'),
+ })
+ .describe('Global feature importances for the model card.')
.optional()
.describe('Global feature importance \/ directionality bundle for the champion model card.'),
recommended_next: zod
diff --git a/products/autoresearch/frontend/pipeline/FeatureImportanceChart.tsx b/products/autoresearch/frontend/pipeline/FeatureImportanceChart.tsx
index 2aface54b1f9..0986c3bdc134 100644
--- a/products/autoresearch/frontend/pipeline/FeatureImportanceChart.tsx
+++ b/products/autoresearch/frontend/pipeline/FeatureImportanceChart.tsx
@@ -1,104 +1,55 @@
import { LemonCollapse, Tooltip } from '@posthog/lemon-ui'
-interface FeatureImportance {
- name: string
- direction?: string
- importance?: number
- note?: string
-}
-
-/** Pull the typed top-features list + note out of the loosely-typed model_explanation JSON. */
-function parseExplanation(explanation: unknown): { features: FeatureImportance[]; note: string | null } {
- if (!explanation || typeof explanation !== 'object') {
- return { features: [], note: null }
- }
- const obj = explanation as { top_features?: unknown; note?: unknown }
- const note = typeof obj.note === 'string' ? obj.note : null
- const raw = Array.isArray(obj.top_features) ? obj.top_features : []
- const features = raw
- .map((f): FeatureImportance | null => {
- if (!f || typeof f !== 'object') {
- return null
- }
- const { name, direction, importance, note: featureNote } = f as Record<string, unknown>
- if (typeof name !== 'string') {
- return null
- }
- return {
- name,
- direction: typeof direction === 'string' ? direction : undefined,
- importance: typeof importance === 'number' ? importance : undefined,
- note: typeof featureNote === 'string' ? featureNote : undefined,
- }
- })
- .filter((f): f is FeatureImportance => f !== null)
- // The agent already lists features strongest-first; only re-rank when it gave numbers.
- if (features.some((f) => f.importance != null)) {
- features.sort((a, b) => (b.importance ?? 0) - (a.importance ?? 0))
- }
- return { features, note }
-}
+import { FeatureDirectionEnumApi, ModelExplanationFieldApi } from '../generated/api.schemas'
-/**
- * A model's top feature drivers: importance bars when the agent supplied numeric
- * importances, otherwise a ranked list with the agent's per-feature notes.
- */
-export function FeatureImportanceChart({ explanation }: { explanation: unknown }): JSX.Element | null {
- const { features, note } = parseExplanation(explanation)
- if (features.length === 0) {
- return null
- }
- const hasImportances = features.some((f) => f.importance != null)
+/** A model's top feature drivers, as importance bars relative to the strongest feature. */
+export function FeatureImportanceChart({ explanation }: { explanation: ModelExplanationFieldApi }): JSX.Element {
+ const features = explanation.top_features ?? []
// Gain has no fixed scale, so bars are relative to the strongest feature.
- const maxImportance = Math.max(0, ...features.map((f) => f.importance ?? 0))
- const content = (
- <div className="space-y-2">
- <div className="text-xs text-muted">
- <span style={{ color: 'var(--success)' }}>● raises</span>{' '}
- <span style={{ color: 'var(--danger)' }}>● lowers</span> the prediction
- {hasImportances ? ' · bars relative to the strongest feature' : ' · strongest first'}
- </div>
- <div className="space-y-1">
- {features.map((f) => {
- const isNegative = f.direction === 'negative'
- const isPositive = f.direction === 'positive'
- const color = isNegative ? 'var(--danger)' : isPositive ? 'var(--success)' : 'var(--muted)'
- const effect = isNegative ? 'Lowers' : isPositive ? 'Raises' : 'Unknown effect on'
- return (
- <div key={f.name} className="flex items-center gap-2 text-sm">
- <div className="w-48 shrink-0 truncate font-mono text-xs" title={f.name}>
- <span style={{ color }}>● </span>
- {f.name}
- </div>
- {hasImportances ? (
+ const maxImportance = Math.max(0, ...features.map((f) => f.importance))
+ const content =
+ features.length === 0 ? (
+ <div className="text-xs text-muted">No feature drivers recorded for this model.</div>
+ ) : (
+ <div className="space-y-2">
+ <div className="text-xs text-muted">
+ <span style={{ color: 'var(--success)' }}>● raises</span>{' '}
+ <span style={{ color: 'var(--danger)' }}>● lowers</span> the prediction · bars relative to the
+ strongest feature
+ </div>
+ <div className="space-y-1">
+ {features.map((f) => {
+ const isNegative = f.direction === FeatureDirectionEnumApi.Negative
+ const color = isNegative ? 'var(--danger)' : 'var(--success)'
+ const effect = isNegative ? 'Lowers' : 'Raises'
+ return (
+ <div key={f.name} className="flex items-center gap-2 text-sm">
+ <div className="w-48 shrink-0 truncate font-mono text-xs" title={f.name}>
+ <span style={{ color }}>● </span>
+ {f.name}
+ </div>
<div
className="flex-1 rounded h-4 overflow-hidden"
style={{ backgroundColor: 'var(--border)' }}
>
- <Tooltip
- title={`${effect} the prediction · importance ${(f.importance ?? 0).toFixed(3)}`}
- >
+ <Tooltip title={`${effect} the prediction · importance ${f.importance.toFixed(3)}`}>
<div
className="h-full rounded"
style={{
- width: `${maxImportance > 0 ? Math.max(2, ((f.importance ?? 0) / maxImportance) * 100) : 2}%`,
+ width: `${maxImportance > 0 ? Math.max(2, (f.importance / maxImportance) * 100) : 2}%`,
backgroundColor: color,
}}
/>
</Tooltip>
</div>
- ) : (
- <Tooltip title={f.note}>
- <div className="flex-1 min-w-0 truncate text-xs text-muted">{f.note}</div>
- </Tooltip>
- )}
- </div>
- )
- })}
+ </div>
+ )
+ })}
+ </div>
+ {explanation.method && <div className="text-xs text-muted">Method: {explanation.method}</div>}
+ {explanation.note && <div className="text-xs text-muted italic">{explanation.note}</div>}
</div>
- {note && <div className="text-xs text-muted italic">{note}</div>}
- </div>
- )
+ )
return (
<LemonCollapse
size="small"
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index fd1bc2b76c97..f5779b5f3a24 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -13310,11 +13310,6 @@ export namespace Schemas {
*/
export type AutoresearchModelModelRecipe = { [key: string]: unknown };
- /**
- * Global feature importance and directionality. Used to explain top drivers on the model card.
- */
- export type AutoresearchModelModelExplanation = { [key: string]: unknown };
-
/**
* Extended metrics bundle: Brier score, precision/recall at thresholds, lift@k, base rate, row counts.
*/
@@ -13334,6 +13329,57 @@ export namespace Schemas {
Archived: 'archived',
} as const;
+ /**
+ * * `positive` - Positive
+ * * `negative` - Negative
+ */
+ export type FeatureDirectionEnum = typeof FeatureDirectionEnum[keyof typeof FeatureDirectionEnum];
+
+
+ export const FeatureDirectionEnum = {
+ Positive: 'positive',
+ Negative: 'negative',
+ } as const;
+
+ export interface FeatureImportance {
+ /**
+ * Feature column name, as returned by the feature SQL.
+ * @maxLength 200
+ */
+ name: string;
+ /**
+ * Non-negative importance, for example the mean holdout AUC drop when the feature is shuffled.
+ * @minimum 0
+ */
+ importance: number;
+ /** 'positive' if a higher value raises the predicted probability, 'negative' if it lowers it.
+ *
+ * * `positive` - Positive
+ * * `negative` - Negative */
+ direction: FeatureDirectionEnum;
+ }
+
+ /**
+ * Global feature importances for the model card.
+ */
+ export interface ModelExplanationField {
+ /**
+ * At most 30 features, strongest first.
+ * @maxItems 30
+ */
+ top_features?: FeatureImportance[];
+ /**
+ * Short description of how the importances were computed, e.g. 'permutation importance on holdout'.
+ * @maxLength 500
+ */
+ method?: string;
+ /**
+ * Optional caveat shown under the chart.
+ * @maxLength 500
+ */
+ note?: string;
+ }
+
export interface AutoresearchModel {
/** Unique UUID of this model version. */
readonly id: string;
@@ -13350,7 +13396,7 @@ export namespace Schemas {
/** Portable recipe artifact. Feature SQL, transforms, model class, params, and metadata. */
model_recipe: AutoresearchModelModelRecipe;
/** Global feature importance and directionality. Used to explain top drivers on the model card. */
- model_explanation: AutoresearchModelModelExplanation;
+ model_explanation: ModelExplanationField;
/**
* AUC on the held-out test split at training time. Preliminary signal before online labels mature.
* @nullable
@@ -23636,11 +23682,6 @@ export namespace Schemas {
check_run_id?: string;
}
- /**
- * Global feature importance / directionality bundle for the champion model card.
- */
- export type CompleteTrainingRunModelExplanation = { [key: string]: unknown };
-
/**
* Input for finalizing a training run. The backend selects/promotes the champion.
*/
@@ -23651,7 +23692,7 @@ export namespace Schemas {
*/
best_iteration_id?: string | null;
/** Global feature importance / directionality bundle for the champion model card. */
- model_explanation?: CompleteTrainingRunModelExplanation;
+ model_explanation?: ModelExplanationField;
/**
* What a future run should try next, given what this run learned. Stored in the run summary so the next run reads it during orientation. Keep it short and concrete; max 2000 characters.
* @maxLength 2000
diff --git a/services/mcp/src/generated/autoresearch/api.ts b/services/mcp/src/generated/autoresearch/api.ts
index f36ca37434be..c3752ecc81a0 100644
--- a/services/mcp/src/generated/autoresearch/api.ts
+++ b/services/mcp/src/generated/autoresearch/api.ts
@@ -419,6 +419,16 @@ export const AutoresearchTrainingRunsCompleteCreateParams = () => zod.object({
),
})
+export const autoresearchTrainingRunsCompleteCreateBodyModelExplanationOneTopFeaturesItemNameMax = 200
+
+export const autoresearchTrainingRunsCompleteCreateBodyModelExplanationOneTopFeaturesItemImportanceMin = 0
+
+export const autoresearchTrainingRunsCompleteCreateBodyModelExplanationOneTopFeaturesMax = 30
+
+export const autoresearchTrainingRunsCompleteCreateBodyModelExplanationOneMethodMax = 500
+
+export const autoresearchTrainingRunsCompleteCreateBodyModelExplanationOneNoteMax = 500
+
export const autoresearchTrainingRunsCompleteCreateBodyRecommendedNextDefault = ``
export const autoresearchTrainingRunsCompleteCreateBodyRecommendedNextMax = 2000
@@ -436,7 +446,49 @@ export const AutoresearchTrainingRunsCompleteCreateBody = () => zod
'Advisory nomination. The server promotes the kept iteration with the highest holdout_score; this id only breaks a tie at that score, and a lower-scoring nomination is logged and ignored.'
),
model_explanation: zod
- .looseObject({})
+ .object({
+ top_features: zod
+ .array(
+ zod.object({
+ name: zod
+ .string()
+ .max(
+ autoresearchTrainingRunsCompleteCreateBodyModelExplanationOneTopFeaturesItemNameMax
+ )
+ .describe('Feature column name, as returned by the feature SQL.'),
+ importance: zod
+ .number()
+ .min(
+ autoresearchTrainingRunsCompleteCreateBodyModelExplanationOneTopFeaturesItemImportanceMin
+ )
+ .describe(
+ 'Non-negative importance, for example the mean holdout AUC drop when the feature is shuffled.'
+ ),
+ direction: zod
+ .enum(['positive', 'negative'])
+ .describe('\* `positive` - Positive\n\* `negative` - Negative')
+ .describe(
+ "'positive' if a higher value raises the predicted probability, 'negative' if it lowers it.\n\n\* `positive` - Positive\n\* `negative` - Negative"
+ ),
+ })
+ )
+ .max(autoresearchTrainingRunsCompleteCreateBodyModelExplanationOneTopFeaturesMax)
+ .optional()
+ .describe('At most 30 features, strongest first.'),
+ method: zod
+ .string()
+ .max(autoresearchTrainingRunsCompleteCreateBodyModelExplanationOneMethodMax)
+ .optional()
+ .describe(
+ "Short description of how the importances were computed, e.g. 'permutation importance on holdout'."
+ ),
+ note: zod
+ .string()
+ .max(autoresearchTrainingRunsCompleteCreateBodyModelExplanationOneNoteMax)
+ .optional()
+ .describe('Optional caveat shown under the chart.'),
+ })
+ .describe('Global feature importances for the model card.')
.optional()
.describe('Global feature importance \/ directionality bundle for the champion model card.'),
recommended_next: zod