Skip to content

Conversation

@junaiddshaukat
Copy link
Contributor

@junaiddshaukat junaiddshaukat commented Jan 3, 2026

Summary

Fixes #37213

Implements LRU (Least Recently Used) cache eviction for CachingStateProvider to prevent unbounded memory growth in long-running workers.

Problem

The CachingStateProvider currently has unbounded cache growth, which can lead to memory issues. There's a TODO comment indicating this needs to be addressed:

// TODO: (Perf) Cache eviction.## Solution

  • Add configurable maxCacheSize parameter (default: 1000 entries)
  • Implement LRU eviction: remove oldest entry when cache reaches capacity
  • Maintain LRU order using JavaScript Map's insertion order
  • Move accessed items to end (most recently used) on cache hits

Changes

  • Modified sdks/typescript/src/apache_beam/worker/state.ts:

    • Added maxCacheSize constructor parameter
    • Implemented evictIfNeeded() method
    • Implemented touchCacheEntry() method for LRU ordering
    • Updated getState() to use eviction and LRU tracking
  • Added sdks/typescript/test/state_provider_test.ts:

    • Test cache hits/misses
    • Test LRU eviction behavior
    • Test promise-based state fetches
    • Test custom maxCacheSize

Testing

  • All tests pass: npm test in sdks/typescript
  • 4 new test cases added for CachingStateProvider
  • No breaking changes (backward compatible)

Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:

  • Mention the appropriate issue in your description (for example: addresses #123), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment fixes #<ISSUE NUMBER> instead.
  • Update CHANGES.md with noteworthy changes.
  • If this contribution is large, please file an Apache Individual Contributor License Agreement.

See the Contributor Guide for more tips on how to make review process smoother.

To check the build health, please visit https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md

GitHub Actions Tests Status (on master branch)

Build python source distribution and wheels
Python tests
Java tests
Go tests

See CI.md for more information about GitHub Actions CI or the workflows README to see a list of phrases to trigger workflows.

Fixes apache#37213

Implements LRU (Least Recently Used) cache eviction to prevent
unbounded memory growth in long-running workers. Adds configurable
maxCacheSize parameter (default: 1000 entries) and maintains LRU
order using JavaScript Map's insertion order.

- Add maxCacheSize constructor parameter with default value of 1000
- Implement evictIfNeeded() to remove oldest entry when cache is full
- Implement touchCacheEntry() to move accessed items to end (LRU)
- Add comprehensive test coverage in state_provider_test.ts

This addresses the TODO comment in the code and improves reliability
for production workloads.
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @junaiddshaukat, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a critical memory management concern in the CachingStateProvider by integrating a Least Recently Used (LRU) cache eviction policy. This enhancement ensures that the cache operates within a defined memory footprint, preventing unbounded growth and potential memory exhaustion in long-running processes, thereby improving the stability and efficiency of the system.

Highlights

  • LRU Cache Eviction: Implemented Least Recently Used (LRU) cache eviction for the CachingStateProvider to prevent unbounded memory growth in long-running workers.
  • Configurable Cache Size: Introduced a configurable maxCacheSize parameter to the CachingStateProvider constructor, defaulting to 1000 entries, allowing control over the cache's maximum capacity.
  • LRU Order Maintenance: Added logic to maintain LRU order by leveraging JavaScript Map's insertion order, ensuring that accessed items are moved to the end (most recently used) of the cache.
  • New Test Coverage: Included comprehensive new test cases for CachingStateProvider to validate cache hits/misses, LRU eviction behavior, promise-based state fetches, and custom maxCacheSize configurations.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@junaiddshaukat
Copy link
Contributor Author

@damccorm, Please have a look on this PR. Thanks

@github-actions
Copy link
Contributor

github-actions bot commented Jan 3, 2026

Assigning reviewers:

R: @chamikaramj added as fallback since no labels match configuration

Note: If you would like to opt out of this review, comment assign to next reviewer.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

The PR bot will only process comments in the main thread (not review comments).

@damccorm
Copy link
Contributor

damccorm commented Jan 5, 2026

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a much-needed LRU cache eviction mechanism to CachingStateProvider, preventing unbounded memory growth. The implementation correctly uses JavaScript's Map to maintain insertion order for LRU logic, and the accompanying tests are thorough. I've identified a bug in the promise-handling logic that could lead to incorrect cache eviction, along with a minor code style improvement. A single code suggestion is provided to address both issues. Overall, this is a solid contribution.

…ider

- Fixed bug: removed incorrect evictIfNeeded() call in promise callback
- Removed unnecessary this_ variable (arrow functions capture this)
- Changed from count-based to size-based eviction (similar to Python statecache.py)
- Added estimateSize() to calculate memory weight of cached values
- Default cache weight: 100MB
- Updated tests to work with weight-based eviction
* Estimates the memory size of a value in bytes.
* This is a simplified estimation - actual memory usage may vary.
*/
function estimateSize(value: any): number {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@damccorm
Copy link
Contributor

damccorm commented Jan 5, 2026

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a much-needed LRU cache eviction mechanism to CachingStateProvider, preventing unbounded memory growth. The implementation uses a weight-based approach with estimateSize to approximate memory usage and relies on JavaScript's Map insertion order to manage LRU logic. The changes are well-structured and include a comprehensive set of new tests.

My review includes a few key points:

  • A critical fix for handling circular references in the estimateSize function to prevent potential crashes.
  • A fix for a bug in the cache-miss logic that could cause the cache to exceed its maximum weight limit.
  • A suggestion to improve the efficiency of the eviction logic.
  • A recommendation to enhance the test suite to cover an important edge case.

Overall, this is a solid contribution that addresses a significant performance and stability concern.

Comment on lines +61 to +98
function estimateSize(value: any): number {
if (value === null || value === undefined) {
return 8;
}

const type = typeof value;

if (type === "boolean") {
return 4;
}
if (type === "number") {
return 8;
}
if (type === "string") {
// Each character is 2 bytes in JavaScript (UTF-16) + overhead
return 40 + value.length * 2;
}
if (value instanceof Uint8Array || value instanceof Buffer) {
return 40 + value.length;
}
if (Array.isArray(value)) {
let size = 40; // Array overhead
for (const item of value) {
size += estimateSize(item);
}
return size;
}
if (type === "object") {
let size = 40; // Object overhead
for (const key of Object.keys(value)) {
size += estimateSize(key) + estimateSize(value[key]);
}
return size;
}

// Default for unknown types
return 64;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The recursive implementation of estimateSize for objects and arrays does not handle circular references. If a cached object contains a cycle (e.g., a.b = a), this function will enter an infinite loop, leading to a stack overflow and crashing the worker. This is a critical stability risk.

function estimateSize(value: any, visited = new Set<any>()): number {
  if (value === null || value === undefined) {
    return 8;
  }

  if (typeof value === "object") {
    if (visited.has(value)) {
      return 8; // Account for reference size, not the full object again.
    }
    visited.add(value);
  }

  const type = typeof value;

  if (type === "boolean") {
    return 4;
  }
  if (type === "number") {
    return 8;
  }
  if (type === "string") {
    // Each character is 2 bytes in JavaScript (UTF-16) + overhead
    return 40 + value.length * 2;
  }
  if (value instanceof Uint8Array || value instanceof Buffer) {
    return 40 + value.length;
  }
  if (Array.isArray(value)) {
    let size = 40; // Array overhead
    for (const item of value) {
      size += estimateSize(item, visited);
    }
    return size;
  }
  if (type === "object") {
    let size = 40; // Object overhead
    for (const key of Object.keys(value)) {
      size += estimateSize(key, visited) + estimateSize(value[key], visited);
    }
    return size;
  }

  // Default for unknown types
  return 64;
}

Comment on lines +185 to +188
// Evict if needed before adding new entry
this.currentWeight += weight;
this.evictIfNeeded();
this.cache.set(cacheKey, { entry: result, weight });
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

There is a bug in the ordering of operations for a synchronous cache miss. evictIfNeeded() is called before the new item is added to the cache via this.cache.set(). If the cache is empty and a new item's weight exceeds maxCacheWeight, evictIfNeeded() will not run (as this.cache.size is 0). The oversized item is then added, causing the cache to violate its weight limit until the next eviction event. The item should be added to the cache before eviction is checked.

    // Add new entry and then evict if needed
    this.currentWeight += weight;
    this.cache.set(cacheKey, { entry: result, weight });
    this.evictIfNeeded();

Comment on lines +121 to +133
private evictIfNeeded() {
while (this.currentWeight > this.maxCacheWeight && this.cache.size > 0) {
// Remove the first (oldest) entry
const firstKey = this.cache.keys().next().value;
if (firstKey !== undefined) {
const evicted = this.cache.get(firstKey);
if (evicted !== undefined) {
this.currentWeight -= evicted.weight;
}
this.cache.delete(firstKey);
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The evictIfNeeded method can be made more efficient and readable. Currently, it gets the first key using this.cache.keys().next().value and then performs a separate this.cache.get(firstKey) lookup. You can achieve this in a single operation by iterating over this.cache.entries().

  private evictIfNeeded() {
    while (this.currentWeight > this.maxCacheWeight && this.cache.size > 0) {
      // JavaScript Maps preserve insertion order, so the first entry is the oldest.
      const [firstKey, evicted] = this.cache.entries().next().value;
      this.currentWeight -= evicted.weight;
      this.cache.delete(firstKey);
    }
  }

}
}

describe("CachingStateProvider", function () {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The test suite is quite thorough. To make it even more robust, consider adding a test case for the edge case where a single item, whose weight is larger than maxCacheWeight, is added to an empty cache. This would verify that the cache's weight limit is strictly enforced. With the recommended fix in state.ts, such an item should be added and then immediately evicted, leaving the cache empty and its weight at zero.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Task]: TypeScript SDK: Add LRU cache eviction to CachingStateProvider

2 participants