Skip to content
This repository was archived by the owner on Oct 22, 2025. It is now read-only.

Conversation

@NathanFlurry
Copy link
Member

@NathanFlurry NathanFlurry commented Aug 18, 2025

Fixes KIT-198

@claude
Copy link

claude bot commented Aug 18, 2025

Claude finished @NathanFlurry's task —— View job


Code Review: Actor Sleeping Feature

Todo List:

  • Read repository guidelines (CLAUDE.md)
  • Analyze core actor changes (config, instance, driver)
  • Review connection and driver modifications
  • Examine test suite changes
  • Check for potential bugs and security issues
  • Assess performance implications
  • Evaluate test coverage
  • Provide comprehensive feedback

Overview

This PR introduces an actor sleeping mechanism that allows inactive actors to be put into a dormant state to conserve resources. The feature includes:

  • Configuration options: noSleep (default: false) and sleepTimeout (default: 30,000ms)
  • Sleep logic: Actors sleep when they have no active connections and exceed the timeout
  • Driver integration: Sleep method added to ActorDriver interface, implemented in engine and file system drivers
  • Connection awareness: Sleep timer resets on connection events and alarm triggers

Code Quality & Best Practices ✅

Strengths:

  • Well-structured configuration: New sleep options properly integrated into existing config schema with sensible defaults
  • Good separation of concerns: Sleep logic contained in instance, driver interface extended cleanly
  • Proper state management: #sleepCalled and #stopCalled flags prevent duplicate operations
  • Consistent naming: Follows established camelCase conventions throughout

Minor improvements needed:

  • Line 86-87 in packages/core/src/drivers/file-system/actor.ts: Empty sleep() method implementation should have a comment explaining it's intentionally a no-op for file system driver

Architecture & Design 🔧

Good design decisions:

  • Optional sleep support: #sleepingSupported property allows drivers to opt-in to sleeping
  • Timeout management: #resetSleepTimer() properly handles timer cleanup and rescheduling
  • Integration with existing lifecycle: Sleep timer resets appropriately on connections/alarms
  • Driver abstraction: Sleep method optional in driver interface, allowing graceful degradation

Potential concerns:

  • Engine driver alarms: packages/core/src/drivers/engine/actor-driver.ts:186 shows alarms are not implemented, which could affect sleep timing accuracy in production

Potential Bugs & Issues ⚠️

Minor issues found:

  1. Race condition potential (packages/core/src/actor/instance.ts:866-868):

    // Update sleep
    // Do this immediately after adding connection & before any async logic
    this.#resetSleepTimer();

    The comment acknowledges this race condition concern, and the placement looks correct.

  2. Error handling in engine driver (packages/core/src/drivers/engine/actor-driver.ts:353-355):

    async sleep(actorId: string) {
        this.#runner.sleepActor(actorId);
    }

    Missing error handling - should await and handle potential errors from sleepActor().

  3. File system driver sleep implementation (packages/core/src/drivers/file-system/global-state.ts:272-292):
    The sleepActor method properly handles the actor lifecycle but doesn't check if the actor is already sleeping/stopped.


Security Considerations 🔒

No security concerns identified. The sleeping feature:

  • Doesn't expose new attack surfaces
  • Maintains proper actor isolation
  • Uses existing authentication flows
  • Doesn't introduce privilege escalation risks

Performance Implications 🚀

Positive impacts:

  • Resource conservation: Inactive actors can be suspended, reducing memory/CPU usage
  • Scalability improvement: Allows platforms to handle more actors by suspending inactive ones
  • Configurable timing: 30-second default provides good balance between responsiveness and resource savings

Performance considerations:

  • Minimal overhead: Timer management adds small constant overhead
  • Connection tracking: Existing connection status checks reused efficiently
  • State persistence: File system driver properly handles state before sleeping

Test Coverage 📋

Test modifications look appropriate:

  • Removed hardcoded timeout values from test fixtures, making them more maintainable
  • Connection liveness and error handling tests simplified without losing functionality
  • No new test coverage added for sleeping feature itself

Recommendation: Consider adding integration tests specifically for the sleeping functionality to verify:

  • Actors sleep after configured timeout with no connections
  • Sleep timer resets correctly on new connections
  • Actors can be awakened properly after sleeping
  • Configuration options work as expected

Final Assessment ✨

This is a well-implemented feature that adds valuable resource management capabilities to RivetKit. The code follows established patterns, maintains backward compatibility, and includes proper safeguards.

Recommendations for improvement:

  1. Add error handling to engine driver's sleep() method
  2. Add comment to file system driver's no-op sleep() method
  3. Consider adding dedicated tests for the sleeping functionality
  4. Implement alarms in engine driver to ensure proper sleep timing

Overall: ✅ Approved - Ready for merge with minor improvements suggested above.


Copy link
Member Author

NathanFlurry commented Aug 18, 2025

Warning

This pull request is not mergeable via GitHub because a downstack PR is open. Once all requirements are satisfied, merge this PR as a stack on Graphite.
Learn more


How to use the Graphite Merge Queue

Add either label to this PR to merge it via the merge queue:

  • merge queue - adds this PR to the back of the merge queue
  • hotfix - for urgent hot fixes, skip the queue and merge this PR next

You must have a Graphite account in order to use the merge queue. Sign up using this link.

An organization admin has enabled the Graphite Merge Queue in this repository.

Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue.

This stack of pull requests is managed by Graphite. Learn more about stacking.

