Skip to content

Rule Engine & Evaluation Lifecycle

Qarar’s evaluation engine is designed for ultra-high throughput, deterministic execution, and zero runtime memory allocations for primitive conditions.


1. Evaluation Lifecycle

Every time a rule is evaluated against a data payload, it follows a strict 4-stage pipeline:

1. INPUT PAYLOAD 2. SAFE RESOLUTION 3. SHORT-CIRCUIT EVAL 4. OUTPUT & TRACE
┌─────────────────┐ ┌───────────────────┐ ┌────────────────────┐ ┌─────────────────┐
│ { customer: │ ─────► │ customer.age ➔ 24 │ ────► │ 24 >= 18 ➔ TRUE │ ────► │ result: true │
│ { age: 24 } } │ │ (guarded path) │ │ (short-circuits) │ │ trace: [...] │
└─────────────────┘ └───────────────────┘ └────────────────────┘ └─────────────────┘
  1. Context Ingestion: Input data is received as an arbitrary JavaScript object or deserialized JSON record.
  2. Safe Field Resolution: Dot-notation paths ("customer.profile.tier") are resolved recursively. If any intermediate parent is missing, it resolves to undefined without throwing runtime exceptions. Prototype access (__proto__) is strictly rejected.
  3. Condition Execution: Conditions evaluate according to strict AST operator semantics.
  4. Short-Circuit Traversal:
    • In an and gate: The moment any condition resolves false, evaluation halts immediately. Remaining branches are skipped.
    • In an or gate: The moment any condition resolves true, evaluation halts immediately. Remaining branches are skipped.
  5. Trace Recording: Condition states, evaluated paths, expected thresholds, and actual values are recorded for explainability.

2. The Three Execution Modes

Qarar provides three distinct execution functions optimized for different operational needs:

MethodThroughputReturn TypeBest For
compileRule(rule)~3,524,570 ops/s(data) => booleanHigh-throughput APIs, Kafka consumers, microservices, batch loops
evaluate(rule, data)~2,537,626 ops/s{ result, trace }Telemetry pipelines, audit logs, debug modes
checkRule(rule, data)~22,478 ops/s{ result, valid, reasons, trace }User-facing forms, customer support tools, admin panels

3. Pre-Compiled Closures (compileRule)

When running in production services, evaluating the exact same rule AST thousands of times per second with standard tree traversal involves repetitive object property checks.

compileRule compiles the AST structure into an optimized, pure JavaScript closure once during server initialization:

import { compileRule, rule } from "@qarar/sdk";
const fraudShield = rule("Fraud Check")
.where("risk.score").gte(700)
.and("transaction.amount").gte(5000)
.build();
// ✅ Compile once during service boot
const isFraudulent = compileRule(fraudShield);
// 🚀 Evaluates in ~280 nanoseconds with ZERO runtime AST traversal overhead
app.post("/transaction", (req, res) => {
const flagged = isFraudulent(req.body);
if (flagged) {
return res.status(403).json({ error: "Transaction flagged by risk engine" });
}
res.json({ status: "approved" });
});

4. Deep Inspection (evaluate)

If your service needs to record structured audit logs for compliance without generating human string sentences:

import { evaluate } from "@qarar/sdk";
const { result, trace } = evaluate(fraudShield, incomingTransaction);
console.log("Evaluation Outcome:", result);
console.log("Recorded Trace Tree:", trace);

5. All-in-One Validator (checkRule)

When processing user submissions or requests where you need to report human-friendly errors back to a client:

import { checkRule } from "@qarar/sdk";
const check = checkRule(fraudShield, incomingTransaction);
if (!check.result) {
console.log("Reasons for failure:", check.reasons);
// ➔ ["risk.score: 640 is not >= 700"]
}

6. Supported Operators

Scalar & String Operators

OperatorTypeDescriptionExample
eqBinaryStrict equality (===)where("status").eq("active")
neqBinaryStrict inequality (!==)where("role").neq("guest")
gtBinaryGreater than (>)where("amount").gt(100)
gteBinaryGreater or equal (>=)where("age").gte(18)
ltBinaryLess than (<)where("riskScore").lt(50)
lteBinaryLess or equal (<=)where("retries").lte(3)
inBinaryValue included in arraywhere("country").in(["US", "CA", "GB"])
notInBinaryValue excluded from arraywhere("tier").notIn(["banned", "suspended"])
betweenTernaryInclusive numeric rangewhere("age").between(21, 65)
containsBinarySubstring matchwhere("title").contains("Pro")
startsWithBinaryString prefix checkwhere("sku").startsWith("PROMO-")
endsWithBinaryString suffix checkwhere("email").endsWith("@corp.com")
isNullUnaryValue is null or undefinedwhere("deletedAt").isNull()
isNotNullUnaryValue is defined and not nullwhere("verifiedAt").isNotNull()

Array Operators

