Skip to content

RulesEngine: add JSON Logic predicate evaluator#3482

Merged
ajpallares merged 72 commits into
mainfrom
pallares/json-logic-evaluator
May 28, 2026
Merged

RulesEngine: add JSON Logic predicate evaluator#3482
ajpallares merged 72 commits into
mainfrom
pallares/json-logic-evaluator

Conversation

@ajpallares

@ajpallares ajpallares commented May 14, 2026

Copy link
Copy Markdown
Member

Resolves SDK-4326

Checklist

  • Unit tests added

Motivation

First slice of the JSON Logic rules engine.

Description

  • Adds Logger, RuleError, Value, Evaluator, and operators/ with the MVP set: var, missing, ==, !=, ===, !==, !, !!, and, or, if.
  • RulesEngine and RulesEngineLogger are public so the host SDK can swap the logger at integration time; everything else stays module-internal.
  • Test-only ValueJsonHelper lets predicates be authored the way they appear in rule artifacts; production callers will build Value trees from the host SDK's own JSON parser.

Note

Medium Risk
New rule-evaluation semantics will gate SDK behavior; subtle JS/json-logic-js alignment (equality, missing vars, short-circuit) is heavily tested but still a correctness-sensitive surface for future rule payloads.

Overview
Introduces the first JSON Logic predicate evaluator in rules-engine-internal: callers pass a typed Value tree plus a variable map; Evaluator.evaluate returns whether the predicate is truthy.

RulesEngine is now a public namespace with a swappable RulesEngineLogger (setLogger); diagnostics (e.g. missing var) go through it instead of threading loggers everywhere. Value models JSON-shaped data with JSON Logic truthiness and JS-aligned looseEq / strictEq (including array/object stringify coercion). Operators dispatches the MVP set: var, missing, == / != / === / !==, ! / !! / and / or / if (short-circuit where required). Unknown operators throw RuleError.UnsupportedOperator.

Tests add ValueJsonHelper (test-only JSON → Value), CapturingLoggerRule, and broad unit coverage for evaluators, accessors, equality, and logic. Production parsing stays outside this module; the smoke RulesEngineTest is removed.

Reviewed by Cursor Bugbot for commit ffa209d. Bugbot is set up for automated code reviews on this repo. Configure here.

ajpallares and others added 11 commits May 14, 2026 10:21
Sets up the plumbing for an internal rules-engine module that the SDK can
depend on without coupling to :purchases or :ui:revenuecatui. Includes:

- New :rules-engine Gradle module using the existing
  `revenuecat-public-library` convention plugin (Metalava, Dokka, Kover,
  Vanniktech publish, baseline profile, explicit-API mode).
- Single-flavor (`apis { defaults }`); no `billingclient` dimension since
  the rules engine has no Billing Client dependency. Publishes a single
  `purchases-rules-engine` artifact instead of a bc7/bc8 split.
- Module-scoped `mavenPublishing.configure(AndroidSingleVariantLibrary("defaultsRelease"))`
  override so the global `ANDROID_VARIANT_TO_PUBLISH=defaultsBc8Release`
  default doesn't apply here.
- Placeholder `RulesEngine` Kotlin object plus a smoke test so CI exercises
  the module from day one. No actual rules logic yet.
- BOM constraint added so consumers using the BOM get an aligned version.

Co-authored-by: Cursor <cursoragent@cursor.com>
Every public declaration in this module is intended to be visible only
to the rest of the SDK (`:purchases`, `:ui:revenuecatui`, hybrid
bridges), not to app developers, so put the opt-in gate in place from
day one instead of bolting it on later.

Sibling annotation, not the existing one
----------------------------------------

`@InternalRevenueCatAPI` lives in `:purchases` and we deliberately
keep `:rules-engine` standalone (no dependency on `:purchases`), so
this defines a parallel `@InternalRulesEngineAPI` in
`com.revenuecat.purchases.rules` with identical
`@RequiresOptIn(level=ERROR)` semantics. Two annotations doing the
same job is mildly redundant but unambiguous in the IDE and avoids
coupling the two modules just for an annotation.

Changes
-------

- New `InternalRulesEngineAPI.kt` mirroring the shape of
  `:purchases`'s `InternalRevenueCatAPI`.
- `RulesEngine` object annotated with `@InternalRulesEngineAPI`.
- Test class opts in with `@OptIn(InternalRulesEngineAPI::class)`.
- Metalava configured (per-module) to add
  `com.revenuecat.purchases.rules.InternalRulesEngineAPI` to the
  hidden-annotations list, on top of the
  `com.revenuecat.purchases.InternalRevenueCatAPI` entry already added
  by the `revenuecat-public-library` convention plugin.
