← Back to Pull requests

[WIP] [POC] [History Server] [Beta] Scalable v2 architecture: Lazy loading with blocking enter_cluster + snapshot LRU #4765

Closed
unknown closed this pull request without merging on May 07, 2026 02:52 UTC
View on GitHub
unknown unknown commented on Apr 24, 2026 10:36 UTC
Author

Why are these changes needed?

Large amount of code is ported https://github.com/ray-project/kuberay/pull/4755, thanks!

Alpha Problems

  • Cold start latency: A cold History Server pod replayed all raw events in S3 before serving the first request

  • Duplicated processing: EventHandler re-read and re-process all raw events periodically (each tick bound to O(all sessions ever))

  • Memory bound: Each History Server pod held ever-growing in-memory maps

  • Data inconsistency: Scaling horizontally yielded inconsistent views between pods
  • Beta Strategy

  • Lazy loading (on-demand processing): Build session snapshot on user request (hit the blocking /enter_cluster endpoint); no ticker, no active scanning

  • Snapshot LRU cache: Prime a freshly-built SessionSnapshot into the LRU for later calls, falling back to on-demand processing on a cache miss
  • [!NOTE]

    Whether to write SessionSnapshot back to object storage is still an open question (tradeoff: processing latency vs extra storage).

    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)             │
       │           │           │  │     │                                           │
       │           │           │  │     ▼                                           │
       │           │           │  │   Supervisor                                    │
       │           │           │  │   (singleflight)                                │
       │           │ raw       │  │     │                                           │
       │           │ events    │  │   ┌─┴───────┐                                   │
       │           │ (PUT)     │  │   ▼         ▼                                   │     ┌─────────┐
       │           ▼           │  │ Snapshot   Pipeline ─── isDead? (RayCluster) ───┼────►│  K8s    │
       └───────────┼───────────┘  │ Loader     (parse only)                         │     │  API    │
                   │              │  (LRU)        │                                 │     └─────────┘
                   │              │   ▲           │ Prime(snap)                     │
                   │              │   └───────────┘                                 │
                   │              └────────▲────────────────────────────────────────┘
                   │                       │ raw events (GET) 
                   ▼                       │ 
       ┌──────────────────────────────────────────────────────────┐
       │  Object Storage  (S3 / GCS / Azure / Aliyun OSS)         │
       │                                                          │
       │  {rootDir}/{cluster}_{ns}/{session}/                     │
       │   node_events/, job_events/, logs/, fetched_endpoints/   │
       │       ▲                                                  │
       │       └── collector PUT (writes); HS reads only          │
       └──────────────────────────────────────────────────────────┘
    

    Request Data Flow

  • Happy path: Snapshot already cached
  • sequenceDiagram
      actor User
      participant HS as HS handler
      participant Sup as Supervisor
      participant Loader as SnapshotLoader
    
      User->>HS: GET /enter_cluster/{ns}/{name}/{session}
      HS->>HS: write 3 cookies
      HS->>Sup: Ensure(reqCtx, info)
      Sup->>Loader: Load(clusterID, session)
      Note over Loader: LRU only — no S3 fallback
      Loader-->>Sup: snap (LRU hit)
      Sup-->>HS: nil
      HS-->>User: 200 OK
    

  • Cold path: First visit to a dead session, with concurrent callers
  • sequenceDiagram
      actor User as Winner
      actor User2 as Follower
      participant HS as HS handler
      participant Sup as Supervisor (singleflight)
      participant Loader as SnapshotLoader
      participant Pipe as Pipeline
      participant K8s as K8s API
      participant S3 as Object Storage
    
      User->>HS: GET /enter_cluster (cold)
      User2->>HS: GET /enter_cluster (concurrent, same session)
      HS->>Sup: Ensure (winner)
      HS->>Sup: Ensure (follower)
      Note over Sup: same singleflight key →<br/>follower joins winner's group
      Sup->>Loader: Load(clusterID, session)
      Loader-->>Sup: ErrSnapshotNotFound (LRU miss)
      Sup->>Pipe: ProcessSession(serverCtx)
      Note over Pipe,Sup: serverCtx (NOT reqCtx) —<br/>winner disconnect cannot cancel<br/>work followers still depend on
      Pipe->>K8s: Get RayCluster
      K8s-->>Pipe: NotFound (dead)
      Pipe->>S3: List + GET event files
      Pipe->>Pipe: parse → SessionSnapshot (in memory)
      Pipe-->>Sup: snap, StatusProcessed
      Sup->>Loader: Prime(snap)
      Note over Loader: next handler call is O(1) —<br/>LRU hit, no re-parse
      Sup-->>HS: nil (winner)
      Sup-->>HS: nil (follower, shared result)
      HS-->>User: 200 OK
      HS-->>User2: 200 OK
    

    Takeaways:

  • singleflight key = {name}_{ns}/{session} (matches LRU key shape)

  • Pipeline closure runs under serverCtx, not the winner's request ctx

  • - Winner disconnects cannot cancel followers' shared work
  • Prime plants the freshly-built snapshot pointer into the LRU so the immediate follow-up calls (e.g. /tasks) is zero-IO
  • Components

    | Component | File | Purpose |
    | ------------------ | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
    | Pipeline | pkg/processor/session.go | Convert dead-session events → SessionSnapshot JSON; stateless across sessions. |
    | SnapshotLoader | pkg/server/cache.go | LRU-fronted snapshot reads; falls through to on-demand processing on miss. |
    | Supervisor | pkg/server/enter_cluster.go | Block /enter_cluster until a snapshot is ready; coalesce concurrent callers. |
    | HTTP handlers | pkg/server/handlers.go + formatters.go + router.go | Read-side API: tasks / actors / jobs / nodes / events / logs / cluster_status. |
    | Live reverse proxy | pkg/server/server.go | When session_name=="live", proxy to the head-pod Ray Dashboard (8265). |
    | Metrics | pkg/metrics/metrics.go | Centralized Prometheus declarations. |

    Unit Test Coverage

    pkg/snapshot          0.0% (no statements; only type declarations)
    pkg/metrics           100.0%
    pkg/processor         75.7%
    pkg/server            41.8%
    cmd/historyserver     0.0%   (main entry; integration-only)
    

    Limitations & Follow-ups

    Test Coverage

  • Raise unit test coverage

  • Add e2e test suite
  • Functional gaps

  • /api/v0/logs/file: task_id / actor_id resolution returns 400 (caller must pass node_id + filename).

  • /api/v0/logs/stream for dead clusters returns 501 — no historical tail.

  • formatTaskForResponse does not emit profiling_data until TASK_PROFILE_EVENT is supported upstream.

  • cluster_status?format=1 reports Pending: (unavailable in history server) — autoscaler events are not exported.
  • Operational gaps

  • Distributed singleflight: Per-replica singleflight.Group; multi-replica races are safe via skip-if-exists but Pipeline can run on more than one replica simultaneously. Acceptable at current scale.

  • Graceful drain on SIGTERM: SIGTERM currently cancels in-flight Pipeline work; if 500-during-shutdown becomes a pain point, switch the closure to a separate runCtx with a grace timer.

  • Stale-snapshot rebuild: No admin endpoint to force rebuild; snapshots are immutable by design.
  • Related issue number

    N/A

    Checks

    For setting up a local dev env for testing, see historyserver/beta-v2/README.md.

  • 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: 18256m
    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 #4765"
    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%