OperatorDescriptionExample
arrayContainsArray contains specified valuewhere("user.tags").arrayContains("vip")
notArrayContainsArray does not contain specified valuewhere("user.flags").notArrayContains("blocked")
arrayContainsAny (some)Array contains at least one of the target valueswhere("user.permissions").arrayContainsAny(["admin", "billing"])
arrayContainsAll (every)Array contains all of the target valueswhere("account.features").arrayContainsAll(["sso", "audit_logs"])
arrayContainsNone (none)Array contains none of the target valueswhere("user.flags").arrayContainsNone(["banned", "suspended"])
arrayIsEmptyArray has zero elements (length === 0)where("team.pendingInvites").arrayIsEmpty()
arrayIsNotEmptyArray has one or more elements (length > 0)where("cart.items").arrayIsNotEmpty()
arrayLengthArray length strictly equals countwhere("cart.items").arrayLength(3)
arrayLengthGteArray length is greater than or equalwhere("cart.items").arrayLengthGte(1)
arrayLengthLteArray length is less than or equalwhere("order.attachments").arrayLengthLte(5)
arrayLengthGtArray length is strictly greaterwhere("team.members").arrayLengthGt(0)
arrayLengthLtArray length is strictly lesswhere("team.pendingInvites").arrayLengthLt(10)

Date & Time Operators

Supports ISO 8601 UTC strings ("2026-01-15T00:00:00Z"), Epoch timestamps, relative duration strings ("30 days", "12 hours", "7 d", "1 year"), and dynamic field expressions with optional offsets ("{{subscription.startDate + 14 days}}").

OperatorDescriptionExample
beforeTimestamp is chronologically before targetwhere("order.createdAt").before("2026-12-31")
afterTimestamp is chronologically after targetwhere("user.verifiedAt").after("2026-01-01")
olderThanTimestamp is older than relative durationwhere("user.registeredAt").olderThan("90 days")
withinLastTimestamp falls within recent duration windowwhere("event.timestamp").withinLast("24 hours")

7. Dynamic Two-Sided Field Comparisons ({{ field.path }})

In real-world business logic, rules frequently need to compare two dynamic attributes from the incoming payload rather than a static literal (e.g. cart.total <= customer.creditLimit or requestedSeats <= venue.availableSeats).

Canonical {{ field.path }} Standard

Qarar adopts {{ field.path }} as the single canonical syntax for referencing dynamic fields:

  • Universal Clarity: Standardized across developer tools (Jinja, Handlebars, Retool) and non-technical LiveOps / CMS workflows (Shopify Liquid, Mailchimp merge tags).
  • Ambiguity-Free: Avoids collision with hashtags, hex codes (#1024, #FFFFFF), or CSS selectors.
  • Bi-directional: Supported transparently across the Fluent TypeScript SDK, the Visual React Builder, in-memory execution, and SQL/MongoDB database compilers.

Two-Sided Date Comparisons & Subscription Offsets

Dynamic field comparisons apply seamlessly to date and time fields, allowing automated verification of subscription trial periods, payment dates, and SLA compliance:

import { rule, field, evaluate } from "@qarar/sdk";
// 1. Direct two-sided date comparison:
const trialRule = rule("Active Trial Check")
.where("subscription.paymentDate")
.before("{{subscription.trialEndsAt}}") // Or: .before(field("subscription.trialEndsAt"))
.build();
// 2. Dynamic date with duration offset (+14 days free trial offer):
const offerRule = rule("Offer Verification")
.where("subscription.endDate")
.after("{{subscription.startDate + 14 days}}")
.build();
const result = evaluate(offerRule, {
subscription: {
startDate: "2026-11-01T00:00:00Z",
endDate: "2026-11-20T00:00:00Z"
}
});
// ➔ result: true (evaluated in 0.48 µs)
import { rule, evaluate } from "@qarar/sdk";
// Using the SDK builder:
const creditRule = rule("Credit Limit Check")
.where("cart.total")
.lte("{{customer.creditLimit}}") // Or: .lte(field("customer.creditLimit"))
.build();
// Evaluates in 0.46 µs:
const result = evaluate(creditRule, {
cart: { total: 450 },
customer: { creditLimit: 500 }
});
// ➔ result: true

8. Strict Type Safety & Edge Cases

JavaScript is infamous for loose type coercion pitfalls (e.g. [] == false, "10" < "2"). Qarar strictly prevents these failure modes:

  • Strict Equality (eq): Comparing an array with a scalar or string strictly yields false. Two arrays are compared by content elements, not reference address.
  • Strict Numeric Comparisons (gt, gte, lt, lte): Both sides must strictly resolve to valid finite numbers. Comparing a string with a number or an array with a number gracefully evaluates to false without throwing an exception.
  • Graceful Null & Undefined Handling: If a referenced dynamic field ({{customer.creditLimit}}) does not exist on the payload, the comparison safely fails (false) without crashing the execution loop.
  • Prototype Pollution Prevention: Direct access to __proto__, prototype, or constructor keys is strictly blocked at the AST and engine resolution level.