Skip to content

Cost Estimation and Sandboxing

github-actions[bot] edited this page Nov 29, 2026 · 1 revision

Cost Estimation & Sandboxing

When evaluating expressions authored by end users (webhook filters, policy rules, query predicates), you should defend against both compile-time complexity bombs (deep nested comprehensions) and runtime resource exhaustion.

Celly.Json pairs JSON Schema size bounds with Celly's built-in static cost estimator (CelEnv.EstimateCost) and runtime EvalLimits.


Static Cost Estimation from JSON Schema

JSON Schema already lets you declare bounds on inputs:

  • minLength / maxLength for strings
  • minItems / maxItems for arrays (including items bounds for comprehension iterators)
  • minProperties / maxProperties for objects

JsonSchemaTypeProvider.CostEstimator automatically translates those bounds into a Celly ICostEstimator:

const string schema = """
    {
      "type": "object",
      "properties": {
        "name": { "type": "string", "minLength": 1, "maxLength": 64 },
        "roles": {
          "type": "array",
          "minItems": 0,
          "maxItems": 10,
          "items": { "type": "string", "maxLength": 32 }
        }
      }
    }
    """;

var provider = JsonSchemaTypeProvider.FromJson(schema);
CelEnv env = JsonSchemaEnv.Create(schema);

var parsed = env.Parse("roles.exists(r, r == 'admin') && name.startsWith('A')");
var check = env.Check(parsed.Ast!);
if (check.HasErrors)
{
    throw new InvalidOperationException(string.Join("; ", check.Issues));
}

// Compute a bounded worst-case cost BEFORE ever running the expression
CostEstimate cost = env.EstimateCost(parsed.Ast!, provider.CostEstimator);

if (cost.IsUnbounded || cost.Max > 1_000)
{
    throw new InvalidOperationException($"Expression exceeds cost budget: {cost}");
}

Variable-Prefixed Cost Estimation

If you created your environment with JsonSchemaEnv.CreateForVariable("req", schema), scope the estimator with .ForVariable("req"):

JsonSchemaCostEstimator estimator = provider.CostEstimator.ForVariable("req");
CostEstimate cost = env.EstimateCost(parsed.Ast!, estimator);

Runtime EvalLimits

Every EvalJson*, FilterJsonArray, and FilterJsonLines overload accepts an optional EvalLimits parameter from Celly to enforce runtime execution caps (such as maximum recursion depth or comprehension iterations):

var limits = new EvalLimits
{
    MaxComprehensionIterations = 1_000,
};

bool allowed = program.EvalJsonBool(doc, limits: limits);

Combining JSON Schema static type checking + JsonSchemaCostEstimator + runtime EvalLimits gives you defense-in-depth for untrusted rules.

Clone this wiki locally