Class MongoSandboxExecutionGuard

java.lang.Object
io.agentscope.extensions.mongodb.sandbox.MongoSandboxExecutionGuard
All Implemented Interfaces:
io.agentscope.harness.agent.sandbox.SandboxExecutionGuard, AutoCloseable

public final class MongoSandboxExecutionGuard extends Object implements io.agentscope.harness.agent.sandbox.SandboxExecutionGuard, AutoCloseable
MongoDB-based SandboxExecutionGuard.

Uses a dedicated MongoDB collection as a distributed lock mechanism. Each lock is a document with a unique _id derived from the SandboxIsolationKey and a TTL index on expiresAt to auto-release stale locks.

Lock acquisition uses a two-step approach for correct mutual exclusion:

  1. Attempt insertOne — atomic under the unique _id index; only one concurrent caller succeeds.
  2. If the lock document already exists (duplicate key), attempt findOneAndUpdate (non-upsert) with a filter that matches only when expiresAt <= now — reclaiming an expired lock.

Acquisition polls until the lock is obtained or the acquisition timeout ( lockTimeout) expires. The lock document itself lives for leaseTtl; while the returned SandboxLease is open, a background watchdog renews the lease every leaseTtl / 3 by pushing expiresAt forward, so an execution that outlives the initial TTL does not lose its own lock to reclamation. If renewal stops working (lock deleted or stolen), the watchdog only warns — like the Redis guard, TTL expiry remains a safety valve against permanent deadlock rather than a correctness guarantee.

Each acquisition generates a random UUID token that is written into the lock document. Renewal and release filter by this token, not by a process-level identifier, so that two guard instances in the same JVM (or two processes with the same PID) cannot accidentally release each other's locks. This mirrors the Redis guard's SET NX + Lua CAS token pattern.

The renewal executor uses a fixed-size thread pool (2 threads) so that a slow updateOne on one lease does not block renewal of other leases. The guard implements AutoCloseable and should be closed by DistributedStore to shut down the executor when the store is closed.

  • Method Details

    • builder

      public static MongoSandboxExecutionGuard.Builder builder(com.mongodb.client.MongoClient mongoClient)
      Creates a new builder.
      Parameters:
      mongoClient - the MongoDB client
      Returns:
      a new builder
    • tryEnter

      public io.agentscope.harness.agent.sandbox.SandboxLease tryEnter(io.agentscope.harness.agent.sandbox.SandboxIsolationKey key) throws InterruptedException
      Specified by:
      tryEnter in interface io.agentscope.harness.agent.sandbox.SandboxExecutionGuard
      Throws:
      InterruptedException
    • close

      public void close()
      Specified by:
      close in interface AutoCloseable