← Back to Pull requests

[2/N] [History Server Beta] [Feat] LRU cache #4796

Closed
unknown closed this pull request without merging on Jun 18, 2026 18:50 UTC
View on GitHub
unknown unknown commented on May 02, 2026 05:41 UTC
Author

Why are these changes needed?

Alpha Problems

Unbounded memory growth: The parsed state lived in the stateful EventHandler's in-memory maps through the process lifetime.

Beta Strategy

In this PR, we use per-call (stateless) EventHandler and add a per-replica, count-based LRU cache. So, the memory usage is bounded by O(#cached_sessions x max_session_snapshot_size).

Overview

System Architecture

                        ┌──────────────────┐
                        │   Dashboard UI   │ ◄── user browser
                        └────────┬─────────┘
                                 │ HTTP
                                 ▼
                        ┌──────────────────┐
                        │   Load Balancer  │
                        └────────┬─────────┘
                                 │
                                 ▼
 ┌── Ray Cluster ───────┐  ┌── History Server (replicas, single binary) ──────────────┐
 │                      │  │                                                          │
 │  Head pod            │  │   HTTP Router                                            │
 │  ray-head+collector  │  │   ├─► /enter_cluster        (blocking on dead session)   │
 │        │             │  │   │     │                                                │
 │        │             │  │   │     ▼                                                │
 │        │             │  │   │  SessionLoader  ── singleflight (coalesce same key)  │
 │        │ raw         │  │   │     │  cache miss                                    │
 │        │ events      │  │   │     ▼                                                │
 │        │ (PUT)       │  │   │  SessionProcessor                                    │    ┌──────┐
 │        │             │  │   │     ├─ isDead?  ──── k8s GET RayCluster ─────────────────►│ K8s  │
 │        │             │  │   │     │   (NotFound ⇒ dead; CR exists ⇒ live)          │    │ API  │
 │        │             │  │   │     │                                                │    └──────┘
 │        │             │  │   │     ├─ h := NewEventHandler(reader)  ★per-call       │
 │        │             │  │   │     │     h.ProcessSingleSession()                   │
 │        │             │  │   │     │     h.BuildSnapshot()                          │
 │        │             │  │   │     │     (h out of scope ⇒ GC, maps freed)          │
 │        │             │  │   │     ▼                                                │
 │        │             │  │   │  putSnapshot(key, snap)                              │
 │        │             │  │   │     ▼                                                │
 │        │             │  │   │  ┌───────────────────────────┐                       │
 │        │             │  │   │  │ LRU[key]→*SessionSnapshot │ cap =                 │
 │        │             │  │   │  │  (count-bounded)          │ --session-cache-size  │
 │        │             │  │   │  └────────────┬──────────────┘ (default 100)         │
 │        │             │  │   │               │ GetSnapshot(key) → per-request view  │
 │        │             │  │   └─► /api/v0/*  ◄─┘  (read path: tasks/actors/...)      │
 │        ▼             │  └──────────────────────────────────────────────────────────┘
 └────────┼─────────────┘                              ▲
          │                                            │ List + GET event files
 ┌────────▼────────────────────────────────────────────┴─────────────────────┐
 │  Object Storage  (S3 / GCS / Azure / Aliyun OSS)                            │
 │                                                                             │
 │  {rootDir}/{cluster}_{ns}/{session}/                                        │
 │    node_events/   job_events/   logs/   fetched_endpoints/                  │
 └─────────────────────────────────────────────────────────────────────────────┘

Request Data Flow

sequenceDiagram
  actor User as Winner
  actor User2 as Follower
  participant HS as HS handler
  participant Loader as SessionLoader (LRU + singleflight)
  participant Proc as SessionProcessor
  participant K8s as K8s API
  participant S3 as Object Storage
  participant EH as per-call EventHandler (h)
  participant LRU as LRU cache

  User->>HS: GET /enter_cluster (cold, dead session)
  User2->>HS: GET /enter_cluster (concurrent, same session)
  HS->>Loader: LoadSession (winner)
  HS->>Loader: LoadSession (follower)
  Loader->>LRU: cache.Get(key) → miss
  Note over Loader: same singleflight key →<br/>follower joins winner's DoChan group

  Loader->>Proc: ProcessSession(loadCtx)
  Note over Proc,Loader: loadCtx = WithTimeout(serverCtx, processTimeout)<br/>NOT reqCtx — winner disconnect cannot cancel<br/>work the follower still depends on

  Proc->>K8s: Get RayCluster
  alt CR NotFound
    K8s-->>Proc: NotFound → dead
  else CR exists
    K8s-->>Proc: RayCluster found → live
    Note over Proc: return SessionStatusLive (skip parse)<br/>known limit: stale session of live CR<br/>misclassified as live
  end

  Proc->>EH: h := NewEventHandler(reader)
  Proc->>S3: List + GET event files
  Proc->>EH: h.ProcessSingleSession (writes h's Tasks/Actors/Jobs/Nodes/LogEvents)
  Proc->>EH: h.BuildSnapshot (deep copy → *SessionSnapshot)
  Note over EH: h has no external ref →<br/>GC-eligible after return, 5 maps freed
  Proc-->>Loader: SessionStatusProcessed, *snapshot, nil

  Loader->>LRU: putSnapshot(key, snap)
  Loader-->>HS: nil (winner)
  Loader-->>HS: nil (follower, shared singleflight result)
  HS-->>User: 200 OK
  HS-->>User2: 200 OK

  Note over User,LRU: subsequent /api/v0/* read via GetSnapshot(key)<br/>→ per-request view (shallow struct copy + fresh Tasks slice)<br/>repeat /enter_cluster hits LRU fast-path (no re-parse)<br/>on cache miss/evicted: 503 "reload via /enter_cluster"

Change Summary

1. Per-Call EventHandler + LRU Cache

The original EventHandler is stateful, and its ingestion maps grow unbounded, risking OOM. This PR creates an EventHandler per call on the cold path, so the raw maps become GC-eligible once the snapshot is built. An LRU cache then bounds the number of processed snapshots kept in memory.

Per-call EventHandler in a nutshell:

func ProcessSession() *SessionSnapshot {
    h := NewEventHandler(reader)
    h.ProcessSingleSession()   // writes 5 ingestion maps
    snap := h.BuildSnapshot()  // deep-copies into the snapshot
    return snap                // raw maps are now GC-eligible
}

2. Separation of Concerns: eventserver vs. historyserver (SessionSnapshot as SSOT)

Previously, the history server (router) read directly from the in-memory maps, tightly coupling it to the event server (which had to expose multiple getters). This PR decouples them so each side owns a single concern:

  • eventserver (ingestion): Parse raw events and build the snapshot

  • historyserver (presentation): Read the snapshot and format it for the Ray Dashboard API
  • The only contract between them is a frozen, read-only SessionSnapshot, acting as the single source of truth: one *SessionSnapshot is shared across concurrent handlers, and each handler receives its own per-request view.

    3. Remove Dead Code

    This PR removes GetTaskByID, GetActors, GetActorByID, GetJobByJobID, and GetNodeByNodeID for two reasons:

    1. With the per-call handler, each handler instance lives entirely within ProcessSession (i.e., there are no external references to it).
    2. They duplicate five existing unexported getters with identical functionality, making them redundant.

    Related issue number

    Part of https://github.com/ray-project/kuberay/issues/4709.

    How to test

    echo "=== Build ===" && \
    go build -o /tmp/hs-bin ./cmd/historyserver/ && rm -f /tmp/hs-bin && echo "BUILD OK"
    
    echo && echo "=== Vet ===" && go vet ./... && echo "VET OK"
    
    echo && echo "=== Tests in packages touched by this PR (must PASS) ===" && \
    go test -race -cover \
      ./pkg/historyserver/... \
      ./pkg/eventserver/... \
      ./pkg/utils/...
    

    Expected Output

    === Build ===
    BUILD OK
    
    === Vet ===
    VET OK
    
    === Tests in packages touched by this PR (must PASS) ===
    ok  	github.com/ray-project/kuberay/historyserver/pkg/historyserver	3.380s	coverage: 9.8% of statements
    ok  	github.com/ray-project/kuberay/historyserver/pkg/eventserver	1.652s	coverage: 57.8% of statements
    ok  	github.com/ray-project/kuberay/historyserver/pkg/eventserver/types	2.277s	coverage: 29.7% of statements
    ok  	github.com/ray-project/kuberay/historyserver/pkg/utils	3.205s	coverage: 4.9% of statements
    

    Checks

  • I've made sure the tests are passing.

  • Testing Strategy

  • - [x] Unit tests
    - [x] Manual tests
    - [ ] This PR is not tested :(

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: JiangJiaWei1103 Review duration: 68469m
    All Vouch review confidence checks passed
    Residual risk 0.22 = Change Risk (0.52) × (1 − Review Confidence (0.57)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    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.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #4796"
    general weight: 0.35
    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: 52% (MEDIUM) · Higher = larger blast radius
    52%
    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: 22.5% · Safe to merge
    22.5%