@NathanFlurry NathanFlurry marked this pull request as draft August 18, 2025 07:28
if (this.#config.options.noSleep || !this.#sleepingSupported) return;

if (this.#sleepTimeout) {
clearInterval(this.#sleepTimeout);
Copy link

Choose a reason for hiding this comment

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

The code is using clearInterval() to clear a timeout that was set with setTimeout(). For proper timer management, clearTimeout() should be used instead to match the timer creation method.

Suggested change
clearInterval(this.#sleepTimeout);
clearTimeout(this.#sleepTimeout);

Spotted by Diamond

Is this helpful? React 👍 or 👎 to let us know.

@jog1t jog1t mentioned this pull request Aug 27, 2025
@NathanFlurry NathanFlurry mentioned this pull request Sep 2, 2025
@graphite-app graphite-app bot changed the base branch from 08-13-feat_engine_add_engine_driver to graphite-base/1178 September 2, 2025 09:14
@NathanFlurry NathanFlurry force-pushed the 08-17-feat_core_actor_sleeping branch from 97e285f to b0d246b Compare September 9, 2025 03:54
@NathanFlurry NathanFlurry changed the base branch from graphite-base/1178 to main September 9, 2025 03:54
@claude
Copy link

claude bot commented Sep 9, 2025

Claude finished @NathanFlurry's task —— View job


Code Review: Actor Sleeping Feature

This PR introduces an actor sleeping mechanism that allows inactive actors to be put into a dormant state to conserve resources. Here's my comprehensive analysis:


Overview

What this adds:

  • Configuration options: noSleep (default: false) and sleepTimeout (default: 30,000ms) in actor config
  • Sleep logic: Actors sleep when they have no active connections and exceed the timeout
  • Driver integration: Optional sleep() method added to ActorDriver interface
  • Connection awareness: Sleep timer resets on connection events and alarm triggers

🐛 Critical Issues Found

1. Timer Management Bug (packages/core/src/actor/instance.ts:1454)

clearInterval(this.#sleepTimeout); // ❌ Wrong - clearing interval for timeout

Issue: Using clearInterval() to clear a timeout created with setTimeout(). This is the same issue flagged by the automated review.

Fix: Should use clearTimeout():

clearTimeout(this.#sleepTimeout); // ✅ Correct

2. Engine Driver Error Handling (packages/core/src/drivers/engine/actor-driver.ts:357-359)

async sleep(actorId: string) {
    this.#runner.sleepActor(actorId); // ❌ Missing await and error handling
}

Issue: The sleepActor() call should be awaited and wrapped in error handling since it can fail.

3. Inconsistent Sleep Implementation

  • File system driver (line 85-87): Has empty implementation with no comment explaining it's intentionally a no-op
  • Engine driver: Has implementation but missing error handling

🏗️ Architecture & Design

✅ Well-designed aspects:

  • Optional sleep support: #sleepingSupported property allows drivers to opt-in
  • Proper state management: #sleepCalled and #stopCalled flags prevent duplicate operations
  • Timer reset logic: #resetSleepTimer() properly handles cleanup and rescheduling
  • Integration points: Sleep timer resets appropriately on connections/alarms

⚠️ Design concerns:

  • Engine driver alarms: Lines 183-190 show alarms use setTimeout rather than proper engine alarms, which could affect sleep timing accuracy in production

🔒 Security Analysis

✅ No security concerns identified:

  • Doesn't expose new attack surfaces
  • Maintains proper actor isolation
  • Uses existing authentication flows
  • No privilege escalation risks

🚀 Performance Implications

✅ Positive impacts:

  • Resource conservation: Inactive actors can be suspended, reducing memory/CPU usage
  • Scalability improvement: Allows platforms to handle more actors by suspending inactive ones
  • Configurable timing: 30-second default provides good balance between responsiveness and resource savings

Minimal overhead: Timer management adds small constant overhead but connection tracking reuses existing logic efficiently.


📋 Code Quality & Best Practices

✅ Strengths:

  • Well-structured configuration: New sleep options properly integrated with sensible defaults
  • Good separation of concerns: Sleep logic contained in instance, driver interface extended cleanly
  • Consistent naming: Follows established camelCase conventions throughout
  • Proper lifecycle integration: Sleep appropriately integrated with existing actor lifecycle

⚠️ Areas for improvement:

  • Missing JSDoc comments for new public configuration options
  • Empty sleep() method should have explanatory comment

🧪 Test Coverage

Test modifications reviewed:

  • Removed hardcoded timeout values from test fixtures ✅
  • Connection liveness and error handling tests simplified appropriately ✅
  • Missing: No dedicated tests for the sleeping functionality itself

Recommendation: Add integration tests for:

  • Actors sleep after configured timeout with no connections
  • Sleep timer resets correctly on new connections
  • Actors can be awakened properly after sleeping
  • Configuration options work as expected

📝 Recommended Changes

High Priority

  1. Fix timer bug: Change clearInterval to clearTimeout in instance.ts:1454
  2. Add error handling: Wrap sleepActor() call in engine driver with proper error handling
  3. Add comment: Explain why file system driver's sleep() method is empty

Medium Priority

  1. Add tests: Create integration tests for sleep functionality
  2. JSDoc: Add documentation for new config options noSleep and sleepTimeout
  3. Engine alarms: Consider implementing proper alarms in engine driver for production use

✅ Final Assessment

This is a well-implemented feature that adds valuable resource management capabilities to RivetKit. The code follows established patterns, maintains backward compatibility, and includes proper safeguards.

Recommendation: ✅ Approve with required fixes

The timer management bug should be fixed before merge, but overall this is solid work that will improve the platform's resource efficiency.

@claude
Copy link

claude bot commented Sep 9, 2025

Claude finished @NathanFlurry's task —— View job


Code Review: Actor Sleeping Feature

Todo List:

  • Read repository guidelines (CLAUDE.md)
  • Analyze core actor changes (config, instance, driver)
  • Review connection and driver modifications
  • Examine test suite changes
  • Check for potential bugs and security issues
  • Assess performance implications
  • Evaluate test coverage
  • Address timer management issue identified by Graphite
  • Provide comprehensive feedback

Overview

This PR introduces an actor sleeping mechanism that allows inactive actors to be put into a dormant state to conserve resources. The feature includes:

  • Configuration options: noSleep (default: false) and sleepTimeout (default: 30,000ms)
  • Sleep logic: Actors sleep when they have no active connections and exceed the timeout
  • Driver integration: Sleep method added to ActorDriver interface, implemented in engine and file system drivers
  • Connection awareness: Sleep timer resets on connection events and alarm triggers

Code Quality & Best Practices ✅

Strengths:

  • Well-structured configuration: New sleep options properly integrated into existing config schema with sensible defaults
  • Good separation of concerns: Sleep logic contained in instance, driver interface extended cleanly
  • Proper state management: #sleepCalled and #stopCalled flags prevent duplicate operations
  • Consistent naming: Follows established camelCase conventions throughout

Issues to address:

  • Line 86-87 in packages/core/src/drivers/file-system/actor.ts: Empty sleep() method implementation should have a comment explaining it's intentionally a no-op for file system driver

Critical Bug Found 🚨

Timer Management Issue (identified by Graphite review bot):

// packages/core/src/actor/instance.ts:1454
clearInterval(this.#sleepTimeout);

Problem: The code uses clearInterval() to clear a timeout that was set with setTimeout(). This is incorrect and could lead to timers not being properly cleared.

Fix needed: Should use clearTimeout() instead:

clearTimeout(this.#sleepTimeout);

Architecture & Design 🔧

Good design decisions:

  • Optional sleep support: #sleepingSupported property allows drivers to opt-in to sleeping
  • Timeout management: #resetSleepTimer() properly handles timer cleanup and rescheduling
  • Integration with existing lifecycle: Sleep timer resets appropriately on connections/alarms
  • Driver abstraction: Sleep method optional in driver interface, allowing graceful degradation

Potential concerns:

  • Engine driver alarms: packages/core/src/drivers/engine/actor-driver.ts:186 shows alarms are not implemented properly, which could affect sleep timing accuracy in production

Additional Issues Found ⚠️

  1. Missing error handling in engine driver (packages/core/src/drivers/engine/actor-driver.ts:357-359):

    async sleep(actorId: string) {
        this.#runner.sleepActor(actorId);
    }

    Missing await and error handling - should handle potential errors from sleepActor().

  2. File system driver sleep implementation (packages/core/src/drivers/file-system/global-state.ts:278-298):
    The sleepActor method properly handles the actor lifecycle but doesn't check if the actor is already sleeping/stopped.

  3. Race condition potential (packages/core/src/actor/instance.ts:866-868):
    The comment acknowledges this concern, and the placement looks correct, but worth monitoring.


Security Considerations 🔒

No security concerns identified. The sleeping feature:

  • Doesn't expose new attack surfaces
  • Maintains proper actor isolation
  • Uses existing authentication flows
  • Doesn't introduce privilege escalation risks

Performance Implications 🚀

Positive impacts:

  • Resource conservation: Inactive actors can be suspended, reducing memory/CPU usage
  • Scalability improvement: Allows platforms to handle more actors by suspending inactive ones
  • Configurable timing: 30-second default provides good balance between responsiveness and resource savings

Performance considerations:

  • Minimal overhead: Timer management adds small constant overhead
  • Connection tracking: Existing connection status checks reused efficiently
  • State persistence: File system driver properly handles state before sleeping

Test Coverage 📋

Test modifications look appropriate:

  • Removed hardcoded timeout values from test fixtures, making them more maintainable
  • Connection liveness and error handling tests simplified without losing functionality
  • Missing: No new test coverage added for sleeping feature itself

Recommendation: Consider adding integration tests specifically for the sleeping functionality to verify:

  • Actors sleep after configured timeout with no connections
  • Sleep timer resets correctly on new connections
  • Actors can be awakened properly after sleeping
  • Configuration options work as expected

Final Assessment ✨

This is a well-designed feature that adds valuable resource management capabilities to RivetKit. The code follows established patterns, maintains backward compatibility, and includes proper safeguards.

Critical issues that MUST be fixed before merge:

  1. Fix timer management bug: Use clearTimeout() instead of clearInterval() in packages/core/src/actor/instance.ts:1454

Recommended improvements:

  1. Add error handling to engine driver's sleep() method
  2. Add comment to file system driver's no-op sleep() method
  3. Consider adding dedicated tests for the sleeping functionality
  4. Implement proper alarms in engine driver to ensure correct sleep timing

Overall: ⚠️ Needs fixes - The timer management bug is critical and must be addressed before merge. With that fix, this is a solid implementation ready for production.


@NathanFlurry NathanFlurry marked this pull request as ready for review September 9, 2025 04:00
@NathanFlurry NathanFlurry changed the base branch from main to graphite-base/1178 September 9, 2025 04:14
@NathanFlurry NathanFlurry force-pushed the 08-17-feat_core_actor_sleeping branch from b0d246b to 7700f30 Compare September 9, 2025 04:14
@NathanFlurry NathanFlurry changed the base branch from graphite-base/1178 to 09-08-fix_core_revert_deleted_fixtures September 9, 2025 04:14
@claude
Copy link

claude bot commented Sep 9, 2025

Claude finished @NathanFlurry's task —— View job


Code Review: Actor Sleeping Feature

Todo List:

  • Read repository guidelines (CLAUDE.md)
  • Analyze core actor changes (config, instance, driver)
  • Review connection and driver modifications
  • Examine test suite changes
  • Check for potential bugs and security issues
  • Assess performance implications
  • Evaluate test coverage
  • Address timer management issue identified by Graphite
  • Provide comprehensive feedback

Overview

This PR introduces an actor sleeping mechanism that allows inactive actors to be put into a dormant state to conserve resources. The feature includes:

  • Configuration options: noSleep (default: false) and sleepTimeout (default: 30,000ms)
  • Sleep logic: Actors sleep when they have no active connections and exceed the timeout
  • Driver integration: Optional sleep() method added to ActorDriver interface
  • Connection awareness: Sleep timer resets on connection events and alarm triggers

🚨 Critical Bug Found

Timer Management Issue (packages/core/src/actor/instance.ts:1454):

clearInterval(this.#sleepTimeout); // ❌ Wrong - clearing interval for timeout

Problem: The code uses clearInterval() to clear a timeout that was set with setTimeout(). This is incorrect and could lead to timers not being properly cleared.

Fix needed: Should use clearTimeout():

clearTimeout(this.#sleepTimeout); // ✅ Correct

This matches the issue identified by the Graphite review bot and must be fixed before merge.


🏗️ Architecture & Design

✅ Well-designed aspects:

  • Optional sleep support: #sleepingSupported property allows drivers to opt-in to sleeping
  • Proper state management: #sleepCalled and #stopCalled flags prevent duplicate operations
  • Timer reset logic: #resetSleepTimer() properly handles cleanup and rescheduling
  • Integration points: Sleep timer resets appropriately on connections/alarms
  • Configuration schema: New sleep options properly integrated with sensible defaults

⚠️ Design concerns:

  • Engine driver alarms: Lines 183-190 in engine driver show alarms use setTimeout rather than proper engine alarms, which could affect sleep timing accuracy in production

🐛 Additional Issues Found

  1. Missing error handling in engine driver (packages/core/src/drivers/engine/actor-driver.ts:357-359):

    async sleep(actorId: string) {
        this.#runner.sleepActor(actorId); // ❌ Missing await and error handling
    }

    Should await and handle potential errors from sleepActor().

  2. Missing documentation in file system driver (packages/core/src/drivers/file-system/actor.ts:85-86):

    sleep(actorId: string): void {} // ❌ No comment explaining intentional no-op

    Should have comment explaining why this is intentionally empty for file system driver.

  3. Race condition handling (packages/core/src/actor/instance.ts:866-868):
    The comment acknowledges this concern and placement looks correct, but worth monitoring.


🔒 Security Analysis

✅ No security concerns identified:

  • Doesn't expose new attack surfaces
  • Maintains proper actor isolation
  • Uses existing authentication flows
  • No privilege escalation risks

🚀 Performance Implications

✅ Positive impacts:

  • Resource conservation: Inactive actors can be suspended, reducing memory/CPU usage
  • Scalability improvement: Allows platforms to handle more actors by suspending inactive ones
  • Configurable timing: 30-second default provides good balance between responsiveness and resource savings

Minimal overhead: Timer management adds small constant overhead but connection tracking reuses existing logic efficiently.


📋 Code Quality & Best Practices

✅ Strengths:

  • Well-structured configuration: New sleep options properly integrated into existing config schema
  • Good separation of concerns: Sleep logic contained in instance, driver interface extended cleanly
  • Consistent naming: Follows established camelCase conventions throughout
  • Proper lifecycle integration: Sleep appropriately integrated with existing actor lifecycle

⚠️ Areas for improvement:

  • Missing JSDoc comments for new public configuration options (noSleep, sleepTimeout)
  • Test fixture changes remove hardcoded timeouts (good) but no dedicated sleep functionality tests

🧪 Test Coverage

Test modifications reviewed:

  • ✅ Removed hardcoded timeout values from test fixtures, making them more maintainable
  • ✅ Connection liveness and error handling tests simplified appropriately
  • Missing: No dedicated tests for the sleeping functionality itself

Recommendation: Add integration tests for:

  • Actors sleep after configured timeout with no connections
  • Sleep timer resets correctly on new connections
  • Actors can be awakened properly after sleeping
  • Configuration options work as expected

📝 Required Changes

High Priority (Must Fix Before Merge)

  1. Fix timer management bug: Change clearInterval to clearTimeout in packages/core/src/actor/instance.ts:1454

Medium Priority (Recommended Improvements)

  1. Add error handling: Wrap sleepActor() call in engine driver with proper error handling
  2. Add documentation: Comment explaining why file system driver's sleep() method is empty
  3. Add tests: Create integration tests for sleep functionality
  4. JSDoc: Add documentation for new config options noSleep and sleepTimeout

✅ Final Assessment

This is a well-designed feature that adds valuable resource management capabilities to RivetKit. The code follows established patterns, maintains backward compatibility, and includes proper safeguards.

Recommendation: ⚠️ Needs fixes - The timer management bug is critical and must be addressed before merge. With that fix, this is a solid implementation ready for production.

The sleep functionality will significantly improve resource efficiency by allowing inactive actors to be suspended, which is especially valuable for platforms handling many actors with varying activity levels.


@claude
Copy link

claude bot commented Sep 9, 2025

Claude finished @NathanFlurry's task —— View job


Code Review: Actor Sleeping Feature

Todo List:

  • Read repository guidelines (CLAUDE.md)
  • Analyze core actor changes (config, instance, driver)
  • Review connection and driver modifications
  • Examine test suite changes
  • Check for the timer management bug flagged by Graphite
  • Check for potential bugs and security issues
  • Assess performance implications
  • Evaluate test coverage
  • Provide comprehensive feedback

Overview

This PR introduces an actor sleeping mechanism that allows inactive actors to be put into a dormant state to conserve resources. The feature includes:

  • Configuration options: noSleep (default: false) and sleepTimeout (default: 30,000ms)
  • Sleep logic: Actors sleep when they have no active connections and exceed the timeout
  • Driver integration: Optional sleep() method added to ActorDriver interface
  • Connection awareness: Sleep timer resets on connection events and alarm triggers

🚨 CRITICAL BUG - MUST FIX

Timer Management Issue (packages/core/src/actor/instance.ts:1454)

clearInterval(this.#sleepTimeout); // ❌ WRONG

Problem: Using clearInterval() to clear a timeout created with setTimeout() on line 1459. This is incorrect and could prevent timers from being properly cleared.

Required Fix:

clearTimeout(this.#sleepTimeout); // ✅ CORRECT

⚠️ Additional Issues Found

1. Engine Driver Error Handling (packages/core/src/drivers/engine/actor-driver.ts:357-359)

async sleep(actorId: string) {
    this.#runner.sleepActor(actorId); // Missing await and error handling
}

Issue: The sleepActor() call should be awaited and wrapped in error handling.

2. File System Driver Missing Comment (packages/core/src/drivers/file-system/actor.ts:85)

sleep(actorId: string): void {} // Should have explanatory comment

Issue: Empty implementation should explain why it's a no-op for file system driver.

3. Test Files Have Merge Conflicts

Several test fixture files contain unresolved merge conflicts (conn-liveness.ts, action-timeout.ts, error-handling.ts) that need to be resolved.


🏗️ Architecture & Design

Well-designed aspects:

  • Optional sleep support: #sleepingSupported property allows drivers to opt-in
  • Proper state management: #sleepCalled and #stopCalled flags prevent duplicate operations
  • Timer reset logic: #resetSleepTimer() properly handles cleanup and rescheduling
  • Integration points: Sleep timer resets appropriately on:
    • New connections (line 868)
    • Alarm triggers (line 393)
    • Actor startup (line 332)
    • Connection removal (line 761)

⚠️ Design concerns:

  • File system driver implementation: The sleepActor() method in global state properly handles lifecycle but doesn't check if actor is already sleeping/stopped

🔒 Security Analysis

✅ No security concerns identified:

  • Doesn't expose new attack surfaces
  • Maintains proper actor isolation
  • Uses existing authentication flows
  • No privilege escalation risks

🚀 Performance Implications

Positive impacts:

  • Resource conservation: Inactive actors can be suspended, reducing memory/CPU usage
  • Scalability improvement: Allows platforms to handle more actors by suspending inactive ones
  • Configurable timing: 30-second default provides good balance between responsiveness and resource savings

Performance considerations:

  • Minimal overhead: Timer management adds small constant overhead
  • Connection tracking: Existing connection status checks reused efficiently
  • State persistence: File system driver properly handles state before sleeping

📋 Code Quality & Best Practices

Strengths:

  • Well-structured configuration: New sleep options properly integrated with sensible defaults (lines 70-71 in config.ts)
  • Good separation of concerns: Sleep logic contained in instance, driver interface extended cleanly
  • Consistent naming: Follows established camelCase conventions throughout
  • Proper lifecycle integration: Sleep appropriately integrated with existing actor lifecycle

⚠️ Areas for improvement:

  • Missing JSDoc comments for new public configuration options (noSleep, sleepTimeout)
  • Test fixture merge conflicts need resolution

🧪 Test Coverage

Test modifications reviewed:

  • Removed hardcoded timeout values from test fixtures, making them more maintainable
  • Connection liveness and error handling tests updated appropriately
  • Configuration flattening (removing nested lifecycle and action objects) improves API consistency

Missing test coverage:

No dedicated tests for the sleeping functionality itself.

Recommendation: Add integration tests for:

  • Actors sleep after configured timeout with no connections
  • Sleep timer resets correctly on new connections
  • Actors can be awakened properly after sleeping
  • Configuration options work as expected

Final Assessment

This is a well-designed feature that adds valuable resource management capabilities to RivetKit. The code follows established patterns, maintains backward compatibility, and includes proper safeguards.

Required Changes Before Merge:

  1. 🚨 CRITICAL: Fix timer management bug - use clearTimeout() instead of clearInterval()
  2. Resolve merge conflicts in test fixture files
  3. Add error handling to engine driver's sleep() method
  4. Add explanatory comment to file system driver's no-op sleep() method

Recommended Improvements:

  1. Add JSDoc documentation for new config options
  2. Add dedicated integration tests for sleep functionality

Overall Rating: ⚠️ Needs Critical Fix

The timer management bug is critical and must be addressed before merge. With that fix and merge conflict resolution, this is a solid implementation that will improve the platform's resource efficiency.


@claude
Copy link

claude bot commented Sep 9, 2025

Claude finished @NathanFlurry's task —— View job


Code Review: Actor Sleeping Feature

Todo List:

  • Read repository guidelines (CLAUDE.md)
  • Analyze core actor changes (config, instance, driver)
  • Review connection and driver modifications
  • Examine test suite changes
  • Check for the timer management bug flagged by Graphite
  • Check for potential bugs and security issues
  • Assess performance implications
  • Evaluate test coverage
  • Provide comprehensive feedback

Overview

This PR introduces an actor sleeping mechanism that allows inactive actors to be put into a dormant state to conserve resources. The feature includes:

  • Configuration options: noSleep (default: false) and sleepTimeout (default: 30,000ms)
  • Sleep logic: Actors sleep when they have no active connections and exceed the timeout
  • Driver integration: Optional sleep() method added to ActorDriver interface
  • Connection awareness: Sleep timer resets on connection events and alarm triggers

Major Issues Resolved

Timer Management Bug Fixed

The timer management issue flagged by Graphite has been resolved. Line 1454 in packages/core/src/actor/instance.ts now correctly uses clearTimeout() instead of clearInterval().


🏗️ Architecture & Design

Well-designed aspects:

  • Optional sleep support: #sleepingSupported property allows drivers to opt-in to sleeping
  • Proper state management: #sleepCalled and #stopCalled flags prevent duplicate operations
  • Timer reset logic: #resetSleepTimer() properly handles cleanup and rescheduling
  • Integration points: Sleep timer resets appropriately on:
    • New connections (instance.ts:868)
    • Alarm triggers (instance.ts:393)
    • Actor startup (instance.ts:332)
    • Connection removal (instance.ts:761)
  • Configuration schema: New sleep options properly integrated with sensible defaults (config.ts:70-71)

Driver Implementations

Engine Driver (packages/core/src/drivers/engine/actor-driver.ts:352-354):

  • Implements sleep() method that delegates to this.#runner.sleepActor(actorId)
  • Simple and clean integration with runner infrastructure

File System Driver (packages/core/src/drivers/file-system/actor.ts:85-87):

  • Implements sleep() method that calls this.#state.sleepActor(actorId)
  • Full lifecycle handling in global state (lines 278-298)
  • Properly waits for actor startup, removes from map, and stops actor

🐛 Issues Found

Minor Issues

  1. Engine Driver Missing Error Handling (packages/core/src/drivers/engine/actor-driver.ts:352-354):

    sleep(actorId: string) {
        this.#runner.sleepActor(actorId); // No error handling
    }

    Recommendation: Add error handling since sleepActor() could potentially fail.

  2. Missing JSDoc Comments:
    New configuration options noSleep and sleepTimeout lack documentation comments explaining their purpose and behavior.

  3. Alarm Implementation Gap (packages/core/src/drivers/engine/actor-driver.ts:182-186):

    async setAlarm(actor: AnyActorInstance, timestamp: number): Promise<void> {
        // TODO: Set timeout
        // TODO: Use alarm on sleep
        // TODO: Send alarm to runner
    }

    Note: Alarms are not fully implemented in engine driver, which could affect sleep timing accuracy in production.


🔒 Security Analysis

✅ No security concerns identified:

  • Doesn't expose new attack surfaces
  • Maintains proper actor isolation
  • Uses existing authentication flows
  • No privilege escalation risks
  • Sleep functionality is properly gated behind configuration options

🚀 Performance Implications

Positive impacts:

  • Resource conservation: Inactive actors can be suspended, reducing memory/CPU usage
  • Scalability improvement: Allows platforms to handle more actors by suspending inactive ones
  • Configurable timing: 30-second default provides good balance between responsiveness and resource savings

Performance considerations:

  • Minimal overhead: Timer management adds small constant overhead
  • Connection tracking: Existing connection status checks reused efficiently
  • State persistence: File system driver properly handles state before sleeping

📋 Code Quality & Best Practices

Strengths:

  • Well-structured configuration: New sleep options properly integrated into existing config schema
  • Good separation of concerns: Sleep logic contained in instance, driver interface extended cleanly
  • Consistent naming: Follows established camelCase conventions throughout
  • Proper lifecycle integration: Sleep appropriately integrated with existing actor lifecycle
  • Defensive programming: Proper use of invariant() for runtime checks

⚠️ Areas for improvement:

  • Missing JSDoc comments for new public configuration options
  • Could benefit from integration tests specifically for sleep functionality

🧪 Test Coverage

Test modifications reviewed:

  • Configuration simplification: Test fixtures updated to remove hardcoded timeout values, making them more maintainable
  • Cleaner actor definitions: Connection liveness, action timeout, and error handling actors streamlined
  • Better configuration structure: Removed complex nested timeout configurations in favor of simpler flat options

Missing test coverage:

No dedicated tests for the sleeping functionality itself.

Recommendation: Add integration tests for:

  • Actors sleep after configured timeout with no connections
  • Sleep timer resets correctly on new connections
  • Actors can be awakened properly after sleeping
  • Configuration options work as expected

Final Assessment

This is a well-designed and implemented feature that adds valuable resource management capabilities to RivetKit. The code follows established patterns, maintains backward compatibility, and includes proper safeguards.

Strengths:

  • ✅ Timer management bug fixed
  • ✅ Clean architecture with proper separation of concerns
  • ✅ Optional driver support allows graceful degradation
  • ✅ Good integration with existing actor lifecycle
  • ✅ Sensible default configuration values

Minor Improvements Recommended:

  1. Add error handling to engine driver's sleep() method
  2. Add JSDoc documentation for new config options
  3. Consider adding dedicated integration tests for sleep functionality
  4. Complete alarm implementation in engine driver for production use

Overall Rating:Approved

This feature will significantly improve resource efficiency by allowing inactive actors to be suspended, which is especially valuable for platforms handling many actors with varying activity levels. The implementation is solid and production-ready.


@NathanFlurry NathanFlurry force-pushed the 08-17-feat_core_actor_sleeping branch from 867931a to 620dda3 Compare September 10, 2025 05:36
@claude
Copy link

claude bot commented Sep 10, 2025

Claude finished @NathanFlurry's task —— View job


Code Review: Actor Sleeping Feature

Todo List:

  • Read repository guidelines (CLAUDE.md)
  • Analyze core actor changes (config, instance, driver)
  • Review driver implementations (engine, file-system)
  • Examine new test suite changes and coverage
  • Check for potential bugs and security issues
  • Assess performance implications
  • Verify timer management bug fix from previous reviews
  • Provide comprehensive feedback

Overview

This PR introduces an actor sleeping mechanism that allows inactive actors to be put into a dormant state to conserve resources. The feature includes:

  • Configuration options: noSleep (default: false) and sleepTimeout (default: 30,000ms)
  • Sleep logic: Actors sleep when they have no active connections and exceed the timeout
  • Driver integration: Optional sleep() method added to ActorDriver interface
  • Connection awareness: Sleep timer resets on connection events and alarm triggers
  • Comprehensive test suite: New test fixtures and integration tests for sleep functionality

Critical Issue Resolved

Timer Management Bug Fixed

The timer management issue flagged by previous reviews has been resolved. Line 1492 in packages/core/src/actor/instance.ts now correctly uses clearTimeout() instead of clearInterval(). This was a critical bug that could prevent timers from being properly cleared.


🏗️ Architecture & Design

Excellent Design Decisions

  • Optional sleep support: #sleepingSupported property allows drivers to opt-in to sleeping (instance.ts:236-238)
  • Proper state management: #sleepCalled and #stopCalled flags prevent duplicate operations (instance.ts:132-137)
  • Comprehensive timer reset logic: #resetSleepTimer() properly handles cleanup and rescheduling (instance.ts:1481-1505)
  • Smart integration points: Sleep timer resets appropriately on:
    • New connections (instance.ts:869-872)
    • Alarm triggers (instance.ts:394-397)
    • Actor startup (instance.ts:335-336)
    • Connection removal (instance.ts:764-765)
    • Raw fetch completion (instance.ts:1239-1241)
  • Configuration schema: New sleep options properly integrated with sensible defaults (config.ts:73-74)

Driver Implementations

Engine Driver (packages/core/src/drivers/engine/actor-driver.ts:352-354):

  • Clean implementation that delegates to this.#runner.sleepActor(actorId)
  • Simple integration with runner infrastructure

File System Driver (packages/core/src/drivers/file-system/actor.ts:85-87):

  • Delegates to this.#state.sleepActor(actorId)
  • Full lifecycle handling in global state

🧪 Test Coverage - Outstanding

Comprehensive Test Suite Added

The PR includes excellent test coverage with:

New Test Fixtures (packages/core/fixtures/driver-test-suite/sleep.ts):

  • sleep actor with configurable timeout and state tracking
  • sleepWithLongRpc actor to test sleep behavior during long-running operations
  • Proper test configuration with SLEEP_TIMEOUT = 500ms for fast testing

Integration Tests (packages/core/src/driver-test-suite/tests/actor-sleep.ts):

  • Actor sleep persistence testing
  • Connection-based sleep prevention
  • Alarm-based sleep reset functionality
  • Long-running RPC sleep behavior
  • WebSocket sleep interaction testing

Test Fixture Improvements:

  • Removed hardcoded timeout values, making tests more maintainable
  • Simplified connection liveness, action timeout, and error handling test actors
  • Better configuration structure with flat options instead of nested objects

🔒 Security Analysis

✅ No security concerns identified:

  • Doesn't expose new attack surfaces
  • Maintains proper actor isolation
  • Uses existing authentication flows
  • No privilege escalation risks
  • Sleep functionality is properly gated behind configuration options
  • Proper validation of sleep conditions prevents unintended sleep states

🚀 Performance Implications

Excellent Performance Benefits

  • Resource conservation: Inactive actors can be suspended, significantly reducing memory/CPU usage
  • Scalability improvement: Allows platforms to handle many more actors by suspending inactive ones
  • Configurable timing: 30-second default provides excellent balance between responsiveness and resource savings
  • Smart activity detection: Considers multiple activity types:
    • Active connections (instance.ts:1512-1514)
    • In-flight raw fetches (instance.ts:1516-1517)
    • Open raw WebSocket connections (instance.ts:1519-1520)

Performance Considerations

  • Minimal overhead: Timer management adds only small constant overhead per actor
  • Connection tracking: Existing connection status checks reused efficiently
  • State persistence: Proper state handling before sleep ensures no data loss

📋 Code Quality & Best Practices

Outstanding Implementation Quality

  • Well-structured configuration: New sleep options properly integrated into existing config schema
  • Excellent separation of concerns: Sleep logic cleanly contained in instance, driver interface extended appropriately
  • Consistent naming: Follows established camelCase conventions throughout
  • Proper lifecycle integration: Sleep functionality seamlessly integrated with existing actor lifecycle
  • Defensive programming: Proper use of invariant() for runtime checks (instance.ts:1527-1528)
  • Clear documentation: Good JSDoc comments on lifecycle hooks mentioning sleep behavior (config.ts:320-329)

Sleep Logic Implementation

The _sleep() method (instance.ts:1525-1542) is well-implemented:

  • Proper guard conditions to prevent duplicate sleep calls
  • Clear logging for debugging
  • Delegates to driver for actual sleep implementation
  • Maintains separation between sleep initiation and stopping

⚠️ Minor Areas for Improvement

1. Engine Driver Alarm Implementation Gap

Location: packages/core/src/drivers/engine/actor-driver.ts:182-186

async setAlarm(actor: AnyActorInstance, timestamp: number): Promise<void> {
    // TODO: Set timeout
    // TODO: Use alarm on sleep  
    // TODO: Send alarm to runner
}

Impact: Alarms are not fully implemented in engine driver, which could affect sleep timing accuracy in production environments.

2. Missing JSDoc for New Config Options

Location: packages/core/src/actor/config.ts:73-74
The new noSleep and sleepTimeout options lack documentation comments explaining their purpose and behavior.

3. Engine Driver Sleep Error Handling

Location: packages/core/src/drivers/engine/actor-driver.ts:352-354

sleep(actorId: string) {
    this.#runner.sleepActor(actorId); // Could potentially fail
}

Recommendation: Consider adding error handling since sleepActor() could potentially fail.


🎯 Final Assessment

This is an exceptionally well-designed and implemented feature that adds significant value to RivetKit. The implementation demonstrates:

Major Strengths

  • Comprehensive architecture: Clean separation of concerns with proper driver abstraction
  • Robust implementation: Proper state management, timer handling, and lifecycle integration
  • Excellent test coverage: Thorough test suite covering various sleep scenarios
  • Performance benefits: Significant resource conservation potential for production deployments
  • Backward compatibility: Optional feature that doesn't impact existing functionality
  • Production ready: Well-thought-out defaults and configuration options

Technical Excellence

  • Smart activity detection: Considers all types of actor activity (connections, raw requests, WebSockets)
  • Proper timer management: Fixed critical bug and implements correct timeout handling
  • Driver flexibility: Optional sleep support allows different backends to implement as appropriate
  • Configuration design: Sensible defaults with clear configuration options

Overall Rating: ✅ Excellent - Ready for Production

This feature will significantly improve resource efficiency for RivetKit deployments, especially beneficial for platforms handling many actors with varying activity levels. The implementation quality is outstanding and demonstrates deep understanding of the actor lifecycle and resource management concerns.

Recommendation: Approve and merge. The minor improvements suggested above can be addressed in future iterations if needed, but they don't block the core functionality.


Comment on lines 351 to 363
while (entry.queuedWrite) {
// Remove pending write resolver so we can write a new write resolver for the next queued operation
//
// If we read entry.pendingWriteResolver directly, we would be resolving *all* waiting promises, not just the ones for this specific queued write
const pendingWriteResolver = entry.pendingWriteResolver;
entry.pendingWriteResolver = undefined;

const writeOperation = entry.queuedWrite;
entry.queuedWrite = undefined;
try {
await writeOperation();
} catch (err) {
logger().error("failed to write state", { err: stringifyError(err) });
}

// Resolve all currently waiting writes after this operation completes
pendingWriteResolver?.resolve();
}
Copy link

Choose a reason for hiding this comment

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

There appears to be a potential race condition in the write queue implementation. The current code sets entry.pendingWriteResolver = undefined before awaiting the write operation. If another writeActor() call occurs during this window, it will create a new resolver that won't be resolved by the current operation.

Consider restructuring to ensure all pending resolvers are properly handled:

// Store resolver before clearing it
const pendingWriteResolver = entry.pendingWriteResolver;
entry.pendingWriteResolver = undefined;

// Execute write operation
try {
  await writeOperation();
} catch (err) {
  logger().error("failed to write state", { err: stringifyError(err) });
}

// Resolve after operation completes
pendingWriteResolver?.resolve();

This pattern ensures that any new write requests that come in during the operation will create a new resolver that will be handled by the next iteration of the loop.

Spotted by Diamond

Fix in Graphite


Is this helpful? React 👍 or 👎 to let us know.

Comment on lines +1526 to +1572
async _sleep() {
invariant(this.#sleepingSupported, "sleeping not supported");
invariant(this.#actorDriver.sleep, "no sleep on driver");

if (this.#sleepCalled) {
logger().warn("already sleeping actor");
return;
}
this.#sleepCalled = true;

logger().info("actor sleeping");

// The actor driver should call stop when ready to stop
//
// This will call _stop once Pegboard responds with the new status
this.#actorDriver.sleep(this.#actorId);
}
Copy link

Choose a reason for hiding this comment

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

Consider adding error handling to the _sleep() method. Currently, if this.#actorDriver.sleep(this.#actorId) throws an exception, the actor will remain in an inconsistent state with #sleepCalled = true but still running. Either await the result and reset the flag on failure, or wrap the call in a try/catch block to maintain consistency.

Spotted by Diamond

Fix in Graphite


Is this helpful? React 👍 or 👎 to let us know.

Comment on lines 297 to 300
// Wait for actor to fully start before stopping it to avoid race conditions
if (actor.loadPromise) await actor.loadPromise.catch();
if (actor.startPromise?.promise) await actor.startPromise.promise.catch();
if (actor.writePromise) await actor.writePromise.catch();
Copy link

Choose a reason for hiding this comment

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

Race condition risk: There's a potential race condition in the sleep sequence. While the code waits for existing promises to complete, new operations could start between these awaits completing and the actor being marked as removed on line 303. Consider adding a flag at the beginning of the method to prevent new operations from starting, or implementing a lock mechanism to ensure atomic transitions to the sleeping state. This would prevent operations from continuing on a sleeping actor and avoid potential state corruption.

Suggested change
// Wait for actor to fully start before stopping it to avoid race conditions
if (actor.loadPromise) await actor.loadPromise.catch();
if (actor.startPromise?.promise) await actor.startPromise.promise.catch();
if (actor.writePromise) await actor.writePromise.catch();
// Mark actor as sleeping to prevent new operations from starting
actor.isSleeping = true;
// Wait for actor to fully start before stopping it to avoid race conditions
if (actor.loadPromise) await actor.loadPromise.catch();
if (actor.startPromise?.promise) await actor.startPromise.promise.catch();
if (actor.writePromise) await actor.writePromise.catch();

Spotted by Diamond

Fix in Graphite


Is this helpful? React 👍 or 👎 to let us know.

@NathanFlurry NathanFlurry force-pushed the 08-17-feat_core_actor_sleeping branch from 620dda3 to 804497f Compare September 10, 2025 17:53
@claude
Copy link

claude bot commented Sep 10, 2025

Claude finished @NathanFlurry's task —— View job


Code Review: Actor Sleeping Feature

Todo List:

  • Read repository guidelines (CLAUDE.md)
  • Analyze core actor changes (config, instance, driver)
  • Review driver implementations (engine, file-system)
  • Examine test suite changes and coverage
  • Check for potential bugs and security issues
  • Assess performance implications
  • Verify timer management bug fix from previous reviews
  • Provide comprehensive feedback

Overview

This PR introduces an actor sleeping mechanism that allows inactive actors to be put into a dormant state to conserve resources. The feature includes:

  • Configuration options: noSleep (default: false) and sleepTimeout (default: 30,000ms)
  • Sleep logic: Actors sleep when they have no active connections and exceed the timeout
  • Driver integration: Optional sleep() method added to ActorDriver interface
  • Connection awareness: Sleep timer resets on connection events and alarm triggers
  • Comprehensive test suite: New test fixtures and integration tests for sleep functionality

Critical Issue Resolved

Timer Management Bug Fixed

The timer management issue flagged by previous reviews has been resolved. Line 1522 in packages/core/src/actor/instance.ts now correctly uses clearTimeout() instead of clearInterval(). This was a critical bug that could prevent timers from being properly cleared.


🏗️ Architecture & Design

Excellent Design Decisions

  • Optional sleep support: #sleepingSupported property allows drivers to opt-in to sleeping (instance.ts:238-239)
  • Proper state management: #sleepCalled and #stopCalled flags prevent duplicate operations (instance.ts:133-137)
  • Comprehensive timer reset logic: #resetSleepTimer() properly handles cleanup and rescheduling (instance.ts:1511-1535)
  • Smart integration points: Sleep timer resets appropriately on:
    • New connections (instance.ts:901-902)
    • Alarm triggers (instance.ts:401-402)
    • Actor startup (instance.ts:337-338)
    • Connection removal (instance.ts:794-795)
    • Raw fetch completion (instance.ts:1251, 1271)
    • WebSocket events (instance.ts:1295, 1305)
  • Configuration schema: New sleep options properly integrated with sensible defaults (config.ts:73-74)

Driver Implementations

Engine Driver (packages/core/src/drivers/engine/actor-driver.ts:352-354):

  • Clean implementation that delegates to this.#runner.sleepActor(actorId)
  • Simple integration with runner infrastructure

File System Driver (packages/core/src/drivers/file-system/actor.ts:82-84):

  • Delegates to this.#state.sleepActor(actorId)
  • Full lifecycle handling in global state (global-state.ts:304-328)

🧪 Test Coverage - Outstanding

Comprehensive Test Suite Added

The PR includes excellent test coverage with:

New Test Fixtures (packages/core/fixtures/driver-test-suite/sleep.ts):

  • sleep actor with configurable timeout and state tracking
  • sleepWithLongRpc actor to test sleep behavior during long-running operations
  • Proper test configuration with SLEEP_TIMEOUT = 500ms for fast testing

Integration Tests (packages/core/src/driver-test-suite/tests/actor-sleep.ts):

  • Actor sleep persistence testing
  • Connection-based sleep prevention
  • Alarm-based sleep reset functionality
  • Long-running RPC sleep behavior
  • WebSocket sleep interaction testing

Test Fixture Improvements:

  • Removed hardcoded timeout values, making tests more maintainable
  • Simplified connection liveness, action timeout, and error handling test actors
  • Better configuration structure with flat options instead of nested objects

🔒 Security Analysis

✅ No security concerns identified:

  • Doesn't expose new attack surfaces
  • Maintains proper actor isolation
  • Uses existing authentication flows
  • No privilege escalation risks
  • Sleep functionality is properly gated behind configuration options
  • Proper validation of sleep conditions prevents unintended sleep states

🚀 Performance Implications

Excellent Performance Benefits

  • Resource conservation: Inactive actors can be suspended, significantly reducing memory/CPU usage
  • Scalability improvement: Allows platforms to handle many more actors by suspending inactive ones
  • Configurable timing: 30-second default provides excellent balance between responsiveness and resource savings
  • Smart activity detection: Considers multiple activity types:
    • Active connections (instance.ts:1542-1544)
    • In-flight raw fetches (instance.ts:1546-1547)
    • Open raw WebSocket connections (instance.ts:1549-1550)

Performance Considerations

  • Minimal overhead: Timer management adds only small constant overhead per actor
  • Connection tracking: Existing connection status checks reused efficiently
  • State persistence: Proper state handling before sleep ensures no data loss

📋 Code Quality & Best Practices

Outstanding Implementation Quality

  • Well-structured configuration: New sleep options properly integrated into existing config schema
  • Excellent separation of concerns: Sleep logic cleanly contained in instance, driver interface extended appropriately
  • Consistent naming: Follows established camelCase conventions throughout
  • Proper lifecycle integration: Sleep functionality seamlessly integrated with existing actor lifecycle
  • Defensive programming: Proper use of invariant() for runtime checks (instance.ts:1557-1558)
  • Clear documentation: Good JSDoc comments on lifecycle hooks mentioning sleep behavior (config.ts:320-329)

Sleep Logic Implementation

The _sleep() method (instance.ts:1556-1572) is well-implemented:

  • Proper guard conditions to prevent duplicate sleep calls
  • Clear logging for debugging
  • Delegates to driver for actual sleep implementation
  • Maintains separation between sleep initiation and stopping

⚠️ Minor Areas for Improvement

1. Engine Driver Alarm Implementation Gap

Location: packages/core/src/drivers/engine/actor-driver.ts:182-186

async setAlarm(actor: AnyActorInstance, timestamp: number): Promise<void> {
    // TODO: Set timeout
    // TODO: Use alarm on sleep  
    // TODO: Send alarm to runner
}

Impact: Alarms are not fully implemented in engine driver, which could affect sleep timing accuracy in production environments.

2. Missing JSDoc for New Config Options

Location: packages/core/src/actor/config.ts:73-74
The new noSleep and sleepTimeout options lack documentation comments explaining their purpose and behavior.

3. Engine Driver Sleep Error Handling

Location: packages/core/src/drivers/engine/actor-driver.ts:352-353

sleep(actorId: string) {
    this.#runner.sleepActor(actorId); // Could potentially fail
}

Recommendation: Consider adding error handling since sleepActor() could potentially fail.


🎯 Final Assessment

This is an exceptionally well-designed and implemented feature that adds significant value to RivetKit. The implementation demonstrates:

Major Strengths

  • Comprehensive architecture: Clean separation of concerns with proper driver abstraction
  • Robust implementation: Proper state management, timer handling, and lifecycle integration
  • Excellent test coverage: Thorough test suite covering various sleep scenarios
  • Performance benefits: Significant resource conservation potential for production deployments
  • Backward compatibility: Optional feature that doesn't impact existing functionality
  • Production ready: Well-thought-out defaults and configuration options

Technical Excellence

  • Smart activity detection: Considers all types of actor activity (connections, raw requests, WebSockets)
  • Proper timer management: Fixed critical bug and implements correct timeout handling
  • Driver flexibility: Optional sleep support allows different backends to implement as appropriate
  • Configuration design: Sensible defaults with clear configuration options

Overall Rating: ✅ Excellent - Ready for Production

This feature will significantly improve resource efficiency for RivetKit deployments, especially beneficial for platforms handling many actors with varying activity levels. The implementation quality is outstanding and demonstrates deep understanding of the actor lifecycle and resource management concerns.

Recommendation: Approve and merge. The minor improvements suggested above can be addressed in future iterations if needed, but they don't block the core functionality.


@linear
Copy link

linear bot commented Sep 10, 2025

KIT-198 Actor sleeping

@graphite-app
Copy link

graphite-app bot commented Sep 11, 2025

Merge activity

  • Sep 11, 10:34 PM UTC: NathanFlurry added this pull request to the Graphite merge queue.
  • Sep 11, 10:35 PM UTC: CI is running for this pull request on a draft pull request (#1206) due to your merge queue CI optimization settings.
  • Sep 11, 10:35 PM UTC: Merged by the Graphite merge queue via draft PR: #1206.

graphite-app bot pushed a commit that referenced this pull request Sep 11, 2025
@graphite-app graphite-app bot closed this Sep 11, 2025
@graphite-app graphite-app bot deleted the 08-17-feat_core_actor_sleeping branch September 11, 2025 22:35
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant