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: [...] │ └─────────────────┘ └───────────────────┘ └────────────────────┘ └─────────────────┘- Context Ingestion: Input data is received as an arbitrary JavaScript object or deserialized JSON record.
- Safe Field Resolution: Dot-notation paths (
"customer.profile.tier") are resolved recursively. If any intermediate parent is missing, it resolves toundefinedwithout throwing runtime exceptions. Prototype access (__proto__) is strictly rejected. - Condition Execution: Conditions evaluate according to strict AST operator semantics.
- Short-Circuit Traversal:
- In an
andgate: The moment any condition resolvesfalse, evaluation halts immediately. Remaining branches are skipped. - In an
orgate: The moment any condition resolvestrue, evaluation halts immediately. Remaining branches are skipped.
- In an
- 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:
| Method | Throughput | Return Type | Best For |
|---|---|---|---|
compileRule(rule) | ~3,524,570 ops/s | (data) => boolean | High-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 bootconst isFraudulent = compileRule(fraudShield);
// 🚀 Evaluates in ~280 nanoseconds with ZERO runtime AST traversal overheadapp.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
| Operator | Type | Description | Example |
|---|---|---|---|
eq | Binary | Strict equality (===) | where("status").eq("active") |
neq | Binary | Strict inequality (!==) | where("role").neq("guest") |
gt | Binary | Greater than (>) | where("amount").gt(100) |
gte | Binary | Greater or equal (>=) | where("age").gte(18) |
lt | Binary | Less than (<) | where("riskScore").lt(50) |
lte | Binary | Less or equal (<=) | where("retries").lte(3) |
in | Binary | Value included in array | where("country").in(["US", "CA", "GB"]) |
notIn | Binary | Value excluded from array | where("tier").notIn(["banned", "suspended"]) |
between | Ternary | Inclusive numeric range | where("age").between(21, 65) |
contains | Binary | Substring match | where("title").contains("Pro") |
startsWith | Binary | String prefix check | where("sku").startsWith("PROMO-") |
endsWith | Binary | String suffix check | where("email").endsWith("@corp.com") |
isNull | Unary | Value is null or undefined | where("deletedAt").isNull() |
isNotNull | Unary | Value is defined and not null | where("verifiedAt").isNotNull() |
Array Operators
| Operator | Description | Example |
|---|---|---|
arrayContains | Array contains specified value | where("user.tags").arrayContains("vip") |
notArrayContains | Array does not contain specified value | where("user.flags").notArrayContains("blocked") |
arrayContainsAny (some) | Array contains at least one of the target values | where("user.permissions").arrayContainsAny(["admin", "billing"]) |
arrayContainsAll (every) | Array contains all of the target values | where("account.features").arrayContainsAll(["sso", "audit_logs"]) |
arrayContainsNone (none) | Array contains none of the target values | where("user.flags").arrayContainsNone(["banned", "suspended"]) |
arrayIsEmpty | Array has zero elements (length === 0) | where("team.pendingInvites").arrayIsEmpty() |
arrayIsNotEmpty | Array has one or more elements (length > 0) | where("cart.items").arrayIsNotEmpty() |
arrayLength | Array length strictly equals count | where("cart.items").arrayLength(3) |
arrayLengthGte | Array length is greater than or equal | where("cart.items").arrayLengthGte(1) |
arrayLengthLte | Array length is less than or equal | where("order.attachments").arrayLengthLte(5) |
arrayLengthGt | Array length is strictly greater | where("team.members").arrayLengthGt(0) |
arrayLengthLt | Array length is strictly less | where("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}}").
| Operator | Description | Example |
|---|---|---|
before | Timestamp is chronologically before target | where("order.createdAt").before("2026-12-31") |
after | Timestamp is chronologically after target | where("user.verifiedAt").after("2026-01-01") |
olderThan | Timestamp is older than relative duration | where("user.registeredAt").olderThan("90 days") |
withinLast | Timestamp falls within recent duration window | where("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: true8. 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 yieldsfalse. 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 tofalsewithout 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, orconstructorkeys is strictly blocked at the AST and engine resolution level.