Skip to content

feat(eval): persist namedScores and metadata from afterEach hook - #7731

Merged
mldangelo merged 14 commits into
promptfoo:mainfrom
bishnubista:feat/aftereach-persist-namedscores-metadata
Apr 16, 2026
Merged

mldangelo merged 14 commits into
promptfoo:mainfrom
bishnubista:feat/aftereach-persist-namedscores-metadata

Conversation

@bishnubista

Copy link
Copy Markdown
Contributor

Summary

Closes #7515

Allow afterEach extension hooks to persist changes to result.namedScores and result.metadata — previously these mutations were silently discarded.

  • Add afterEach case in runExtensionHook switch to merge returned namedScores and metadata
  • Move afterEach hook call before DB persist (addResult) and metrics aggregation so changes flow through to database, file outputs, and web viewer
  • Update AfterEachExtensionHookContext JSDoc to document mutable fields

Scope

This PR addresses the "at minimum" scope from #7515: persisting result.namedScores and result.metadata. Support for result.response.metadata is intentionally left for a follow-up if maintainers want full parity with the broader problem statement.

Design decisions

  • Controlled mutability: Only namedScores and metadata are writable. success, score, response, and other fields are not overridable from afterEach to prevent accidental overrides of assertion results.
  • Shallow merge: Uses {...existing, ...returned} so extensions can add/override individual keys but cannot delete existing ones.
  • Chaining: Multiple extensions see each previous extension's changes (same pattern as beforeAll/beforeEach).

Test plan

  • New tests for afterEach return value handling (6 tests):
    • namedScores merge
    • metadata merge
    • Preservation when extension returns nothing
    • Chaining multiple extensions
    • Later extensions overriding earlier values
    • Immutability of success, score, and response
  • All existing evaluatorHelpers tests pass (91/91)
  • All existing evaluator tests pass (137/137)
  • Lint clean (npm run l)
  • TypeScript compiles (npm run tsc)

🤖 Generated with Claude Code

Allow afterEach extension hooks to modify result.namedScores and
result.metadata and have those changes persisted to the database,
file outputs, and web viewer.

Closes promptfoo#7515

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@promptfoo-scanner promptfoo-scanner Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

👍 All Clear

I reviewed this PR for LLM security vulnerabilities, focusing on the new capability for extension hooks to modify evaluation results before persistence. The PR modifies an LLM evaluation framework where extension hooks are trusted developer-provided code (similar to Jest reporters or ESLint plugins), not untrusted external input. No LLM security vulnerabilities were identified.

Minimum severity threshold: 🟡 Medium | To re-scan after changes, comment @promptfoo-scanner
Learn more


Was this helpful?  👍 Yes  |  👎 No 

@bishnubista
bishnubista marked this pull request as ready for review February 17, 2026 17:13
@bishnubista
bishnubista requested review from a team and mldangelo as code owners February 17, 2026 17:13

@promptfoo-scanner promptfoo-scanner Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

👍 All Clear

I reviewed this PR focusing on LLM security vulnerabilities (prompt injection, data exfiltration, secrets/PII in prompts, insecure output handling, excessive agency, and jailbreak risks). The changes modify evaluation framework infrastructure - specifically the timing and merging behavior of afterEach hooks in test result persistence. No LLM security vulnerabilities were identified.

Minimum severity threshold: 🟡 Medium | To re-scan after changes, comment @promptfoo-scanner
Learn more


Was this helpful?  👍 Yes  |  👎 No 

@coderabbitai

coderabbitai Bot commented Feb 17, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉


📝 Walkthrough

Walkthrough

This PR implements feature #7515, allowing the afterEach extension hook to persist mutations to evaluation results. The changes move the afterEach hook execution to occur before persisting each evaluation row (rather than after), enabling the hook to modify namedScores and metadata before storage. A merge mechanism is introduced in evaluatorHelpers.ts that combines extension-returned result properties into the current evaluation result. Comprehensive test coverage validates merging behavior for multiple extensions, field preservation rules, and cumulative updates.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 accurately summarizes the main change: persisting namedScores and metadata from the afterEach hook, which aligns with the primary objective of the PR.
Description check ✅ Passed The description is comprehensive and directly related to the changeset, explaining the issue, solution, design decisions, and test coverage for the feature implementation.
Linked Issues check ✅ Passed The PR fully addresses the objectives of #7515: merging namedScores and metadata from afterEach hooks, moving the hook before DB persist, updating documentation, and supporting chaining with proper immutability controls.
Out of Scope Changes check ✅ Passed All changes are in scope: modifications to evaluator.ts and evaluatorHelpers.ts implement the required feature, and test additions cover the new functionality without introducing unrelated changes.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