- `api.txt` regenerated: `RulesEngine` is now hidden; the annotation
  itself remains public so consumers can opt in.

Verified
--------

- `./gradlew :rules-engine:testDefaultsDebugUnitTest` ✔
- `./gradlew :rules-engine:metalavaCheckCompatibilityDefaultsRelease` ✔
- `./gradlew detektAll` ✔

Co-authored-by: Cursor <cursoragent@cursor.com>
Drop the explainer comment above the `mavenPublishing.configure(...)`
override in `rules-engine/build.gradle.kts` and the doc on
`InternalRulesEngineAPI`. The behavior is self-evident from the code
and the annotation already carries a `@RequiresOptIn` message.

Co-authored-by: Cursor <cursoragent@cursor.com>
…public API

Adds scripts/check-rules-engine-internal-only.sh which regenerates rules-engine/api.txt and asserts it contains only the @InternalRulesEngineAPI annotation declaration. Unlike a baseline diff, this check is intrinsic and cannot be silenced by regenerating api.txt.

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
…merge)

Co-authored-by: Cursor <cursoragent@cursor.com>
First slice of the JSON Logic rules engine in the new `:rules-engine`
module (built on top of the module skeleton from
`pallares/rules-engine-skeleton`). Pure Kotlin, no exported API
surface — every new declaration is module-`internal` so the engine can
land incrementally without changing `rules-engine/api.txt` or pulling
anything into the SDK's metalava signature.

What's in:

- `Logger.kt` — internal `RulesEngineLogger` interface + default
  `PrintlnLogger` (stderr) + test `CapturingLogger`. Kept internal so a
  future host-supplied logger can be adapted to the same interface
  without API churn.
- `Value.kt` — typed `Value` sealed class (`Null` / `BoolValue` /
  `IntValue` / `FloatValue` / `StringValue` / `ArrayValue` /
  `ObjectValue`), JSON Logic truthiness + loose (`==`) / strict (`===`)
  equality with type coercion.
- `RuleError.kt` — `RuleError` sealed `RuntimeException` (`Parse`,
  `TypeMismatch`, `UnsupportedOperator`).
- `Evaluator.kt` — top-level dispatcher; takes a typed `Value`
  predicate (no JSON parsing in the engine) and returns `Boolean`.
- `operators/` — MVP set: `var` (strict dot-path), `missing`, `==`,
  `!=`, `===`, `!==`, `!`, `!!`, `and`, `or`, `if`.
- Test source set adds a `helpers/ValueJsonHelper.kt` (`org.json` +
  `BigDecimal` scale check to preserve int-vs-decimal intent) so test
  predicates can be expressed as JSON literals — production callers
  will construct `Value` trees from the host SDK's own JSON parser.

Key decisions:

- **JSON parsing lives outside the engine.** The engine accepts a typed
  `Value` tree (the JSON-shaped sealed class is what cross-language
  bridges can express across the boundary). The `org.json`-backed JSON
  helper is gated to the test source set only via a new
  `testImplementation(libs.json)` dep.
- **Missing variables** resolve to `Null` and emit a warning, per JSON
  Logic spec. No `MissingVariable` subclass in v1; reserved for a
  future strict mode.
- **`var` lookup** uses strict dot-path navigation. Flat-key fallback
  considered and deferred — pure addition if we need it later.

Verification:

- `./gradlew :rules-engine:test` — 63 tests, 0 failures.
- `./gradlew :rules-engine:check` — `lint` + `metalavaCheckCompatibility`
  pass; `api.txt` unchanged because every new declaration is
  `internal`.
- `./gradlew detektAll` — clean.

