← Back to Pull requests

[1/N] [History Server Beta] [Feat] Lazy loading #4795

Closed
unknown closed this pull request without merging on May 22, 2026 14:16 UTC
View on GitHub
unknown unknown commented on May 01, 2026 12:27 UTC
Author

Why are these changes needed?

Alpha Problems

  • Long data warm-up window: Dead sessions were not fully available until startup processing finishes

  • Duplicated processing: EventHandler re-parsed all raw events every hour (bounded by O(#sessions))
  • Process restart wiped all in-memory maps and the next startup repeated the entire warm-up cycle.

    Beta Strategy

    In this PR, we remove startup processing/ticker and introduce lazy loading to process raw events on user requests and records processed dead sessions in in-memory maps (inherited from alpha).

    [!NOTE]

    The unbounded memory growth problem will be solved in the next PR via caching and the third PR's dead code cleanup.

    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) │
    │ │ │ │ │ │
    │ │ │ │ ▼ │
    │ │ │ │ SessionLoader │
    │ │ │ │ (singleflight + loaded set) │
    │ │ raw │ │ │ │
    │ │ events │ │ ┌─┴──────────┐ │
    │ │ (PUT) │ │ ▼ ▼ │
    │ ▼ │ │ EventHandler SessionProcessor ── isDead? (RayCluster) ┼──┐
    └───────────┼───────────┘ │ in-mem maps (parse only) HTTPLiveSessionResolver │
    │ │ (Tasks/ │ │ ▼
    │ │ Actors/ │ ProcessSingleSession │ ┌─────────┐
    │ │ Jobs/ │ (writes events into maps) │ │ K8s │
    │ │ Nodes/ │ │ │ API │
    │ │ LogEvents) │ │ └─────────┘
    │ │ ▲ │ │
    │ │ └───────────┘ │
    │ └─────────────────────────────────────────────────┘
    │ ▲
    ▼ │ raw events (GET)
    ┌──────────────────────────────────────────────────────────┐
    │ Object Storage (S3 / GCS / Azure / Aliyun OSS) │
    │ │
    │ {rootDir}/{cluster}_{ns}/{session}/ │
    │ node_events/, job_events/, logs/, fetched_endpoints/ │
    └──────────────────────────────────────────────────────────┘

    
    #### Request Data Flow
    
    
    mermaid
    sequenceDiagram
    actor User as Winner
    actor User2 as Follower
    participant HS as HS handler
    participant Loader as SessionLoader (singleflight + loaded set)
    participant Proc as SessionProcessor
    participant Resolver as HTTPLiveSessionResolver
    participant K8s as K8s API
    participant Dash as Ray Dashboard
    participant S3 as Object Storage
    participant EH as EventHandler maps

    User->>HS: GET /enter_cluster (cold, dead session)
    User2->>HS: GET /enter_cluster (concurrent, same session)
    HS->>Loader: LoadSession (winner)
    HS->>Loader: LoadSession (follower)
    Note over Loader: same singleflight key →<br/>follower joins winner's group
    Loader->>Loader: loaded set check → not found
    Loader->>Proc: ProcessSession(serverCtx)
    Note over Proc,Loader: serverCtx (NOT reqCtx) —<br/>winner disconnect cannot cancel<br/>work followers still depend on

    Proc->>K8s: Get RayCluster
    alt CR NotFound
    K8s-->>Proc: NotFound → dead
    else CR exists
    K8s-->>Proc: RayCluster (Status.Head.ServiceName set)
    Proc->>Resolver: FetchSessionName(ns, headSvcName)
    Resolver->>Dash: GET /api/version
    Dash-->>Resolver: { session_name: "<live_session>" }
    Resolver-->>Proc: "<live_session>"
    Note over Proc: queried != live → dead
    end

    Proc->>S3: List + GET event files
    Proc->>EH: ProcessSingleSession (writes into Tasks/Actors/Jobs/Nodes/LogEvents)
    Proc-->>Loader: SessionStatusProcessed, nil
    Loader->>Loader: mark session in loaded set
    Loader-->>HS: nil (winner)
    Loader-->>HS: nil (follower, shared result)
    HS-->>User: 200 OK
    HS-->>User2: 200 OK

    Note over User,EH: subsequent /api/v0/* calls read from EventHandler maps directly<br/>repeat /enter_cluster returns immediately via loaded set fast-path<br/>(no re-parse on this replica)

    
    ### Components and Design Decisions
    
    #### `SessionProcessor`
    
    Determine session liveness by comparing the queried session name against the one currently running on the live RayCluster; execute `ProcessSingleSession` for dead sessions.
    
    **Design Decisions**
    Probe-based comparison replaces the old timestamp comparison, which could not distinguish multiple sessions in the same CR (head-pod restarts) and had a time zone alignment issue in `ParseSessionTimestamp`.
    
    **Trade-off:** One HTTP round-trip per cold load; hot path unaffected by `loaded` cache.
    
    #### `SessionLoader`
    
    Gate `/enter_cluster` until session events are in memory.
    
    **Design Decisions**
    - `singleflight` per session key prevents redundant storage scans when concurrent callers race on the same dead session
    - 2-min per-load timeout prevents goroutine leak
    
    **Trade-off:** First-request cold-load latency; subsequent hits are O(1).
    
    #### `HTTPLiveSessionResolver`
    
    Call `/api/version` on the Ray dashboard and return the cluster's current `session_name`.
    
    **Design Decisions**
    Fresh implementation rather than reusing `RayDashboardClient` since the existing interface lacked `GetVersion()` and its factory required `manager.Manager`, which is unavailable in HS.
    
    **Trade-off:** URL-construction logic is duplicated with `redirectRequest`.
    
    #### `ProcessSingleSession`
    
    Process ray-events and log-events into in-memory maps for one session.
    
    **Design Decisions**
    ray-events failure blocks the `loaded` marker; log-events failure is logged but does not block. log-events feeds only `/events`, so coupling both error paths would let a transient log outage block all other dead-session APIs.
    
    **Trade-off:** Silent data loss on `/events` if log-events fails; no retry until HS restart.
    
    #### `/enter_cluster`
    
    Route requests to `SessionLoader` (dead session) or dashboard proxy (live session).
    
    **Design Decisions**
    Session-name validation lives at the router level rather than inside `isDead`, following the KubeRay caller-validates convention.
    
    **Trade-off:** —
    
    ## Related issue number
    
    Part of https://github.com/ray-project/kuberay/issues/4709.
    
    ## How to test
    
    
    bash
    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"

    Directly affected packages


    echo && echo "=== Tests in packages touched by this PR (must PASS) ===" && \
    go test -race -cover ./pkg/historyserver/...

    Verbose run of NEW tests added by this PR


    echo && echo "=== New tests (verbose) ===" && \
    go test -race -v -run "TestEnsure_PipelineError" ./pkg/historyserver/

    echo && echo "=== eventserver tests (must PASS) ===" && \
    go test -race ./pkg/eventserver/types/... && \
    go test -race ./pkg/eventserver/ 2>&1 | tail -5 || true
    ``

    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: 30348m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). 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%
    60%
    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 #4795"
    general weight: 0.35
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% 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: 60.5% · Lower = rushed or shallow review
    60.5%
    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: 20.5% · Safe to merge
    20.5%