Class: ActiveMatrix::Agent::Jobs::MemoryReaper

Inherits:
ActiveMatrix::ApplicationJob show all
Defined in:
app/models/active_matrix/agent/jobs/memory_reaper.rb

Overview

Background job responsible for harvesting dead agent memories from the system.

This job systematically harvests dead memory entries to prevent database bloat and maintain optimal performance. It operates as a scheduled reaper process that runs automatically when agent memories reach their expiration time.

The job performs the following operations:

  1. Identifies dead agent memory records based on their expires_at timestamp

  2. Harvests dead entries from both database and cache layers

  3. Logs harvesting statistics for monitoring and debugging purposes

  4. Handles harvesting failures gracefully without affecting system stability

Usage:

# Schedule immediate harvesting
ActiveMatrix::Agent::Jobs::MemoryReaper.perform_later

# Schedule harvesting for specific time
ActiveMatrix::Agent::Jobs::MemoryReaper.set(wait_until: 1.hour.from_now).perform_later

Instance Method Summary collapse

Instance Method Details

#performObject

Performs the memory reaping operation with comprehensive error handling



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'app/models/active_matrix/agent/jobs/memory_reaper.rb', line 29

def perform
  ActiveMatrix.logger.info 'Starting agent memory reaping operation'

  reaping_stats = {
    agent_memories_reaped: 0,
    cache_entries_cleared: 0,
    errors_encountered: 0
  }

  begin
    # Harvest dead agent memories
    reaping_stats[:agent_memories_reaped] = harvest_dead_agent_memories

    # Clear associated cache entries
    reaping_stats[:cache_entries_cleared] = clear_expired_cache_entries

    ActiveMatrix.logger.info "Memory reaping completed successfully: #{reaping_stats}"
  rescue StandardError => e
    reaping_stats[:errors_encountered] += 1
    ActiveMatrix.logger.error "Memory reaping failed: #{e.message}"
    ActiveMatrix.logger.error e.backtrace.join("\n")

    # Re-raise to ensure job is marked as failed for retry
    raise e
  end

  reaping_stats
end