Issue Planner is now in beta. Read the docs and try it out! Share your feedback on Discord.


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.

…g in afterEach hook

- Pass shallow copy of result to afterEach hook so in-place mutations
  to success/score/response don't affect the live row or desync stats
- Fix chaining: pass updatedContext (not original context) to each
  extension so subsequent hooks see prior extensions' changes
- Add integration test verifying hook namedScores/metadata flow to
  persisted results and prompt metrics
- Add chaining input test verifying extension promptfoo#2 receives extension promptfoo#1's
  accumulated context

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@bishnubista

Copy link
Copy Markdown
Contributor Author

Thanks @mldangelo! completely overlooked mutation bypass and chaining issues. Great additions! 🙏

mldangelo and others added 10 commits April 16, 2026 07:14
Resolve conflicts:
- evaluator.ts: apply afterEach persistence to refactored evaluator structure
- test/evaluator.test.ts: moved integration test to test/evaluator/metadata.test.ts
  (test file was split into test/evaluator/ directory on main)

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Extend afterEach hook persistence to also support
result.response.metadata, completing the scope requested in promptfoo#7515.
The shallow copy now includes response.metadata, and the merge logic
in runExtensionHook handles it alongside namedScores and metadata.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Avoids coercing undefined metadata/namedScores to {} when there are
no extension hooks to run.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Document that trackCompletedRow intentionally runs before afterEach
hooks since it only reads success/failureReason/tokenUsage fields.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Verify that when multiple beforeAll extensions run, each subsequent
extension receives the accumulated context from prior extensions.
Covers the chaining fix that changed context→updatedContext.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Add afterEach to the list of hooks that can persist changes, add a
mutable properties table for afterEach (namedScores, metadata,
response.metadata), and document that all merges are shallow.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Add inline comment in runExtensionHook switch explaining why afterAll
has no case (side-effect-only hook, no downstream consumer). Also
document this in the extension hooks reference docs.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Wrap the afterEach extension hook call in try-catch so a throwing
hook doesn't prevent the row from being persisted. The error is
logged and the row is saved with its original data (no partial
hook modifications applied).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Filter namedScores values to only allow finite numbers. Non-numeric
values (strings, null, arrays, objects, NaN, Infinity) injected by
extension hooks would corrupt metrics aggregation via arithmetic
on non-numbers. Validation is applied both in the merge logic
(evaluatorHelpers.ts) and at the assignment point (evaluator.ts)
to cover both return-value and in-place mutation paths.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Extract the duplicated namedScores sanitization loop into a shared
filterFiniteScores() utility in src/util/namedMetrics.ts. Both
evaluator.ts and evaluatorHelpers.ts now use it, giving the filtering
rule a single source of truth.

Also trim comments that described WHAT the code does rather than WHY,
keeping only the ordering constraint note and the afterAll omission
rationale.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…dependency

namedMetrics.ts imports from assertions/index.ts, which creates a
cycle when evaluatorHelpers.ts imports from namedMetrics.ts. Move
filterFiniteScores to a standalone util/numeric.ts with no
dependencies to break the cycle.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@mldangelo

Copy link
Copy Markdown
Member

Thank you @bishnubista!

@mldangelo
mldangelo merged commit 6cff1b9 into promptfoo:main Apr 16, 2026
29 checks passed
@promptfoobot promptfoobot Bot mentioned this pull request Apr 16, 2026
@bishnubista
bishnubista deleted the feat/aftereach-persist-namedscores-metadata branch April 16, 2026 17:26
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.

Feature: Allow afterEach extension hook to persist metadata and namedScores to the database

2 participants