Co-authored-by: Cursor <cursoragent@cursor.com>
@ajpallares ajpallares added the pr:feat A new feature label May 14, 2026
ajpallares and others added 10 commits May 14, 2026 18:28
- Gate the `mavenPublishing { ... }` configuration on the
  `com.vanniktech.maven.publish` plugin actually being applied.
  `ConfigureConditionalPublishing` in the convention plugin skips the
  publish plugin when `ANDROID_VARIANT_TO_PUBLISH` contains
  `customEntitlementComputation` (which `:rules-engine` doesn't have),
  so the unconditional block was breaking
  `./gradlew :purchases:publish -PANDROID_VARIANT_TO_PUBLISH=customEntitlementComputationBc8Release`
  — i.e. the "Deploying Custom Entitlements Computation version"
  fastlane step — with `Unresolved reference: mavenPublishing` while
  configuring `:rules-engine`.

- Suppress `:rules-engine` from `dokkaHtmlMultiModule`. The existing
  `HideInternalRevenueCatAPIPlugin` is hardcoded to
  `com.revenuecat.purchases.InternalRevenueCatAPI` and only applied to
  `:purchases`, so without this `RulesEngine` and `InternalRulesEngineAPI`
  would leak into the published docs at `docs/{version}/`. Every public
  symbol in this module is gated by `@InternalRulesEngineAPI`, so a
  dedicated docs page would be empty anyway — suppressing the module
  is simpler than generalizing the hide-plugin.

- Add `:rules-engine:metalavaGenerateSignatureDefaultsRelease` to
  `scripts/api-dump.sh`. The script previously only invoked the
  `Bc8`/`Bc7`/`customEntitlement` task names, so `:rules-engine`
  (single-flavor, no `billingclient` dimension) was never regenerated,
  meaning the committed `rules-engine/api.txt` couldn't act as a
  tripwire via `scripts/api-check.sh`. With this change a leaked
  non-internal API would show up as a diff in CI.

Verified:
- `:purchases:publish --dry-run -PANDROID_VARIANT_TO_PUBLISH=customEntitlementComputationBc8Release` now only fails on the unrelated `mavenCentralUsername`/`Password` credentials error.
- `:rules-engine:dokkaHtmlPartial` reports `Exiting Generation: Nothing to document`.
- `scripts/api-dump.sh` runs the rules-engine task and `api.txt` round-trips clean.
- `:rules-engine:testDefaultsReleaseUnitTest`, `:rules-engine:metalavaCheckCompatibilityDefaultsRelease`, and `detektAll` all pass.

Co-authored-by: Cursor <cursoragent@cursor.com>
# Conflicts:
#	scripts/api-dump.sh
The module is currently a skeleton with no functionality and no
consumers, so publishing `purchases-rules-engine` would ship an empty
artifact whose Maven Central version we'd then be on the hook to keep
publishing forever. Defer the publishing wiring until the JSON Logic
engine lands.

- Short-circuit `:rules-engine` in `ConfigureConditionalPublishing` so
  `com.vanniktech.maven.publish` is never applied to it. The module
  still compiles, gets detekt'd, runs tests, and is dokka-suppressed on
  every PR — there's just no AAR pushed to Sonatype.
- Drop the `mavenPublishing { configure(AndroidSingleVariantLibrary(…)) }`
  block (and its imports) from `rules-engine/build.gradle.kts`. With the
  publish plugin no longer applied, it's unreachable.
- Remove `api(project(":rules-engine"))` from `:bom` so consumers
  exploring the BoM don't see a real-looking `purchases-rules-engine`
  they could pull in and get nothing.
- Drop the `:rules-engine:metalavaGenerateSignatureDefaultsRelease`
  entry from `scripts/api-dump.sh`. It will be re-added in the same
  follow-up PR that flips publishing back on, to keep all the "publish
  wiring" in one switch-flip.

Follow-up PR (alongside the first real consumer of `RulesEngine`):
revert the `:rules-engine` short-circuit, restore the
`mavenPublishing { … }` block (gated with `plugins.withId(...)` so it
doesn't break CE deploys), restore the `:bom` entry, and re-add the
api-dump invocation.

Verified:
- `:purchases:publish --dry-run -PANDROID_VARIANT_TO_PUBLISH=customEntitlementComputationBc8Release` only fails on the unrelated `mavenCentralUsername`/`Password` credentials error — `:rules-engine` configures cleanly.
- `:rules-engine:tasks --all` lists no Maven publish tasks (only the unrelated `prepareLintJarForPublish` Android Lint internal).
- `:bom:tasks` resolves without `:rules-engine`.
- `:rules-engine:testDefaultsReleaseUnitTest`, `:rules-engine:metalavaCheckCompatibilityDefaultsRelease`, `:rules-engine:dokkaHtmlPartial`, and `detektAll` all pass.
- `scripts/api-dump.sh` leaves all `api*.txt` files unchanged.

Co-authored-by: Cursor <cursoragent@cursor.com>
Keep this PR minimal: an internal kotlin android library that
compiles, tests, and gets detekt'd. Everything that's only relevant
when the module ships an artifact lives in a separate draft PR:

- Drop the module-level `metalava { … }` block (and the committed
  `api.txt` baseline). Without a CI step regenerating it, the file
  was just static; we'll re-add both — and wire them into
  `scripts/api-dump.sh` — once publishing flips on.
- Drop the `dokkaHtmlPartial` suppression. The module would only show
  up in `dokkaHtmlMultiModule` output once it's published, so there's
  nothing to hide today.

Replace the two trailing comments with a single short pointer to the
follow-up PR and the `ConfigureConditionalPublishing` short-circuit.

Co-authored-by: Cursor <cursoragent@cursor.com>
…into pallares/rules-engine-enforce-internal-api
The `metalava { hiddenAnnotations.add(…) }` block lives in this branch
(rather than the skeleton) because the
`scripts/check-rules-engine-internal-only.sh` guardrail is the only
thing that depends on it: it asserts that, once
`@InternalRulesEngineAPI`-annotated declarations are hidden, the
generated `api.txt` contains nothing but the annotation interface
itself. Anything else is a leaked non-internal public API.

Without this block, the skeleton would have nothing exercising metalava
on `:rules-engine` (publishing wiring also lives in a separate draft
PR), so we keep it co-located with the check that needs it.

Co-authored-by: Cursor <cursoragent@cursor.com>
`metalava { hiddenAnnotations.add(InternalRulesEngineAPI) }` + a
committed `api.txt` are standard hygiene for every module that uses
`revenuecat.public.library`. The CocoaPods/Maven publishing wiring is
the only thing that's truly "exists but unwired" in this PR and that
already moved to its own draft.

Keeping the metalava config here also avoids a duplicate `metalava {}`
block landing in both the distribution PR (which adds the
`api-dump.sh` entry to enforce drift) and the enforce-internal-api PR
(which uses metalava to verify nothing leaks outside
`@InternalRulesEngineAPI`).

The `api.txt` file is not yet regenerated by CI in this PR — that
follow-up lives in the distribution draft PR.

Co-authored-by: Cursor <cursoragent@cursor.com>
…into pallares/rules-engine-enforce-internal-api
@ajpallares ajpallares added pr:other and removed pr:feat A new feature labels May 15, 2026
The comment described what `ConfigureConditionalPublishing` already
explains via its own short-circuit comment, so it was duplicating
context.

Co-authored-by: Cursor <cursoragent@cursor.com>
ajpallares and others added 9 commits May 28, 2026 09:49
Add jsDotSplit so empty path segments are preserved like
String(path).split(".") and pin the edge cases with regression tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
Trim RulesEngineLogger and PrintLogger KDoc to high-level defaults
without implementation details or future integration promises.

Co-authored-by: Cursor <cursoragent@cursor.com>
Trim Value KDoc to high-level predicate and variable data semantics,
aligned with iOS.

Co-authored-by: Cursor <cursoragent@cursor.com>
Drop cross-platform comparisons in KDoc and regression test comments.

Co-authored-by: Cursor <cursoragent@cursor.com>
Align with iOS: drop JS reference-impl detail for empty input.

Co-authored-by: Cursor <cursoragent@cursor.com>
The operator object now has 11 functions after lookupVar and jsDotSplit helpers; suppress keeps detekt green without splitting the module.

Co-authored-by: Cursor <cursoragent@cursor.com>
@ajpallares ajpallares marked this pull request as ready for review May 28, 2026 08:35
@ajpallares ajpallares requested a review from a team as a code owner May 28, 2026 08:35
@ajpallares ajpallares requested a review from a team May 28, 2026 11:19
ajpallares and others added 2 commits May 28, 2026 16:24

@tonidero tonidero left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some nitpicky comments but nothing really blocking. Looking great!

Comment thread rules-engine-internal/api.txt Outdated
Comment thread rules-engine-internal/src/main/kotlin/com/revenuecat/purchases/rules/Logger.kt Outdated
Comment thread rules-engine-internal/src/main/kotlin/com/revenuecat/purchases/rules/Evaluator.kt Outdated
* Diagnostic warnings are routed through [RulesEngine.logger].
*/
public interface RulesEngineLogger {
public fun warn(message: String)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we add a tag parameter here? Just thinking about eventually hooking this to the existing LogHandler... then again, we can probably just hardcode the tag in the mapping to LogHandler later, so NABD.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure I understood it right with the other comment, but I added a tag parameter in 6ee2297 that defaults to "[RulesEngine]". Lmk if you meant something else!

/** Default logger for [RulesEngine.logger]. */
internal object PrintLogger : RulesEngineLogger {
override fun warn(message: String) {
System.err.println("[RulesEngine] $message")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very nitpicky but we might want to extract the [RulesEngine] part to a TAG constant, so we can reuse for the "proper" logger later on?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure! Done in 6ee2297

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can always iterate on this, but for now it's a public constant in the Rules Engine. I guess that's what you meant?

/** Namespace for the RevenueCat rules engine. */
public object RulesEngine {
@Volatile
public var logger: RulesEngineLogger = PrintLogger

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm maybe we could add a setter method instead of making this public variable, like setLogger? which can be synchronized. Feels safer to me :)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense! Done in 6ee2297

ajpallares and others added 4 commits May 28, 2026 17:13
Make evaluateValue internal, add warn tag parameter with a default, expose setLogger instead of a public logger property, and remove api.txt left over from a pre-#3478 merge (Metalava is already disabled for this module).

Co-authored-by: Cursor <cursoragent@cursor.com>
Nothing in the MVP evaluator throws it yet; add it back in the PR that introduces the first call site.

Co-authored-by: Cursor <cursoragent@cursor.com>

@tonidero tonidero left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you!

Base automatically changed from pallares/rules-engine-skeleton to main May 28, 2026 15:50
…valuator

Co-authored-by: Cursor <cursoragent@cursor.com>

# Conflicts:
#	rules-engine-internal/build.gradle.kts
#	rules-engine-internal/src/main/kotlin/com/revenuecat/purchases/rules/RulesEngine.kt
@ajpallares ajpallares enabled auto-merge May 28, 2026 15:54
@ajpallares ajpallares added this pull request to the merge queue May 28, 2026
Merged via the queue into main with commit 1690666 May 28, 2026
37 checks passed
@ajpallares ajpallares deleted the pallares/json-logic-evaluator branch May 28, 2026 16:30
matteinn pushed a commit to matteinn/purchases-android that referenced this pull request Jun 5, 2026
**This is an automatic release.**

## RevenueCat SDK
### ✨ New Features
* Add presented offering context to custom paywall events (RevenueCat#3424) via
Rick (@rickvdl)
* Add Workflows list endpoint (RevenueCat#3509) via Cesar de la Vega (@vegaro)

## RevenueCatUI SDK
### Paywalls_v2
#### 🐞 Bugfixes
* Fix 1px seam between sliding multipage paywall pages (RevenueCat#3526) via Cesar
de la Vega (@vegaro)

### 🔄 Other Changes
* refactor: extract Offering.presentedOfferingContext() helper and apply
across SDK (RevenueCat#3513) via Rick (@rickvdl)
* Add JSON Logic string + array operators (RevenueCat#3485) via Antonio Pallares
(@ajpallares)
* Add ForbiddenPublicSealedClass detekt rule (RevenueCat#3503) via Toni Rico
(@tonidero)
* Update baseline profiles (RevenueCat#3519) via RevenueCat Git Bot (@RCGitBot)
* build(deps): bump fastlane-plugin-revenuecat_internal from `af7bb5c`
to `ce6a7ef` (RevenueCat#3515) via dependabot[bot] (@dependabot[bot])
* Add JSON Logic comparison operators (<, <=, >, >=) (RevenueCat#3484) via Antonio
Pallares (@ajpallares)
* Add JSON Logic arithmetic operators (+, -, *, /, %) (RevenueCat#3483) via
Antonio Pallares (@ajpallares)
* Add WorkflowEvent model and backend serialization (RevenueCat#3486) via Cesar de
la Vega (@vegaro)
* RulesEngine: add JSON Logic predicate evaluator (RevenueCat#3482) via Antonio
Pallares (@ajpallares)
* Add :rules-engine-internal skeleton module (RevenueCat#3478) via Antonio
Pallares (@ajpallares)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Version bump and changelog/docs/CI path updates only; no application
logic changes in the diff.
> 
> **Overview**
> This **automatic release** finalizes **Android SDK 10.8.0** by
replacing **`10.8.0-SNAPSHOT`** with **`10.8.0`** across versioning
(`gradle.properties`, `.version`, `Config.frameworkVersion`), sample
apps, and changelog files.
> 
> Release notes for **10.8.0** are recorded in **`CHANGELOG.md`** /
**`CHANGELOG.latest.md`** (workflows list API, paywall offering context
on custom events, multipage paywall seam fix, rules-engine/JSON Logic
work, etc.). **Docs publishing** now targets **`10.8.0`** on S3, and
**`docs/index.html`** redirects to the new doc URL.
> 
> There are **no functional code changes** in this diff beyond version
strings and release metadata.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c3048b8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants