Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(conditions): stop loose equality collapsing distinct 18-digit ids
trohitg20d00a07da2b
diff --git a/docs-internal/ui_migration_plan.md b/docs-internal/ui_migration_plan.mdindex b656d7a1..e81b298b 100644--- a/docs-internal/ui_migration_plan.md+++ b/docs-internal/ui_migration_plan.md@@ -401,7 +401,7 @@ The OpenCompany frontend was coupled to Ant Design (40 files, 187-line theme fil- **antd usage:** 40 files. Top imports: `Space` (20), `Button` (16), `Flex` (13), `Tag` (11), `Spin` (10), `Alert` (10), `Typography` (9), `InputNumber` (7), `Collapse` (7), `Input` (6), `Card` (6), `Form` (5), `Statistic` (4), `Select` (4), `Switch` (3).- **ConfigProvider:** only in [client/src/App.tsx](../client/src/App.tsx); theme in `client/src/config/antdTheme.ts` (deleted in Phase 7) mirrors [client/src/styles/theme.ts](../client/src/styles/theme.ts).- **Already installed:** Tailwind 4.1.13, `@radix-ui/react-dialog`, `@radix-ui/react-collapsible`, `react-hook-form`, `[email protected]` (scoped to `components/credentials/`), `@uiw/react-json-view`, `class-variance-authority`, `clsx`, `tailwind-merge`, `@radix-ui/react-slot`, `sonner`.-- **styled-components:** exactly 1 file — [client/src/components/shared/JSONTreeRenderer.tsx](../client/src/components/shared/JSONTreeRenderer.tsx).+- **styled-components:** exactly 1 file — `client/src/components/shared/JSONTreeRenderer.tsx` (audit-time fact; that file was migrated off styled-components and later deleted as unreferenced in Wave 15, so this is no longer a live path).- **Hand-written code to be deleted in corrected Phase 0:** `client/src/design-system/primitives/*` (8 files) and `client/src/design-system/lib/toast.ts` (introduced by commits `2209dba` and `7ac69fe` — the previous mistake).- **Imperative antd APIs:** 21 call sites already moved from `message.*`/`notification.*` to a `toast` adapter — they get **re-pointed at `sonner` directly**.- **antd Form:** 7 files, mostly under `components/credentials/panels/` + `sections/`.diff --git a/server/services/execution/conditions.py b/server/services/execution/conditions.pyindex 9e2b4b03..54284179 100644--- a/server/services/execution/conditions.py+++ b/server/services/execution/conditions.py@@ -24,6 +24,7 @@ Supported operators:"""import re+from decimal import Decimal, InvalidOperationfrom typing import Dict, Any, Listfrom core.logging import get_logger@@ -236,7 +237,7 @@ def _evaluate_operator(operator: str, actual: Any, target: Any) -> bool:def _loose_eq(actual: Any, target: Any) -> bool:- """Equality that tolerates the editor storing every target as a string.+ """Equality that bridges the editor's string target to a numeric output.The edge-condition editor types ``eq``/``neq`` targets as ``any`` and storesthe raw input, so a numeric comparison arrives as ``"200"`` while the node@@ -244,21 +245,37 @@ def _loose_eq(actual: Any, target: Any) -> bool:indistinguishable from a mis-typed field name. The ordering operatorsalready coerce via :func:`_safe_compare`; this brings equality in line.- Booleans are deliberately excluded from numeric coercion -- ``float(True)``- is ``1.0``, so without the guard ``eq 1`` would match a ``True`` output.+ **The coercion is deliberately narrow: exactly one side must be a string+ and the other a real number.** Coercing string-vs-string looks harmless and+ is not -- ``float()`` rounds past 2**53, so two *distinct* 18-digit+ identifiers (WhatsApp group JIDs, snowflake ids, ns timestamps) would+ compare equal and silently take each other's branch. Two strings are+ compared as strings, which is what the user wrote.++ :class:`~decimal.Decimal` rather than ``float`` for the same reason: it is+ exact, and it swallows arbitrarily large ints instead of raising+ ``OverflowError`` (which is outside the caught tuple, so it would escape and+ make ``neq`` answer False for a pair that is plainly unequal).++ Booleans, ``None`` and every other type need no special case: they either+ satisfy plain ``==`` or fail the text/number guard, and ``Decimal("True")``+ is simply invalid. Note that ``eq 1`` still matches a ``True`` output --+ ``1 == True`` in Python, short-circuiting on the first line. That predates+ loose equality; tightening it here would be an unrelated behaviour change."""if actual == target:return True- if actual is None or target is None:- return False-- if isinstance(actual, bool) or isinstance(target, bool):+ numeric = (int, float, Decimal)+ bridges_text_to_number = (isinstance(actual, str) and isinstance(target, numeric)) or (+ isinstance(target, str) and isinstance(actual, numeric)+ )+ if not bridges_text_to_number:return Falsetry:- return float(actual) == float(target)- except (ValueError, TypeError):+ return Decimal(str(actual)) == Decimal(str(target))+ except (InvalidOperation, ValueError, TypeError):return Falsediff --git a/server/services/temporal/workflow.py b/server/services/temporal/workflow.pyindex e3922ed2..090835bd 100644--- a/server/services/temporal/workflow.py+++ b/server/services/temporal/workflow.py@@ -19,10 +19,15 @@ from temporalio import workflowfrom ._retry_policies import DEFAULT_ACTIVITY_RETRY, QUICK_ACTIVITY_RETRYfrom services.workflow_naming import node_label_slug-# Imported straight from the module, never the package: ``services.execution``-# re-exports through an ``__init__`` that also pulls in the executor, cache,-# recovery sweeper and DLQ. ``conditions`` itself is pure (``re`` + comparisons,-# no IO, no clock, no randomness), so it is safe to evaluate inside a workflow.+# ``conditions`` is pure -- ``re`` + comparisons, no IO, no clock, no+# randomness -- so it is safe to evaluate inside a workflow.+#+# Importing the submodule still executes ``services/execution/__init__.py``+# first (Python always initialises the parent package), which drags in the+# executor, cache, recovery sweeper and DLQ. That is tolerated, not avoided:+# nothing in that subtree imports back into ``services.temporal``, so there is+# no cycle, and none of it pulls redis or sqlalchemy at import time. The+# pass-through keeps the sandbox from re-importing the chain per workflow.with workflow.unsafe.imports_passed_through():from services.execution.conditions import evaluate_conditiondiff --git a/server/tests/test_edge_conditions.py b/server/tests/test_edge_conditions.pyindex 2e134d69..fcc06290 100644--- a/server/tests/test_edge_conditions.py+++ b/server/tests/test_edge_conditions.py@@ -62,14 +62,67 @@ class TestNonNumericEqualityUnchanged:assert evaluate_condition(_cond("eq", None), {"result": {"status_code": 200}}) is False+class TestTextToTextIsNeverCoerced:+ """The coercion bridges text to a number, never text to text.++ A first cut coerced both sides whenever neither was bool/None. That looked+ harmless and was not: ``float()`` rounds past 2**53, so two *distinct*+ 18-digit identifiers compared equal and silently took each other's branch.+ WhatsApp group JIDs, snowflake ids and nanosecond timestamps all live in+ that range, and `eq` on an id is one of the most natural conditions to+ write -- so the failure would have been both common and invisible.+ """++ @pytest.mark.parametrize(+ "left,right",+ [+ ("120363012345678901", "120363012345678902"), # WhatsApp group JIDs+ ("1234567890123456789", "1234567890123456788"), # snowflake ids+ ("1700000000000000001", "1700000000000000002"), # ns timestamps+ ],+ )+ def test_distinct_long_numeric_strings_are_not_equal(self, left, right):+ output = {"result": {"chat_id": left}}+ assert evaluate_condition(_cond("eq", right, "result.chat_id"), output) is False++ def test_identical_long_numeric_string_still_matches(self):+ jid = "120363012345678901"+ output = {"result": {"chat_id": jid}}+ assert evaluate_condition(_cond("eq", jid, "result.chat_id"), output) is True++ def test_precision_holds_when_one_side_is_a_real_int(self):+ """Exactness comes from Decimal, not from refusing to compare."""+ output = {"result": {"chat_id": 120363012345678901}}+ assert evaluate_condition(_cond("eq", "120363012345678902", "result.chat_id"), output) is False+ assert evaluate_condition(_cond("eq", "120363012345678901", "result.chat_id"), output) is True++ def test_unrelated_strings_compare_as_strings(self):+ output = {"result": {"status": "success"}}+ assert evaluate_condition(_cond("eq", "failure", "result.status"), output) is False+++class TestNoOverflowOnHugeIntegers:+ """``float(10**400)`` raises OverflowError, which is not ValueError or+ TypeError -- it escaped the helper, so ``neq`` answered False for a pair+ that was plainly unequal. Decimal takes arbitrary-precision ints."""++ def test_huge_int_does_not_raise_and_compares_correctly(self):+ output = {"result": {"n": 10**400}}+ assert evaluate_condition(_cond("neq", "1", "result.n"), output) is True+ assert evaluate_condition(_cond("eq", "1", "result.n"), output) is False++ def test_huge_int_equal_to_its_own_text(self):+ output = {"result": {"n": 10**400}}+ assert evaluate_condition(_cond("eq", str(10**400), "result.n"), output) is True++class TestBooleanCarveOut:- """``float(True)`` is ``1.0``, so the new numeric coercion would have made- a truthy flag satisfy ``eq "1"``. The guard blocks that path only.+ """No boolean special case exists: ``Decimal("True")`` is invalid, so a+ truthy flag cannot reach a number through the bridge.- It deliberately does NOT touch ``True == 1``: that is plain Python- equality, it short-circuits before the guard, and it matched under the- old strict ``==`` too. Tightening it here would be a behaviour change- smuggled in under a bug fix.+ ``True == 1`` deliberately still matches -- that is plain Python equality,+ it short-circuits first, and it matched under the old strict ``==`` too.+ Tightening it would be a behaviour change smuggled in under a bug fix."""@pytest.mark.parametrize("target", ["1", "true", "True"])