Skip to content

Sandbox & Security

Worker code runs in a restricted Python sandbox. This page documents what is and isn't allowed.

Execution Model

  • Each worker runs as an isolated subprocess
  • Code is loaded via exec() with restricted builtins
  • The ctx object is injected as a global variable
  • Each tick() has a 60 second timeout
  • Import restrictions are enforced at runtime

Allowed Built-in Functions

The following Python builtins are available in worker code:

Math & Logic

abs, all, any, divmod, max, min, pow, round, sum

Types & Collections

bool, chr, dict, float, format, frozenset, hex, id, int, iter, len, list, oct, ord, range, repr, reversed, set, slice, sorted, str, super, tuple, type, zip

Iteration & Filtering

enumerate, filter, map, next

Introspection

getattr, hasattr, hash, isinstance, issubclass

Output

print (output goes to worker logs)

Constants

True, False, None

Exceptions

Exception, ValueError, TypeError, KeyError, IndexError, RuntimeError, StopIteration, ZeroDivisionError

Allowed Imports

You can import these modules in your worker code:

ModuleDescription
mathMathematical functions
statisticsStatistical functions
datetimeDate and time handling
jsonJSON encoding/decoding
collectionsSpecialized containers (defaultdict, Counter, etc.)
timeTime functions (sleep, time, etc.)
reRegular expressions
functoolsHigher-order functions (reduce, lru_cache, etc.)
itertoolsIterator building blocks
decimalDecimal fixed-point arithmetic
hashlibSecure hash algorithms
hmacHMAC message authentication
base64Base64 encoding/decoding
copyShallow and deep copy
randomRandom number generation
numpyNumerical computing (if installed)
pandasData analysis (if installed)

Import Example

python
import json
import datetime
from collections import defaultdict
import math

def tick(ctx):
    now = datetime.datetime.now()
    data = json.dumps({"time": str(now), "pi": math.pi})
    ctx.log.info(data)

Blocked

The following are not allowed in worker code:

Blocked Built-ins

  • open() -- use ctx.files instead
  • exec(), eval(), compile() -- no dynamic code execution
  • __import__() -- replaced with restricted version

Blocked Modules

  • os, sys, subprocess -- no system access
  • socket, urllib, http -- use ctx.http instead
  • pathlib, shutil, glob -- use ctx.files instead
  • Any module not in the allowed list above

Blocked Access

  • File system (use ctx.files)
  • Network (use ctx.http, ctx.bybit, ctx.telegram, etc.)
  • Environment variables
  • Process management
  • Thread/multiprocessing

Attempting Blocked Operations

If you try to import a blocked module:

python
import os  # ImportError: Import of os is not allowed in worker sandbox.
           # Allowed: ['base64', 'collections', 'copy', 'datetime', 'decimal',
           #           'functools', 'hashlib', 'hmac', 'itertools', 'json',
           #           'math', 'random', 're', 'statistics', 'time']

Memory & Resource Limits

  • Tick timeout: 60 seconds per tick
  • Log message size: max 4000 characters per message
  • Log batch size: 20 messages (auto-flushed)
  • File storage: 100 MB per workspace
  • Single file read: max 50 KB
  • HTTP request timeout: 30 seconds
  • State value size: limited by Redis (practical limit: ~512 KB per value)

Best Practices

  1. Keep ticks fast -- don't do heavy computation in a single tick. Split work across multiple ticks using ctx.state.

  2. Handle errors gracefully -- always check for "error" keys in API responses.

  3. Use state for persistence -- don't rely on global variables (they reset on restart). Use ctx.state.set() / ctx.state.get().

  4. Limit data size -- trim lists and dicts to reasonable sizes. Don't store unlimited history.

  5. Log meaningfully -- use ctx.log.info() for important events, ctx.log.debug() for verbose output.

AiSpinner Documentation