Skip to content

Add JSON Logic arithmetic operators (+, -, *, /, %)#3483

Merged
ajpallares merged 80 commits into
mainfrom
pallares/json-logic-arithmetic-operators
May 29, 2026
Merged

Add JSON Logic arithmetic operators (+, -, *, /, %)#3483
ajpallares merged 80 commits into
mainfrom
pallares/json-logic-arithmetic-operators

Conversation

@ajpallares

@ajpallares ajpallares commented May 14, 2026

Copy link
Copy Markdown
Member

Resolves SDK-4330

Motivation

Adds JSON Logic arithmetic so predicates can express numeric thresholds, sums, and counters.

Summary

  • Implements +, -, *, /, % per the JSON Logic spec, including the variadic forms, the 1-arg numeric cast of +, and unary -.
  • All operators return Value.FloatValue for consistency with the JS reference; existing looseEq / strictEq already bridge IntValue ↔ FloatValue.
  • Non-numeric operands coerce to Double.NaN and propagate, so a malformed predicate falls through isTruthy as falsy.

Made with Cursor


Note

Medium Risk
Changes predicate evaluation semantics for numeric rules; incorrect coercion or IEEE edge cases could mis-target users, though scope is isolated to the rules engine with heavy spec tests.

Overview
Adds JSON Logic +, -, *, /, and % to the rules engine so predicates can do numeric math (thresholds, scaled counters, etc.), aligned with json-logic-js.

ArithmeticOperators implements variadic + / *, unary/binary -, and binary / / %, always returning FloatValue. + and multi-arg * coerce operands with jsParseFloat; -, /, and % use Number() via extended toNumberOrNull (arrays/objects stringify then parse). Edge cases match JS: empty +0, empty *RuleError.TypeMismatch, / by zero → ±Infinity, NaN propagates and stays falsy in truthiness.

Shared coercion is tightened with jsParseFloat and compound handling in toNumberOrNull. RuleError.TypeMismatch is new for bad arity. Coverage is added in ArithmeticOperatorsTest, ValueTest, and EvaluatorTest integration cases.

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

ajpallares and others added 14 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>
Extends the JSON Logic operator set with arithmetic so predicates can
express counter and sum conditions before the comparison and string
operators land.

What's new:

- `+`, `-`, `*`, `/`, `%` per the JSON Logic spec, including variadic
  `+` and `*`, the 1-arg numeric-cast form of `+`, and unary negation
  via `-`. All arithmetic returns `Value.FloatValue(Double)` for
  consistency with the JS reference (which `parseFloat`s every
  operand). `looseEq` and `strictEq` already bridge `IntValue(n) ↔
  FloatValue(n.0)`, so existing comparisons keep working.
- Non-numeric operands (`ObjectValue`, `ArrayValue`, unparseable
  strings) coerce to `Double.NaN` and propagate through arithmetic —
  the result is `FloatValue(NaN)`, falsy under `isTruthy`.
- Division and modulo by zero return `Value.Null` (deliberate
  deviation from JS's `Infinity` / `NaN` — friendlier for rule
  authors and matches the engine's "missing value" convention).
  Documented in the type's KDoc.

Tests:

- `ArithmeticOperatorsTest` covers each operator (basic, variadic,
  coercion, NaN propagation, divide/mod by zero, arity errors).
- `EvaluatorTest` adds two integration tests through dispatch:
  `var * 2 == 6` and the divide-by-zero → null → falsy flow.

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
ajpallares and others added 3 commits May 15, 2026 20:00
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>
`aed6e2f88` committed an `api.txt` for parity with other public-library
convention-plugin modules, but the immediate follow-up #3480
(no-public-apis enforcement) replaces that baseline with an explicit
annotate-or-fail check that doesn't keep a file in source. Committing
the baseline here just to delete it there is churn, so:

- Drop `rules-engine/api.txt`.
- Set `enforceCheck = false` so the standard `check` task no longer runs
  `metalavaCheckCompatibility*` against a missing baseline.
- Redirect `metalavaGenerateSignature*` output to `build/api-dump.txt`
  so local spot-checks don't drop a file at the module root.
- Keep `hiddenAnnotations.add(...InternalRulesEngineAPI)` so the
  generated dump filters gated symbols.
- Update the trailing comment to call out both follow-up PRs
  (publishing/distribution + #3480 enforcement).

Co-authored-by: Cursor <cursoragent@cursor.com>
…ternal-api' into pallares/json-logic-evaluator
ajpallares and others added 16 commits May 28, 2026 09:02
Rename Rules to RulesEngine and PrintlnLogger to PrintLogger (public),
route missing through varLookup for empty paths, drop dead evalTwo
opName, make RuleError subclasses data classes, and pin jsNumberString
platform divergence with regression tests.

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

Resolve module rename conflicts by moving evaluator sources into
:rules-engine-internal and keeping the public RulesEngine logger API.

Co-authored-by: Cursor <cursoragent@cursor.com>
Extract lookupVar for opVar and missing, and add a jsNumberString
regression at the last Long-roundtripping whole number before 1e19.

Co-authored-by: Cursor <cursoragent@cursor.com>
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>
…-arithmetic-operators

Co-authored-by: Cursor <cursoragent@cursor.com>
Drop redundant paragraphs so the Android doc matches the concise iOS
comment without changing behavior.

Co-authored-by: Cursor <cursoragent@cursor.com>
Add JS-sign modulo cases and test toNumberOrNull independently of
arithmetic operators, matching the jsParseFloat helper coverage pattern.

Co-authored-by: Cursor <cursoragent@cursor.com>
Describe JS IEEE 754 remainder sign rule only, matching the iOS
comment style without naming Swift or Kotlin.

Co-authored-by: Cursor <cursoragent@cursor.com>
@ajpallares ajpallares marked this pull request as ready for review May 28, 2026 11:20
@ajpallares ajpallares requested a review from a team as a code owner May 28, 2026 11:20
Base automatically changed from pallares/json-logic-evaluator to main May 28, 2026 16:30
Resolve conflicts: keep arithmetic operators and extended ToNumber
coercion from this branch, take main's RulesEngine.setLogger API and
evaluator visibility, and merge TypeMismatch with UnsupportedOperator.

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

@cursor cursor Bot 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.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 4adbe83. Configure here.

Comment thread rules-engine-internal/api.txt Outdated
The internal module opts out of Metalava; drop the accidental api.txt
and revert the unrelated api-dump.sh comment so this PR stays focused
on arithmetic operators only.

Co-authored-by: Cursor <cursoragent@cursor.com>
@ajpallares ajpallares enabled auto-merge May 29, 2026 09:53
@ajpallares ajpallares added this pull request to the merge queue May 29, 2026
Merged via the queue into main with commit f60aa1d May 29, 2026
34 of 35 checks passed
@ajpallares ajpallares deleted the pallares/json-logic-arithmetic-operators branch May 29, 2026 10:23
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