fix(prreview): restore the benchmark runner on configured models and public PRs

This commit is contained in:
sam committed 2026-10-11 04:11:40 +11:00
1 parent 5c3bf0b642
commit e2d6b75b10
7 files changed
+1110

No files matched your search

+5
View File
@@ -170,6 +170,11 @@ tasks:
cmds:
- bash tools/webhook-send.sh {{.CLI_ARGS}}
bench:prreview:
desc: Run the PR review benchmark on the configured models and write docs/benchmarks/pr-review-*.md (-- -model ALIAS -judge-model REF; --help for flags)
cmds:
- go run ./cmd/archied prbench {{.CLI_ARGS}}
dev:
desc: Run development services and Vite at http://localhost:5173
deps: [dev:daemon, dev:gateway, dev:messaging, dev:state-store, dev:dashboard, dev:ui]
+4
View File
@@ -6,6 +6,7 @@ import (
"github.com/samcharles93/archie-core/internal/app/archied"
"github.com/samcharles93/archie-core/internal/app/archieplaybooks"
"github.com/samcharles93/archie-core/internal/app/prbench"
)
func main() {
@@ -28,6 +29,9 @@ func main() {
if len(args) > 0 && args[0] == "status" {
os.Exit(archied.RunStatus(args[1:], os.Stdout, os.Stderr))
}
if len(args) > 0 && args[0] == "prbench" {
os.Exit(prbench.Main(args[1:], os.Stdout, os.Stderr))
}
if len(args) > 0 && args[0] == "playbooks" {
os.Exit(archieplaybooks.Run(args[1:], os.Stderr))
}
+24
View File
@@ -0,0 +1,24 @@
# PR review benchmark
```
task bench:prreview
```
Reviews the 38 runnable Martian pull requests once each at `deep` depth with
the production pipeline, judges the posted comments against the golden
comments in `internal/app/prbench/martian.json`, and writes
`docs/benchmarks/pr-review-<timestamp>.md` (recall per PR, overall recall,
precision, models, archie version). Commit that file with the run.
- Models come from the config at `~/.config/archie/config.toml`: the reviewer
and judge both default to its `default` alias. Override with
`task bench:prreview -- -model ALIAS_OR_PROVIDER/MODEL -judge-model ALIAS_OR_PROVIDER/MODEL`.
Pick a judge other than the reviewer's model for an independent judgement.
Aliases set only in the dashboard are not in the file; pass a
`provider/model` ref instead.
- Pull requests are public, so no credential is needed. `GH_TOKEN` or
`GITHUB_TOKEN`, if set, only raises the GitHub API rate limit.
- `-problems ID,ID` runs a partial smoke run; its report says it is not the
acceptance run. A full run reports PASS when nothing failed and golden
micro-recall is at least 0.70.
- It is not part of `task test` and posts nothing to any pull request.
+90
View File
@@ -0,0 +1,90 @@
package prbench
import (
"context"
"fmt"
"strings"
"github.com/samcharles93/ai-sdk/agent"
"github.com/samcharles93/ai-sdk/core"
"github.com/samcharles93/ai-sdk/runtime"
"github.com/samcharles93/archie-core/internal/domain/workflow/prreview"
"github.com/samcharles93/archie-core/internal/domain/workflow/prreview/bench"
)
// modelJudge asks one model, independent of the reviewer's, which posted
// comment catches each golden.
type modelJudge struct {
runtime *runtime.Runtime
modelRef string
}
func (j *modelJudge) Judge(ctx context.Context, p bench.Problem, comments []prreview.ScoredFinding) ([]bench.Verdict, error) {
provider, model, err := j.runtime.ChatProvider(ctx, j.modelRef)
if err != nil {
return nil, fmt.Errorf("resolve judge model %q: %w", j.modelRef, err)
}
var verdicts []bench.Verdict
sub := agent.Subagent{
Provider: provider,
Model: model,
System: judgeSystemPrompt,
Tools: core.ToolSet{"record_verdict": recordVerdictTool(len(p.Goldens), len(comments), &verdicts)},
MaxSteps: 2*len(p.Goldens) + 3,
}
// The verdicts are the judgement, not the closing reply: a run that recorded
// some and then ran out of steps is checked for completeness by the caller.
if _, err := sub.Run(ctx, judgePrompt(p, comments)); err != nil && len(verdicts) == 0 {
return nil, err
}
return verdicts, nil
}
const judgeSystemPrompt = `You score a code reviewer against known defects. You are given the pull request's known defects (goldens) and the numbered comments the reviewer posted.
For each golden, decide whether any posted comment identifies the same underlying defect: the same location and the same root cause. A comment about the same file but a different problem is not a match, and neither is a vague comment that would only be right by coincidence. Wording does not need to match.
Call record_verdict exactly once per golden. Pass the index of the matching comment, or -1 when no comment matches, and a one-sentence reason. When several comments match, pass the one that states the defect most directly.`
func judgePrompt(p bench.Problem, comments []prreview.ScoredFinding) string {
var b strings.Builder
fmt.Fprintf(&b, "Pull request: %s\n\n<goldens>\n", p.PRURL)
for i, g := range p.Goldens {
fmt.Fprintf(&b, "[%d] (%s) %s\n", i, g.Severity, g.Comment)
}
b.WriteString("</goldens>\n\n<comments>\n")
for i, c := range comments {
fmt.Fprintf(&b, "[%d] %s:%d-%d (%s) %s\n%s\n\n", i, c.File, c.LineStart, c.LineEnd, c.Severity, c.Title, c.Body)
}
b.WriteString("</comments>\n")
return b.String()
}
type verdictInput struct {
Golden int `json:"golden" jsonschema:"description=Index of the golden this verdict is for."`
Comment int `json:"comment" jsonschema:"description=Index of the comment that identifies the same defect, or -1 when none does."`
Reason string `json:"reason" jsonschema:"description=One sentence on why the comment does or does not match."`
}
func recordVerdictTool(goldens, comments int, verdicts *[]bench.Verdict) *core.Tool {
return core.NewTypedTool(
"record_verdict",
"Record whether a posted comment catches one golden. Call once per golden.",
func(_ context.Context, in verdictInput) (string, error) {
if in.Golden < 0 || in.Golden >= goldens {
return fmt.Sprintf("record_verdict rejected: golden must be 0..%d", goldens-1), nil
}
if in.Comment < bench.NoComment || in.Comment >= comments {
return fmt.Sprintf("record_verdict rejected: comment must be -1..%d", comments-1), nil
}
for _, v := range *verdicts {
if v.Golden == in.Golden {
return fmt.Sprintf("record_verdict rejected: golden %d already has a verdict", in.Golden), nil
}
}
*verdicts = append(*verdicts, bench.Verdict{Golden: in.Golden, Comment: in.Comment, Reason: in.Reason})
return "verdict recorded", nil
},
)
}
+150
View File
@@ -0,0 +1,150 @@
package prbench
import (
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/agentrun"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/domain/workflow/prreview"
"github.com/samcharles93/archie-core/internal/domain/workflow/prreview/bench"
"github.com/samcharles93/archie-core/internal/infrastructure/prsource"
)
// liveReviewer runs the production pr-review decision phases on one problem.
type liveReviewer struct {
cfg config.Config
agent agentrun.Runner
source workflow.PRSource
nextID atomic.Int64
}
func (r *liveReviewer) Review(ctx context.Context, p bench.Problem) (bench.Review, error) {
owner, repo, number, err := parsePRURL(p.PRURL)
if err != nil {
return bench.Review{}, err
}
slog.Info("benchmark review started", "problem", p.ID)
tc := &workflow.TaskContext{
Task: &workflow.Task{ID: r.nextID.Add(1), Attempt: 1, Owner: owner, Repo: repo, PRNumber: number, Workflow: "pr-review", Inputs: map[string]any{"depth": "deep"}},
Cfg: r.cfg, Agent: r.agent, PRSource: r.source, Log: slog.Default(),
}
decision, err := workflow.ReviewPullRequest(ctx, tc)
if err != nil {
return bench.Review{}, err
}
// Non-nil empty comments means a completed pipeline found nothing.
if decision.Comments == nil {
decision.Comments = []prreview.ScoredFinding{}
}
slog.Info("benchmark review completed", "problem", p.ID, "comments", len(decision.Comments), "skipped_phases", decision.SkippedPhases)
return bench.Review{Comments: decision.Comments, SkippedPhases: decision.SkippedPhases}, nil
}
func parsePRURL(raw string) (string, string, int, error) {
u, err := url.Parse(raw)
if err != nil {
return "", "", 0, fmt.Errorf("invalid pull request URL: %w", err)
}
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
if u.Scheme != "https" || u.Host != "github.com" || len(parts) != 4 || parts[2] != "pull" {
return "", "", 0, fmt.Errorf("benchmark requires a GitHub pull request URL")
}
n, err := strconv.Atoi(parts[3])
if err != nil || n <= 0 {
return "", "", 0, fmt.Errorf("invalid pull request URL")
}
return parts[0], parts[1], n, nil
}
// publicGitHub reads the benchmark's public pull requests anonymously. The
// diff and archive come from hosts outside the API rate limit, so a full run
// makes one API call per pull request. GH_TOKEN or GITHUB_TOKEN, when set,
// only lifts that API limit.
type publicGitHub struct {
token string
mu sync.Mutex
prs map[string]prsource.PullRequest
}
func newPublicGitHub() *publicGitHub {
token := os.Getenv("GH_TOKEN")
if token == "" {
token = os.Getenv("GITHUB_TOKEN")
}
return &publicGitHub{token: token, prs: map[string]prsource.PullRequest{}}
}
func (g *publicGitHub) get(ctx context.Context, rawURL string, api bool) (io.ReadCloser, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return nil, err
}
if api && g.token != "" {
req.Header.Set("Authorization", "Bearer "+g.token)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
_ = resp.Body.Close()
return nil, fmt.Errorf("GET %s: %s", rawURL, resp.Status)
}
return resp.Body, nil
}
func (g *publicGitHub) GetPullRequest(ctx context.Context, owner, repo string, number int) (prsource.PullRequest, error) {
key := fmt.Sprintf("%s/%s#%d", owner, repo, number)
g.mu.Lock()
pr, ok := g.prs[key]
g.mu.Unlock()
if ok {
return pr, nil
}
body, err := g.get(ctx, fmt.Sprintf("https://api.github.com/repos/%s/%s/pulls/%d", owner, repo, number), true)
if err != nil {
return prsource.PullRequest{}, err
}
defer body.Close()
var raw struct {
Title string `json:"title"`
Body string `json:"body"`
Head struct {
SHA string `json:"sha"`
} `json:"head"`
}
if err := json.NewDecoder(body).Decode(&raw); err != nil {
return prsource.PullRequest{}, err
}
pr = prsource.PullRequest{Title: raw.Title, Body: raw.Body, HeadSHA: raw.Head.SHA}
g.mu.Lock()
g.prs[key] = pr
g.mu.Unlock()
return pr, nil
}
func (g *publicGitHub) GetPullRequestDiff(ctx context.Context, owner, repo string, number int) (string, error) {
body, err := g.get(ctx, fmt.Sprintf("https://github.com/%s/%s/pull/%d.diff", owner, repo, number), false)
if err != nil {
return "", err
}
defer body.Close()
data, err := io.ReadAll(body)
return string(data), err
}
func (g *publicGitHub) GetRepoArchive(ctx context.Context, owner, repo, ref string) (io.ReadCloser, error) {
return g.get(ctx, fmt.Sprintf("https://codeload.github.com/%s/%s/tar.gz/%s", owner, repo, ref), false)
}
+638
View File
@@ -0,0 +1,638 @@
[
{
"id": "cal_dot_com#10600",
"pr_url": "https://github.com/calcom/cal.com/pull/10600",
"goldens": [
{
"comment": "The exported function TwoFactor handles backup codes and is in BackupCode.tsx. Inconsistent naming.",
"severity": "Low"
},
{
"comment": "Error message mentions 'backup code login' but this is a disable endpoint, not login",
"severity": "Low"
},
{
"comment": "Backup code validation is case-sensitive due to the use of indexOf(). This causes validation to fail if a user enters uppercase hex characters, as backup codes should be case-insensitive for a better user experience.",
"severity": "Medium"
},
{
"comment": "Because backupCodes are decrypted and mutated in memory before being written back, two concurrent login requests using the same backupCode could both pass this check and update, so a single backup code may effectively be accepted more than once if used concurrently, weakening the intended one-time-use semantics.",
"severity": "High"
}
]
},
{
"id": "cal_dot_com#10967",
"pr_url": "https://github.com/calcom/cal.com/pull/10967",
"goldens": [
{
"comment": "Potential null reference if mainHostDestinationCalendar is undefined if evt.destinationCalendar is null or an empty array ",
"severity": "High"
},
{
"comment": "The optional chaining on mainHostDestinationCalendar?.integration is redundant since you already check mainHostDestinationCalendar in the ternary condition.",
"severity": "Low"
},
{
"comment": "Logic error: when externalCalendarId is provided, you're searching for a calendar where externalId === externalCalendarId, but this will always fail since you're looking for a calendar that matches itself. Should likely find by credentialId or use different logic.",
"severity": "High"
},
{
"comment": "Logic inversion in organization creation: The slug property is now conditionally set when IS_TEAM_BILLING_ENABLED is true, instead of when it's false as originally intended. This change, combined with requestedSlug still being set when IS_TEAM_BILLING_ENABLED is true, results in both properties being set when billing is enabled, and neither when disabled",
"severity": "Medium"
},
{
"comment": "The Calendar interface now requires createEvent(event, credentialId), but some implementations (e.g., Lark/Office365) still declare createEvent(event) only—this breaks the interface contract (also applies to other locations in the PR).",
"severity": "Low"
}
]
},
{
"id": "cal_dot_com#11059",
"pr_url": "https://github.com/calcom/cal.com/pull/11059",
"goldens": [
{
"comment": "The parseRefreshTokenResponse function incorrectly sets refresh_token to the hardcoded string 'refresh_token' when it's missing from the OAuth refresh token response. This invalidates the token, breaking subsequent token refreshes and causing authentication failures.",
"severity": "High"
},
{
"comment": "Invalid Zod schema syntax. Computed property keys like [z.string().toString()] are not valid in Zod object schemas and will cause runtime errors. ",
"severity": "High"
},
{
"comment": "parseRefreshTokenResponse returns a Zod safeParse result ({ success, data, error }), not the credential key object. Persisting that as key stores the wrapper instead of the token payload; we should store the parsed data or use schema parse.",
"severity": "High"
},
{
"comment": "When APP_CREDENTIAL_SHARING_ENABLED and CALCOM_CREDENTIAL_SYNC_ENDPOINT are set, the refreshFunction helper returns the fetch Response, but several callers (for example GoogleCalendarService.refreshAccessToken expecting res.data, and HubspotCalendarService.refreshAccessToken expecting a HubspotToken) assume it returns the integration-specific token object. That mismatch will cause runtime errors in the sync-enabled path unless the return type or those call sites are adjusted.",
"severity": "High"
},
{
"comment": "When the sync endpoint path is used, res is a fetch Response and has no .data; res?.data will be undefined and token.access_token will throw at runtime. This relies on a consistent return shape from refreshOAuthTokens, which isn’t guaranteed currently.",
"severity": "High"
}
]
},
{
"id": "cal_dot_com#14740",
"pr_url": "https://github.com/calcom/cal.com/pull/14740",
"goldens": [
{
"comment": "Case sensitivity bypass in email blacklist",
"severity": "High"
},
{
"comment": "The logic for checking team admin/owner permissions is incorrect. This condition uses AND (&&) which requires both isTeamAdmin AND isTeamOwner to be true, but it should use OR (||) since a user needs to be either an admin OR an owner to have permission.",
"severity": "Critical"
},
{
"comment": "This calls the email sender with the original guests, so existing attendees included in the input will be treated as new when sending notifications, leading to incorrect emails.",
"severity": "Medium"
},
{
"comment": "uniqueGuests filters out existing attendees and blacklisted emails but does not deduplicate duplicates within the input; createMany can insert duplicate attendee rows if the client submits repeated emails.",
"severity": "Medium"
},
{
"comment": "Starting with an array containing an empty string may cause validation issues. Consider starting with an empty array [] and handling the empty state in the MultiEmail component instead.",
"severity": "Low"
}
]
},
{
"id": "cal_dot_com#14943",
"pr_url": "https://github.com/calcom/cal.com/pull/14943",
"goldens": [
{
"comment": "Using retryCount: reminder.retryCount + 1 reads a possibly stale value and can lose increments under concurrency; consider an atomic increment via Prisma (increment: 1) to avoid race conditions (also applies to the similar update in the catch block).",
"severity": "High"
},
{
"comment": "The deletion logic in scheduleSMSReminders.ts incorrectly deletes non-SMS workflow reminders (e.g., Email, WhatsApp) that have retryCount > 1. This occurs because the retryCount condition within the OR clause for deletion lacks a method: WorkflowMethods.SMS filter, causing it to apply to all reminder types instead of only SMS reminders, which is the intended scope of this function.",
"severity": "High"
}
]
},
{
"id": "cal_dot_com#22345",
"pr_url": "https://github.com/calcom/cal.com/pull/22345",
"goldens": [
{
"comment": "In getBaseConditions(), the else if (filterConditions) and final else branches are unreachable. This is because getAuthorizationConditions() always returns a non-null Prisma.Sql object, making authConditions always truthy, which means only the first two if/else if conditions are ever evaluated.",
"severity": "Low"
},
{
"comment": "Fetching userIdsFromOrg only when teamsFromOrg.length > 0 can exclude org-level members for orgs without child teams; consider deriving from teamIds (which includes orgId) or removing the guard so org-only orgs still include member user bookings.",
"severity": "Medium"
}
]
},
{
"id": "cal_dot_com#22532",
"pr_url": "https://github.com/calcom/cal.com/pull/22532",
"goldens": [
{
"comment": "The updateManyByCredentialId call uses an empty data object, which prevents Prisma's @updatedAt decorator from updating the updatedAt timestamp. This results in inaccurate cache status tracking, as the timestamp isn't updated when the cache is refreshed. To fix this, explicitly set the updatedAt field.",
"severity": "Medium"
},
{
"comment": "logic: macOS-specific sed syntax with empty string after -i flag will fail on Linux systems",
"severity": "Low"
}
]
},
{
"id": "cal_dot_com#7232",
"pr_url": "https://github.com/calcom/cal.com/pull/7232",
"goldens": [
{
"comment": "Asynchronous functions deleteScheduledEmailReminder and deleteScheduledSMSReminder are called without await inside forEach loops. This occurs during booking rescheduling/cancellation, and workflow/workflow step deletion/updates. Consequently, scheduled workflow reminders may not be reliably cancelled, potentially leaving them active.",
"severity": "Medium"
},
{
"comment": "When immediateDelete is true, the deleteScheduledEmailReminder function cancels the SendGrid email but fails to delete the corresponding WorkflowReminder record from the database. This creates orphaned database entries and is inconsistent with the immediateDelete: false path, which marks the record as cancelled. The SendGrid DELETE API call is also omitted in this path.",
"severity": "High"
}
]
},
{
"id": "cal_dot_com#8087",
"pr_url": "https://github.com/calcom/cal.com/pull/8087",
"goldens": [
{
"comment": "Consider adding try-catch around the await to handle import failures gracefully",
"severity": "Low"
},
{
"comment": "The code uses forEach with async callbacks, which causes asynchronous operations (e.g., calendar/video event deletions, payment refunds) to run concurrently without being awaited. This 'fire-and-forget' behavior leads to unhandled promise rejections, race conditions, and incomplete cleanup, as surrounding try-catch blocks cannot properly handle errors from these unawaited promises. Replace forEach with for...of loops or Promise.all() with map() to ensure proper sequential execution and error handling.",
"severity": "Critical"
}
]
},
{
"id": "cal_dot_com#8330",
"pr_url": "https://github.com/calcom/cal.com/pull/8330",
"goldens": [
{
"comment": "Incorrect end time calculation using slotStartTime instead of slotEndTime",
"severity": "Medium"
},
{
"comment": "Using === for dayjs object comparison will always return false as it compares object references, not values. Use .isSame() method instead: dayjs(date.start).add(utcOffset, 'minutes').isSame(dayjs(date.end).add(utcOffset, minutes))",
"severity": "Medium"
}
]
},
{
"id": "grafana#103633",
"pr_url": "https://github.com/grafana/grafana/pull/103633",
"goldens": [
{
"comment": "The Check operation exhibits asymmetric cache trust logic: cached permission grants are trusted and returned immediately, but cached denials from the same permission cache are ignored, leading to a fresh database lookup. This allows stale cached grants to provide access to revoked resources, posing a security risk. ",
"severity": "High"
},
{
"comment": "The test comment says the cached permissions 'allow access', but the map stores false for dashboards:uid:dash1, so checkPermission will still treat this scope as not allowed.",
"severity": "Low"
}
]
},
{
"id": "grafana#106778",
"pr_url": "https://github.com/grafana/grafana/pull/106778",
"goldens": [
{
"comment": "The rendered GrafanaRuleListItem is missing the required key prop for React list items. This can cause rendering issues when the list order changes.",
"severity": "Medium"
},
{
"comment": "RuleActionsButtons is invoked with only promRule, but SilenceGrafanaRuleDrawer inside RuleActionsButtons still depends on a Grafana Ruler rule being present, so for Grafana rules coming from list views the 'Silence notifications' menu entry (now driven by Grafana Prom abilities) will toggle showSilenceDrawer without ever rendering the drawer. This means clicking 'Silence notifications' for these rules has no visible effect, even when abilities indicate silencing is allowed.",
"severity": "High"
}
]
},
{
"id": "grafana#107534",
"pr_url": "https://github.com/grafana/grafana/pull/107534",
"goldens": [
{
"comment": "The applyTemplateVariables method is called with request.filters as the third parameter, but this parameter is not used in the corresponding test setup.",
"severity": "Low"
}
]
},
{
"id": "grafana#76186",
"pr_url": "https://github.com/grafana/grafana/pull/76186",
"goldens": [
{
"comment": "The ContextualLoggerMiddleware methods (QueryData, CallResource, CheckHealth, CollectMetrics) panic when a nil request is received. This occurs because they directly access req.PluginContext (via the instrumentContext function) without first checking if req is nil. This is a regression, as previous middleware layers gracefully handled nil requests.",
"severity": "High"
},
{
"comment": "The traceID is no longer logged for plugin requests. During a refactoring, the tracing import and the logic to extract and add traceID from the context to log parameters were removed from the LoggerMiddleware. The newly introduced ContextualLoggerMiddleware does not add this information, resulting in missing traceID in plugin request logs and impacting debugging and request tracing capabilities.",
"severity": "Low"
}
]
},
{
"id": "grafana#79265",
"pr_url": "https://github.com/grafana/grafana/pull/79265",
"goldens": [
{
"comment": "Race condition: Multiple concurrent requests could pass the device count check simultaneously and create devices beyond the limit. Consider using a database transaction or lock.",
"severity": "High"
},
{
"comment": "Anonymous authentication now fails entirely if anonDeviceService.TagDevice returns ErrDeviceLimitReached. Previously, device tagging was asynchronous and non-blocking. This change prevents anonymous users from authenticating when the device limit is reached.",
"severity": "Medium"
},
{
"comment": "This call won’t compile: dbSession.Exec(args...) is given a []interface{} where the first element is the query, but Exec’s signature requires a first parameter of type string (not an interface{} splat).",
"severity": "Medium"
},
{
"comment": "Returning ErrDeviceLimitReached when no rows were updated is misleading; the device might not exist.",
"severity": "Low"
},
{
"comment": "Time window calculation inconsistency: Using device.UpdatedAt.UTC().Add(-anonymousDeviceExpiration) as the lower bound but device.UpdatedAt as the current time may not match the intended logic. Consider using time.Now().UTC() consistently.",
"severity": "Low"
}
]
},
{
"id": "grafana#80329",
"pr_url": "https://github.com/grafana/grafana/pull/80329",
"goldens": [
{
"comment": "The code uses Error log level for what appears to be debugging information. This will pollute error logs in production. Consider using Debug or Info level instead.",
"severity": "Low"
}
]
},
{
"id": "grafana#90045",
"pr_url": "https://github.com/grafana/grafana/pull/90045",
"goldens": [
{
"comment": "The context is being created with d.Log instead of the log variable that was initialized with additional context values (name, kind, method). This means those values won't be propagated to the logging context.",
"severity": "Medium"
},
{
"comment": "Bug: calling recordLegacyDuration when storage operation fails should be recordStorageDuration.",
"severity": "High"
},
{
"comment": "Inconsistency: using name instead of options.Kind for metrics recording differs from other methods.",
"severity": "Medium"
}
]
},
{
"id": "grafana#90939",
"pr_url": "https://github.com/grafana/grafana/pull/90939",
"goldens": [
{
"comment": "The GetWebAssets function implements an incomplete double-checked locking pattern for caching web assets. The function first checks if the cache is populated using a read lock (RLock), and if the cache is empty, it acquires a write lock to populate it. However, it fails to re-check whether the cache was populated by another goroutine while waiting to acquire the write lock.",
"severity": "Medium"
},
{
"comment": "In addition to the missing double-check, the function has a critical flaw in its error handling: it unconditionally assigns the fetch result to the cache (line 69: entryPointAssetsCache = result) regardless of whether the fetch succeeded or failed. When an error occurs during asset fetching, result is nil, and this nil value overwrites any previously valid cache entry.",
"severity": "High"
}
]
},
{
"id": "grafana#94942",
"pr_url": "https://github.com/grafana/grafana/pull/94942",
"goldens": [
{
"comment": "The enableSqlExpressions function has flawed logic that always returns false, effectively disabling SQL expressions unconditionally:",
"severity": "Critical"
},
{
"comment": "Several methods such as NewInMemoryDB().RunCommands and db.QueryFramesInto return 'not implemented'.",
"severity": "High"
}
]
},
{
"id": "grafana#97529",
"pr_url": "https://github.com/grafana/grafana/pull/97529",
"goldens": [
{
"comment": "A race condition in BuildIndex allows multiple goroutines to concurrently build the same expensive index for the same key. This is caused by moving the b.cacheMu lock from protecting the entire function to only protecting the final cache assignment. ",
"severity": "High"
},
{
"comment": "Calling s.search.TotalDocs() here may race with concurrent index creation: TotalDocs iterates b.cache without synchronization, and the event watcher goroutine started just above could trigger BuildIndex writes concurrently, potentially causing a concurrent map read/write panic.",
"severity": "High"
}
]
},
{
"id": "keycloak#32918",
"pr_url": "https://github.com/keycloak/keycloak/pull/32918",
"goldens": [
{
"comment": "Recursive caching call using session instead of delegate",
"severity": "Critical"
},
{
"comment": "Cleanup reference uses incorrect alias - should be 'idp-alias-' + i instead of 'alias'.",
"severity": "Medium"
}
]
},
{
"id": "keycloak#33832",
"pr_url": "https://github.com/keycloak/keycloak/pull/33832",
"goldens": [
{
"comment": "Returns wrong provider (default keystore instead of BouncyCastle)",
"severity": "High"
},
{
"comment": "Dead code exists where ASN1Encoder instances are created and written to, but their results are immediately discarded. The actual encoding is performed by new ASN1Encoder instances created in the subsequent return statement, rendering the earlier operations useless.",
"severity": "Low"
}
]
},
{
"id": "keycloak#36880",
"pr_url": "https://github.com/keycloak/keycloak/pull/36880",
"goldens": [
{
"comment": "Inconsistent feature flag bug causing orphaned permissions. The AdminPermissions event listener, responsible for cleaning up permissions upon role, client, or group removal, is incorrectly guarded by the ADMIN_FINE_GRAINED_AUTHZ (V1) feature flag. This is inconsistent with other methods in the class that use ADMIN_FINE_GRAINED_AUTHZ_V2. Consequently, if ADMIN_FINE_GRAINED_AUTHZ_V2 is enabled but V1 is not, the permission cleanup logic will not execute, leading to orphaned permission data. Cleanup should occur regardless of which fine-grained authorization version is enabled.",
"severity": "High"
},
{
"comment": "In hasPermission(ClientModel client, String scope), the resource lookup uses findByName(server, client.getId(), server.getId()), but AdminPermissionsSchema.getOrCreateResource creates per-client resources with the owner set to resourceServer.getClientId(), so this lookup will never find those resources and will always fall back to the 'all-clients' resource, effectively ignoring client-specific permissions.",
"severity": "High"
},
{
"comment": "In getClientsWithPermission(String scope), iterating resourceStore.findByType(server, AdminPermissionsSchema.CLIENTS_RESOURCE_TYPE) and returning resource.getName() will only ever consider the type-level 'Clients' resource (per-client resources have no type) and return its name, while AvailableRoleMappingResource#getRoleIdsWithPermissions expects actual client IDs to pass to realm.getClientById, which can lead to incorrect behavior or a null client and subsequent failures.",
"severity": "High"
}
]
},
{
"id": "keycloak#36882",
"pr_url": "https://github.com/keycloak/keycloak/pull/36882",
"goldens": [
{
"comment": "Incorrect method call for exit codes. The picocli.exit() method calls System.exit() directly, which is problematic:",
"severity": "Medium"
}
]
},
{
"id": "keycloak#37038",
"pr_url": "https://github.com/keycloak/keycloak/pull/37038",
"goldens": [
{
"comment": "Incorrect permission check in canManage() method",
"severity": "High"
},
{
"comment": "In getGroupIdsWithViewPermission, hasPermission is called with groupResource.getId() and the same groupResource.getId() is added to granted, but hasPermission resolves resources by name (treating the argument as a group id) and the GroupPermissionEvaluator contract says this method returns group IDs that are later used as UserModel.GROUPS and in getUsersCount group filters. This mismatch means per-group VIEW_MEMBERS/MANAGE_MEMBERS permissions may not yield the expected group IDs for filtering and counts, and evaluation may effectively only look at the type-level 'all-groups' resource; consider revisiting whether this should operate on the underlying group ids (resource names) instead so it aligns with the JPA queries and the interface contract.",
"severity": "High"
}
]
},
{
"id": "keycloak#37429",
"pr_url": "https://github.com/keycloak/keycloak/pull/37429",
"goldens": [
{
"comment": "The translation is in Italian instead of Lithuanian. This should be translated to Lithuanian to match the file's locale (messages_lt.properties).",
"severity": "Medium"
},
{
"comment": "The totpStep1 value uses Traditional Chinese terms in the Simplified Chinese file (zh_CN), which is likely incorrect for this locale. Please verify the locale‑appropriate translation.",
"severity": "Medium"
},
{
"comment": "The anchor sanitization logic has a potential issue where it consumes English matcher groups without proper validation. If the translated text has more anchor tags than the English text, this could lead to incorrect validation results.",
"severity": "Low"
},
{
"comment": "The method name 'santizeAnchors' should be 'sanitizeAnchors' (missing 'i').",
"severity": "Low"
}
]
},
{
"id": "keycloak#37634",
"pr_url": "https://github.com/keycloak/keycloak/pull/37634",
"goldens": [
{
"comment": "Wrong parameter in null check (grantType vs. rawTokenId)",
"severity": "Critical"
},
{
"comment": "In isAccessTokenId, the substring for the grant shortcut and the equality check look inverted: the grant shortcut occupies indices 4–5 (substring(4,6)), and a match should return true (combined with UUID check), not false.",
"severity": "High"
},
{
"comment": "Javadoc mentions \"usually like 3-letters shortcut\" but some implementations use 2-letter shortcuts (\"ac\", \"cc\", \"rt\", \"te\", \"pc\", \"ci\", \"ro\"). Consider updating documentation to reflect actual usage pattern.",
"severity": "Low"
},
{
"comment": " Catching generic RuntimeException is too broad. The implementation throws IllegalArgumentException specifically - catch that instead for more precise testing.",
"severity": "Low"
}
]
},
{
"id": "keycloak#38446",
"pr_url": "https://github.com/keycloak/keycloak/pull/38446",
"goldens": [
{
"comment": "Unsafe raw List deserialization without type safety. Calling Optional.get() directly on the Optional returned by RecoveryAuthnCodesUtils.getCredential(user) without checking isPresent() can lead to a NoSuchElementException if the Optional is empty.",
"severity": "Medium"
},
{
"comment": "After creating the RecoveryAuthnCodesCredentialModel, consider setting its id from the stored credential (e.g., myUser.recoveryCodes.getId()); otherwise getId() will be null and downstream removal by id (e.g., removeStoredCredentialById in the authenticator flow) may not work.",
"severity": "Low"
}
]
},
{
"id": "keycloak#40940",
"pr_url": "https://github.com/keycloak/keycloak/pull/40940",
"goldens": [
{
"comment": "Returning null from getSubGroupsCount() violates the GroupModel contract (Javadoc says it never returns null) and may lead to NPEs in callers that expect a non-null count.",
"severity": "Critical"
},
{
"comment": "The reader thread isn’t waited for; flipping deletedAll to true and asserting immediately can race and miss exceptions added just after the flag change, making this test flaky.",
"severity": "Medium"
}
]
},
{
"id": "keycloak#41249",
"pr_url": "https://github.com/keycloak/keycloak/pull/41249",
"goldens": [
{
"comment": "ConditionalPasskeysEnabled() called without UserModel parameter",
"severity": "Medium"
},
{
"comment": "With isConditionalPasskeysEnabled(UserModel user) requiring user != null, authenticate(...) will not call webauthnAuth.fillContextForm(context) on the initial login page where context.getUser() is still null, so conditional passkey UI will not be set up for first-time passkey login. Consider whether this should also be enabled when no user has been selected yet so ID-less passkey authentication on the initial login form continues to work.",
"severity": "Medium"
}
]
},
{
"id": "sentry#67876",
"pr_url": "https://github.com/getsentry/sentry/pull/67876",
"goldens": [
{
"comment": "Null reference if github_authenticated_user state is missing",
"severity": "Medium"
},
{
"comment": "OAuth state uses pipeline.signature (static) instead of a per-request random value",
"severity": "Medium"
},
{
"comment": "The code attempts to access integration.metadata[sender][login] without checking for the existence of the sender key. This causes a KeyError for integrations where the sender metadata was not set during creation",
"severity": "High"
}
]
},
{
"id": "sentry#77754",
"pr_url": "https://github.com/getsentry/sentry/pull/77754",
"goldens": [
{
"comment": "Shared mutable default in dataclass timestamp",
"severity": "Medium"
},
{
"comment": "The method name has a typo: test_from_dict_inalid_data should be test_from_dict_invalid_data.",
"severity": "Low"
},
{
"comment": "Method name says 'empty_array' but tests empty dict - consider renaming to 'test_from_dict_empty_dict' for clarity.",
"severity": "Low"
},
{
"comment": "to_dict() returns a datetime for queued; if this dict is passed in task kwargs (e.g., via apply_async), JSON serialization may fail depending on the serializer, which can cause enqueue errors.",
"severity": "Medium"
}
]
},
{
"id": "sentry#80168",
"pr_url": "https://github.com/getsentry/sentry/pull/80168",
"goldens": [
{
"comment": "MetricAlertDetectorHandler inherits from StatefulDetectorHandler but only contains pass, failing to implement its required abstract methods: counter_names (property), get_dedupe_value(), get_group_key_values(), and build_occurrence_and_event_data(). This will cause a TypeError at runtime when the class is instantiated.",
"severity": "High"
},
{
"comment": "Docstring says this returns a list of DetectorEvaluationResult, but the method now returns a dict keyed by DetectorGroupKey. Consider updating the docstring to match the new return type.",
"severity": "Low"
}
]
},
{
"id": "sentry#80528",
"pr_url": "https://github.com/getsentry/sentry/pull/80528",
"goldens": [
{
"comment": "The function modifies the config variable to include display values but then returns the original monitor.config instead of the modified version.",
"severity": "High"
},
{
"comment": "The code fetches MonitorCheckIn objects by ID when the required data already exists in previous_checkins. This creates an unnecessary database query.",
"severity": "Low"
}
]
},
{
"id": "sentry#92393",
"pr_url": "https://github.com/getsentry/sentry/pull/92393",
"goldens": [
{
"comment": "OptimizedCursorPaginator negative-offset branch slices QuerySet with a negative start index",
"severity": "Critical"
},
{
"comment": "BasePaginator negative-offset branch slices QuerySet with a negative start index",
"severity": "High"
},
{
"comment": "OptimizedCursorPaginator.get_item_key uses floor/ceil on a datetime key (order_by='-datetime'), causing TypeError.",
"severity": "High"
}
]
},
{
"id": "sentry#93824",
"pr_url": "https://github.com/getsentry/sentry/pull/93824",
"goldens": [
{
"comment": "Inconsistent metric tagging with 'shard' and 'shards'",
"severity": "Medium"
},
{
"comment": "Fixed sleep in tests can be flaky; wait on condition instead",
"severity": "Low"
},
{
"comment": "Because flusher processes are created via multiprocessing.get_context('spawn').Process, they are instances of multiprocessing.context.SpawnProcess, which on POSIX is not a subclass of multiprocessing.Process, so this isinstance check will always be false and hung processes won't be killed here.",
"severity": "High"
},
{
"comment": "Sleep in test_consumer.py won’t actually wait because time.sleep was monkeypatched above; consider restoring sleep or using a different sync to ensure the flusher has time to process.",
"severity": "Medium"
},
{
"comment": "Breaking out of the loop when the deadline has elapsed can skip terminating remaining flusher processes, potentially leaving them running after shutdown; consider ensuring termination is attempted even if the deadline is exceeded.",
"severity": "Medium"
}
]
},
{
"id": "sentry#94376",
"pr_url": "https://github.com/getsentry/sentry/pull/94376",
"goldens": [
{
"comment": "sample_rate = 0.0 is falsy and skipped",
"severity": "Low"
},
{
"comment": "Using Python’s built-in hash() to build cache keys is non-deterministic across processes (hash randomization), so keys won’t match across workers and invalidate_upsampling_cache may fail to delete them. Use a deterministic serialization of project_ids for the cache key.",
"severity": "Low"
},
{
"comment": "The upsampling eligibility check passes the outer dataset instead of the actual dataset used by scoped_dataset. In paths where the query ultimately runs against discover (e.g., dashboard split) while the original dataset is metrics, upsampling may be skipped even when all projects are allowlisted.",
"severity": "Medium"
}
]
},
{
"id": "sentry#95633",
"pr_url": "https://github.com/getsentry/sentry/pull/95633",
"goldens": [
{
"comment": "The queue.shutdown() method with 'immediate=False' parameter may not exist in the standard Python queue module. This could cause AttributeError at runtime. Verify the correct API or implement a custom shutdown mechanism.",
"severity": "High"
},
{
"comment": "The magic number 50 for max_wait is used repeatedly throughout the tests. Consider extracting this as a named constant to improve maintainability.",
"severity": "Low"
},
{
"comment": "The test test_thread_queue_parallel_error_handling has a docstring that doesn't match the test implementation.",
"severity": "Low"
}
]
}
]
+199
View File
@@ -0,0 +1,199 @@
// Package prbench runs the PR reviewer benchmark: the Martian Code-Review-Bench
// problems, the production review pipeline, and a judge model, all on the
// providers and model aliases the instance already configures.
package prbench
import (
"context"
_ "embed"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log/slog"
"os"
"os/signal"
"path/filepath"
"slices"
"strings"
"syscall"
"time"
"github.com/samcharles93/archie-core/internal/agentexec"
"github.com/samcharles93/archie-core/internal/agentexec/modelloop"
"github.com/samcharles93/archie-core/internal/app/servicekit"
"github.com/samcharles93/archie-core/internal/buildinfo"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/workflow/prreview/bench"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
"github.com/samcharles93/archie-core/internal/infrastructure/prsource"
)
// acceptanceRecall is the PRD's golden micro-recall bar for a full run.
const acceptanceRecall = 0.70
// martian holds the 38 runnable problems of the Martian Code-Review-Bench
// offline set: those whose pull request still exists upstream.
//
//go:embed martian.json
var martian []byte
// Problems returns the benchmark problems, optionally narrowed to ids.
func Problems(ids []string) ([]bench.Problem, error) {
var all []bench.Problem
if err := json.Unmarshal(martian, &all); err != nil {
return nil, fmt.Errorf("decode benchmark problems: %w", err)
}
if len(ids) == 0 {
return all, nil
}
var out []bench.Problem
for _, id := range ids {
i := slices.IndexFunc(all, func(p bench.Problem) bool { return p.ID == id })
if i < 0 {
return nil, fmt.Errorf("no benchmark problem %q", id)
}
out = append(out, all[i])
}
return out, nil
}
// Options configures one benchmark run. Model and Judge each name a model
// alias of the config or a provider/model ref; empty means the "default" alias.
type Options struct {
Config string
Model string
Judge string
OutDir string
Problems []string
Concurrency int
}
// Run reviews and judges the selected problems, writes the report into
// Options.OutDir, and prints it to w.
func Run(ctx context.Context, opts Options, w io.Writer) (bench.Summary, error) {
problems, err := Problems(opts.Problems)
if err != nil {
return bench.Summary{}, err
}
doc, err := configuration.New(nil).File(opts.Config)
if err != nil {
return bench.Summary{}, err
}
cfg := doc.Config
if err := servicekit.ResolveProviders(&cfg, slog.Default()); err != nil {
return bench.Summary{}, err
}
reviewRef, err := resolveRef(cfg.Models, opts.Model)
if err != nil {
return bench.Summary{}, err
}
judgeRef, err := resolveRef(cfg.Models, opts.Judge)
if err != nil {
return bench.Summary{}, err
}
rt := modelloop.NewRuntime(agentexec.ProvidersFromConfig(cfg.Providers), cfg.ModelLimits)
if rt == nil {
return bench.Summary{}, fmt.Errorf("%s configures no providers", opts.Config)
}
// The pipeline resolves its model through the default alias.
cfg.Models = map[string]string{config.DefaultModelAlias: reviewRef}
cfg.Review.ApproveBeforePost = false
cfg.Review.PrecisionGate = false
reviewer := &liveReviewer{cfg: cfg, agent: modelloop.NewLoopRunner(rt, slog.Default()), source: prsource.New(newPublicGitHub())}
judge := &modelJudge{runtime: rt, modelRef: judgeRef}
results := bench.Run(ctx, problems, reviewer, judge, opts.Concurrency)
summary := bench.Summarize(results)
report := render(results, summary, reviewRef, judgeRef, len(opts.Problems) == 0)
path, err := writeReport(opts.OutDir, report)
if err != nil {
return summary, err
}
fmt.Fprint(w, report)
fmt.Fprintf(w, "\nreport written to %s\n", path)
if summary.Failed != 0 {
return summary, fmt.Errorf("%d benchmark problem(s) failed; results are incomplete", summary.Failed)
}
return summary, nil
}
// Main is the `archied prbench` subcommand.
func Main(args []string, stdout, stderr io.Writer) int {
var opts Options
var problems string
flags := flag.NewFlagSet("archied prbench", flag.ContinueOnError)
flags.SetOutput(stderr)
flags.StringVar(&opts.Config, "config", configuration.DefaultConfigPath(), "config file whose providers and model aliases serve the run")
flags.StringVar(&opts.Model, "model", "", "model alias or provider/model for the reviewer (default: the default alias)")
flags.StringVar(&opts.Judge, "judge-model", "", "model alias or provider/model for the judge (default: the default alias; use a different model from the reviewer's for an independent judge)")
flags.StringVar(&opts.OutDir, "out", "docs/benchmarks", "directory the report is written to")
flags.StringVar(&problems, "problems", "", "comma-separated problem ids for a partial run (default: all 38)")
flags.IntVar(&opts.Concurrency, "concurrency", 4, "problems reviewed at once")
if err := flags.Parse(args); err != nil {
if errors.Is(err, flag.ErrHelp) {
return 0
}
return 2
}
if problems != "" {
opts.Problems = strings.Split(problems, ",")
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if _, err := Run(ctx, opts, stdout); err != nil {
fmt.Fprintln(stderr, "archied prbench:", err)
return 1
}
return 0
}
// resolveRef accepts a provider/model ref as is and otherwise looks the alias up.
func resolveRef(aliases map[string]string, v string) (string, error) {
v = strings.TrimSpace(v)
if strings.Contains(v, "/") {
return v, nil
}
return config.ResolveModel(aliases, v, config.PurposeAgent)
}
func render(results []bench.Result, s bench.Summary, reviewRef, judgeRef string, full bool) string {
var b strings.Builder
scope, verdict := "partial run (not the acceptance run)", ""
if full {
scope = "full run"
verdict = fmt.Sprintf("\nAcceptance (recall >= %.2f): %s\n", acceptanceRecall, passFail(s.Failed == 0 && s.Recall >= acceptanceRecall))
}
fmt.Fprintf(&b, "# PR review benchmark\n\nDate: %s\nArchie version: %s\nReview model: %s\nJudge model: %s\nScope: %s\n\n",
time.Now().UTC().Format("2006-01-02"), buildinfo.Version, reviewRef, judgeRef, scope)
fmt.Fprintf(&b, "Problems %d (failed %d) recall %.3f (%d/%d) golden-only precision %.3f (%d/%d)\n%s\n",
s.Problems, s.Failed, s.Recall, s.Hits, s.Goldens, s.Precision, s.Matched, s.Comments, verdict)
b.WriteString("| Problem | Recall | Comments | Notes |\n| --- | --- | --- | --- |\n")
for _, r := range results {
recall, notes := fmt.Sprintf("%d/%d", r.Hits(), len(r.Problem.Goldens)), ""
switch {
case r.Err != "":
recall, notes = "-", "failed: "+strings.ReplaceAll(r.Err, "|", "/")
case len(r.SkippedPhases) != 0:
notes = "skipped phases: " + strings.Join(r.SkippedPhases, ", ")
}
fmt.Fprintf(&b, "| %s | %s | %d | %s |\n", r.Problem.ID, recall, len(r.Comments), notes)
}
return b.String()
}
func passFail(ok bool) string {
if ok {
return "PASS"
}
return "FAIL"
}
func writeReport(dir, report string) (string, error) {
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", err
}
path := filepath.Join(dir, "pr-review-"+time.Now().UTC().Format("20060102-150405")+".md")
return path, os.WriteFile(path, []byte(report), 0o644)
}