← Back to Pull requests

perf(expand): prefetch descendant grants to eliminate per-principal SQL queries #863

Closed
unknown closed this pull request without merging on Jun 04, 2026 01:08 UTC
View on GitHub
unknown unknown commented on May 24, 2026 02:54 UTC
Author

Summary

  • Replace O(N) per-principal ListGrantsForEntitlement SQL queries in runAction with a single bulk pre-fetch into an in-memory map

  • For a large tenant (180K users, 139K groups, 72 GB c1z), a single expansion action was taking 38 minutes — 180K individual SQLite queries through pure-Go modernc.org/sqlite

  • After: one paginated scan of the descendant entitlement + O(1) map lookups per source grant → expected seconds instead of minutes
  • Problem

    Profile evidence from be-temporal-sync prod (1h aggregate):

  • 100% of CPU in dotc1z.listGrantsGeneric → ListGrantsForEntitlement → database/sql.Rows.Next → modernc.org/sqlite._sqlite3VdbeExec

  • Block profile: 0 blocked samples — CPU-bound, not I/O-bound

  • 277 pending grant-expansion actions × ~38 min each = days to complete one sync
  • The inner loop in runAction (previously lines 278-350) called ListGrantsForEntitlement with a specific PrincipalId for each source grant. Even though the compound index (entitlement_id, principal_resource_type_id, principal_resource_id) makes each a point lookup returning 0-1 rows, the per-query overhead in pure-Go SQLite (~0.1-1ms per call) compounds to 38 minutes at 180K source grants.

    Fix

    Pre-fetch ALL grants on the descendant entitlement into map[principalKey][]*v2.Grant before entering the source grants loop. Each source grant then does a map lookup (O(1)) instead of a SQL query.

    The pre-fetch is per-runAction call, not cached across actions. This ensures correctness in diamond graphs: if action A→C creates grants that action B→C must see, the B→C call does a fresh pre-fetch that includes the writes from A→C.

    Memory tradeoff

    For the worst case (descendant with 180K grants × ~2KB each = ~360MB peak), this is within budget for worker pods (32GB RAM). Most entitlements are much smaller.

    Test plan

  • go test ./pkg/sync/expand/... — all pass (including diamond graph, multi-level, mixed directness, cycle tests)

  • go test ./pkg/sync/... — all pass

  • go test -short ./pkg/dotc1z/... — all pass

  • go test -bench=BenchmarkExpand ./pkg/sync/expand/... — 70% improvement
  • Benchmark

                                  main (baseline)      branch (prefetch)     delta
    BenchmarkExpandSmall            89.0s                26.4s              -70.3%
    BenchmarkExpandSmallMedium     113.5s                34.4s              -69.7%
    allocs/op (Small)              299M                 129M                -57.0%
    B/op (Small)                  14.8 GB               7.2 GB             -51.4%
    

    🤖 Generated with Claude Code

    Diff: 328 lines (+246 / -82) across 4 files Reviewer: arreyder Review duration: 15733m
    All Vouch review confidence checks passed
    Residual risk 0.18 = Change Risk (0.42) × (1 − Review Confidence (0.57)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.42 · 328 lines diff across 4 files
    0.42
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    56%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.347
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #863"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 56.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 42.1% (MEDIUM) · Higher = larger blast radius
    42.1%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 56.8% · Lower = rushed or shallow review
    56.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 18.2% · Safe to merge
    18.2%