This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/texera.git


The following commit(s) were added to refs/heads/main by this push:
     new ab9ec50275 test(verify): compare what the two paths produced (#8359)
ab9ec50275 is described below

commit ab9ec502753cdb5ab924161bb3794e30bca9fdfb
Author: Kary Zheng <[email protected]>
AuthorDate: Thu Nov 19 03:32:02 2026 +0000

    test(verify): compare what the two paths produced (#8359)
    
    ### What changes were proposed in this PR?
    
    Two frames agree when they hold the same rows in the same order with the
    same
    values, and the comparison says which of those failed rather than that
    they
    differ. A float is compared within a tolerance, since the two paths
    reach the
    same number by different arithmetic. A model column is compared by what
    it
    predicts on a probe set rather than by its bytes. A BINARY column that
    holds no
    model, such as the file File Scan read, is compared byte for byte with
    the rest
    of the frame.
    
    A visualization has no frame to compare at all. The two comparators that
    read
    what one draws are in #8509.
    
    ### Any related issues, documentation, discussions?
    
    Part of #8325, 6 of 27; that issue lists the set in order.
    
    It does not compile until #8357 lands: that entry's build.sbt change
    puts workflow-operator's test sources on this module's test classpath,
    and the comparison reuses the `PythonWorkerPool` that lives there.
    
    Closes #8411, the task this change is the whole of.
    
    ### How was this PR tested?
    
    The tests in this change cover it. The whole set is exercised together
    once the last piece lands: every operator run through the engine and
    through its generated script, and the two answers compared.
    
    ### Was this PR authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Code (Opus 5)
    
    ---------
    
    Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
---
 .../src/test/resources/python/compare.py           | 1099 ++++++++++++++++++++
 .../amber/translator/verify/Comparator.scala       |  184 ++++
 .../amber/translator/verify/ComparatorSpec.scala   |  702 +++++++++++++
 3 files changed, 1985 insertions(+)

diff --git a/workflow-compiling-service/src/test/resources/python/compare.py 
b/workflow-compiling-service/src/test/resources/python/compare.py
new file mode 100644
index 0000000000..06974a862a
--- /dev/null
+++ b/workflow-compiling-service/src/test/resources/python/compare.py
@@ -0,0 +1,1099 @@
+#!/usr/bin/env python3
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Compare the two paths' outputs for one operator: JSONL DataFrames, or the 
Plotly
+figure a visualization operator renders.
+
+Usage: compare.py [--unordered] [--ignore-cols c1,c2]
+                  [--model-cols c1,c2 --probe features.jsonl]
+                  <actual.jsonl> <expected.jsonl>
+       compare.py --plotly <actual.jsonl> <expected.json>
+
+  --unordered   Pair each row with an equal row on the other side, by its exact
+                columns, its float columns within tolerance and its models'
+                answers, before comparing anything, so rows match as a
+                set/bag rather than positionally.
+                This is the norm: the engine runs operators across parallel
+                workers, so output row order is not part of the contract.
+                Without this flag the comparator matches rows positionally
+                (after reset_index(drop=True)) — used only for the sort family,
+                whose output order IS meaningful.
+
+  --ignore-cols Comma-separated column names to drop from both frames before
+                comparing. For opaque columns whose value isn't compared.
+
+  --model-cols  Comma-separated columns holding a base64(pickle) sklearn model.
+                Rather than byte-compare them (two independently-trained models
+                are functionally equal but not bit-identical), the comparator
+                unpickles both sides, has each model predict on the --probe
+                feature set, and asserts the predictions match — verifying the
+                two code paths produce behaviorally-equivalent models. The raw
+                model columns are then dropped before the frame comparison.
+
+  --probe       JSONL feature set the --model-cols models predict on. Each
+                model uses its own feature_names_in_ to select columns, so the
+                probe may include extra columns (e.g. the training target).
+
+  --plotly      Compare Plotly figures instead of DataFrames. The actual side 
is
+                a JSONL with `html-content` or `json-content`, a chart per row
+                or a page of them in one row; every `Plotly.newPlot(...)`
+                payload counts. The expected side is the standalone path's
+                `fig.write_json(...)`, one figure or a list of them, or its 
page
+                when that is where the whole set landed. The two are compared 
in
+                order, so a chart one path drew and the other did not is a
+                mismatch. Only data and layout are compared, with display-only
+                `uid` fields stripped and floats matched by tolerance. Takes
+                none of the DataFrame flags.
+
+Exit 0  - Outputs equal (and model predictions match, if --model-cols)
+Exit 1  - Outputs differ; detail on stderr
+Exit 2  - Bad invocation
+
+Persistent mode: `compare.py --serve` imports pandas once and then serves many
+comparisons over its lifetime, reading one JSON job per line on stdin and
+writing one JSON result per line on stdout. This avoids paying the ~214 ms
+pandas import on every comparison (the comparison itself is ~ms). It reuses the
+exact same functions the CLI calls, so behavior is identical.
+
+  request   {"kind": "dataframe", "actual": "<abs>", "expected": "<abs>",
+             "unordered": false, "ignoreCols": [], "modelCols": [],
+             "probe": null}\n
+            {"kind": "plotly", "actual": "<abs>", "expected": "<abs>"}\n
+  response  {"exit": 0|1, "stdout": "", "stderr": "<diff on mismatch>"}\n
+
+`kind` defaults to "dataframe". Both kinds are served by the same worker so a
+run needs one comparison pool rather than one per output shape; the Plotly side
+needs nothing pandas does not already pull in.
+
+A mismatch is exit 1 with the diff on `stderr`, mirroring the CLI's nonzero
+exit so the Scala side's ComparatorMismatchException path is unchanged. A
+comparison error never kills the server; only closing stdin (EOF) ends it.
+"""
+import sys
+
+# pandas is imported where it is used, not here: the --plotly comparison needs
+# nothing from it, and a module-level import would make that one-shot 
invocation
+# pay ~500 ms for an interpreter that then compares two JSON documents. 
`serve()`
+# imports it eagerly at startup instead, so a pooled worker still pays it once
+# rather than once per DataFrame comparison.
+
+
+def _holds_pickle(frame, col) -> bool:
+    """Whether every value in `col` is a base64 pickle, which is how a model is
+    written. A column the frame lacks, or one with no value, holds none."""
+    import base64
+    import pickle
+
+    if col not in frame.columns:
+        return False
+    cells = [v for v in frame[col] if isinstance(v, str)]
+    if not cells:
+        return False
+    try:
+        for v in cells:
+            pickle.loads(base64.b64decode(v))
+    except Exception:
+        return False
+    return True
+
+
+def _load_probe(probe_path):
+    """The feature set both sides' models predict on. Raises AssertionError 
when
+    there is none to ask."""
+    import pandas as pd
+
+    if probe_path is None:
+        raise AssertionError("--model-cols requires --probe with a feature 
set")
+    probe = pd.read_json(probe_path, lines=True)
+    # The probe is the operator's own input table, so under the nulls scenario 
it
+    # carries the holes that scenario punched. What is under test is whether 
the
+    # two models agree, and an estimator that refuses a NaN at predict time 
would
+    # end the comparison over the probe rather than over either model. Drop 
those
+    # rows: both models are asked the same questions either way.
+    probe = probe.dropna()
+    if probe.empty:
+        raise AssertionError(
+            "probe has no complete row to predict on; the two models cannot be 
compared"
+        )
+    return probe
+
+
+def _model_answer(cell, probe) -> tuple:
+    """What a pickled model was fitted on, what it predicts on the probe, and
+    whether it is a regressor."""
+    import base64
+    import pickle
+
+    import numpy as np
+
+    # A model column holds an sklearn estimator, so the unpickling below 
imports
+    # sklearn anyway; asking it what kind of estimator it handed back costs
+    # nothing more. Both are function-local so a run with no model column, 
which
+    # is most of them, never pays for either.
+    from sklearn.base import is_regressor
+
+    model = pickle.loads(base64.b64decode(cell))
+    # A model with feature_names_in_ selects its (numeric) feature columns from
+    # the probe, naturally dropping the training target the probe may still
+    # carry. A model WITHOUT it was fitted on a 1-D input rather than a named
+    # frame — i.e. a text pipeline (e.g. CountVectorizer) trained on a single
+    # text Series — so feed the probe's first column as a Series, not the whole
+    # frame (predicting on a DataFrame would make CountVectorizer iterate 
column
+    # labels).
+    names = getattr(model, "feature_names_in_", None)
+    listed = None if names is None else list(names)
+    # A model fitted on columns the probe lacks has nothing to be asked. Two 
such
+    # models still differ by their feature names, which are compared first.
+    if listed is not None and not set(listed) <= set(probe.columns):
+        return listed, None, is_regressor(model)
+    x = probe[listed] if listed is not None else probe.iloc[:, 0]
+    return listed, np.asarray(model.predict(x)), is_regressor(model)
+
+
+def _answers_differ(one, other) -> "str | None":
+    """How two models' answers differ, or None when they agree."""
+    import numpy as np
+
+    listed, pred_a, regressor_a = one
+    listed_e, pred_e, regressor_e = other
+    # What a model was fitted on is part of the model, and each side was being
+    # asked about its own features. Two models fitted on different columns 
still
+    # answer alike on a probe that carries both, so the predictions agreed 
while
+    # the models did not. One side having names where the other has none is the
+    # same divergence: it says the two were fitted on differently shaped input.
+    if listed != listed_e:
+        return (
+            "fitted feature names differ\n"
+            f"  actual:   {listed}\n"
+            f"  expected: {listed_e}"
+        )
+    if pred_a is None or pred_e is None:
+        return f"the probe lacks features the models were fitted on: {listed}"
+    if pred_a.shape != pred_e.shape:
+        return f"prediction shape differs ({pred_a.shape} vs {pred_e.shape})"
+    # Only a regressor predicts a measurement, where the last bits are
+    # arithmetic and a tolerance belongs. Every other estimator predicts a
+    # label, a class or a cluster, and a different label is a different answer
+    # however near the two numbers sit: classes 100000 and 100001 are one part
+    # in 1e5 apart, which allclose accepts. The estimator says which it is; the
+    # prediction's dtype cannot, since a numeric label is a number too. 
Anything
+    # sklearn does not call a regressor, including a non-sklearn pickle, is
+    # compared exactly.
+    tolerant = (
+        regressor_a
+        and regressor_e
+        and np.issubdtype(pred_a.dtype, np.number)
+        and np.issubdtype(pred_e.dtype, np.number)
+    )
+    ok = (
+        np.allclose(pred_a, pred_e, rtol=1e-5, atol=1e-8)
+        if tolerant
+        else np.array_equal(pred_a, pred_e)
+    )
+    if not ok:
+        return (
+            "predictions differ\n"
+            f"  actual:   {pred_a}\n"
+            f"  expected: {pred_e}"
+        )
+    return None
+
+
+def _compare_model_predictions(actual, expected, model_cols, probe) -> None:
+    """For each model column, assert both sides' models answer alike on the
+    probe, row by row. Raises AssertionError on any divergence."""
+    for col in model_cols:
+        # A requested column is one the engine declared as a model, so a side
+        # that never emitted it IS the divergence. Skipping it here would hide
+        # that: the column is dropped from both frames afterwards, and a path
+        # that produced no model at all would compare equal.
+        missing = [
+            side
+            for side, frame in (("actual", actual), ("expected", expected))
+            if col not in frame.columns
+        ]
+        if missing:
+            raise AssertionError(
+                f"model column {col!r} missing from {' and '.join(missing)}"
+            )
+        if len(actual) != len(expected):
+            raise AssertionError(
+                f"model column {col!r}: row count differs "
+                f"({len(actual)} vs {len(expected)})"
+            )
+        for i in range(len(actual)):
+            differ = _answers_differ(
+                _model_answer(actual[col].iloc[i], probe),
+                _model_answer(expected[col].iloc[i], probe),
+            )
+            if differ:
+                raise AssertionError(f"model column {col!r} row {i}: {differ}")
+
+
+def _declared_types(actual_path: str) -> dict:
+    """What the engine declared each output column as, read off the schema it
+    writes beside its output. Empty when there is no sidecar, which leaves the
+    inference in place rather than guessing."""
+    import json
+    import os
+
+    sidecar = actual_path + ".schema.json"
+    if not os.path.exists(sidecar):
+        return {}
+    # The engine writes UTF-8. Left to the platform default, a column name
+    # outside ASCII reads back as another name on Windows and loses its type.
+    with open(sidecar, "r", encoding="utf-8") as fh:
+        schema = json.load(fh)
+    return {a["attributeName"]: a.get("attributeType") for a in 
schema.get("attributes", [])}
+
+
+def _string_columns(actual_path: str) -> dict:
+    """The declared STRING columns, as a `read_json` dtype map."""
+    return {
+        name: str for name, kind in _declared_types(actual_path).items() if 
kind == "string"
+    }
+
+
+def _declared_strings(path: str, columns: list) -> dict:
+    """The named columns re-read with Python's json, which keeps a string a
+    string and leaves a number a number.
+
+    Reading them with `dtype=str` settles the two sides on one spelling, which
+    is what a text column needs, but it settles too much: it turns the JSON
+    number 6 into "6" as readily as it leaves "6" alone, so a side that wrote a
+    number where the engine declared text compared equal to the text. The
+    engine's own output is always text here, so a number is the divergence.
+    """
+    import json
+
+    import pandas as pd
+
+    values = {column: [] for column in columns}
+    with open(path, "r", encoding="utf-8") as fh:
+        for line in fh:
+            line = line.strip()
+            if not line:
+                continue
+            row = json.loads(line)
+            for column in columns:
+                cell = row.get(column)
+                if cell is None:
+                    values[column].append(pd.NA)
+                elif isinstance(cell, str):
+                    values[column].append(cell)
+                else:
+                    raise AssertionError(
+                        f"column '{column}' is declared text but holds 
{cell!r} in {path}"
+                    )
+    return {column: pd.array(cells, dtype="string") for column, cells in 
values.items()}
+
+
+def _raw_column(path: str, columns: list) -> dict:
+    """The named columns as Python's json read them, where an integer is exact
+    and a float is still a float."""
+    import json
+
+    values = {column: [] for column in columns}
+    with open(path, "r", encoding="utf-8") as fh:
+        for line in fh:
+            line = line.strip()
+            if not line:
+                continue
+            row = json.loads(line)
+            for column in columns:
+                values[column].append(row.get(column))
+    return values
+
+
+def _json_kind(cell) -> str:
+    if isinstance(cell, bool):
+        return "boolean"
+    if isinstance(cell, int):
+        return "integer"
+    if isinstance(cell, float):
+        return "float"
+    return type(cell).__name__
+
+
+def _assert_sides_agree(actual: dict, expected: dict, columns: list, declared: 
str) -> None:
+    """Fail where the two sides wrote a column as different JSON kinds.
+
+    What the comparison is asked is whether the paths match, not whether pandas
+    kept the declared type: where the engine's own path is a Python operator 
its
+    table goes through pandas too, so a hole widens the column on both paths
+    alike and the two still agree. One side widening on its own is the
+    divergence, and it is the one the digits hide.
+    """
+    for column in columns:
+        kinds_a = {_json_kind(c) for c in actual[column] if c is not None}
+        kinds_e = {_json_kind(c) for c in expected[column] if c is not None}
+        if kinds_a != kinds_e:
+            raise AssertionError(
+                f"column '{column}' is declared {declared} and the two sides 
wrote it "
+                f"differently\n"
+                f"  actual:   {sorted(kinds_a) or ['all null']}\n"
+                f"  expected: {sorted(kinds_e) or ['all null']}"
+            )
+
+
+def _exact_integers(actual_path: str, expected_path: str, columns: list) -> 
tuple:
+    """Both sides' named columns re-read with Python's json, whose integers are
+    exact, having first agreed on what each column holds.
+
+    `read_json` parses a column holding a null through float64, so a LONG of
+    9007199254740993 is already 9007199254740992 by the time anything compares
+    it. Pinning the dtype does not help: the rounding happens on the way in.
+
+    One side writing a float where the other wrote an integer is the divergence
+    the digits hide. 6.0 was read as the 6 the schema asked for, on the grounds
+    that both spell the same integer, but they do not survive the same: a later
+    cast to text writes "6" from one and "6.0" from the other.
+
+    Both sides writing a float is not a divergence; see 
[[_assert_sides_agree]].
+    """
+    import pandas as pd
+
+    actual = _raw_column(actual_path, columns)
+    expected = _raw_column(expected_path, columns)
+    _assert_sides_agree(actual, expected, columns, "integral")
+
+    def arrays(values):
+        out = {}
+        for column, cells in values.items():
+            # A column either side widened is compared as the float it now is,
+            # exactly rather than by tolerance; one both sides kept integral is
+            # carried in the nullable integer, where a long stays exact. A null
+            # stays None so each dtype takes its own hole: float64 cannot hold
+            # pd.NA.
+            widened = any(isinstance(c, float) for c in cells)
+            out[column] = pd.array(cells, dtype="float64" if widened else 
"Int64")
+        return out
+
+    return arrays(actual), arrays(expected)
+
+
+def _declared_booleans(actual_path: str, expected_path: str, columns: list) -> 
tuple:
+    """Both sides' declared BOOLEAN columns, having first agreed on what each
+    one holds.
+
+    numpy counts True as 1, and `assert_frame_equal` is asked not to check
+    dtypes, so a column of booleans compared equal to a column of ones. The
+    engine says of a BOOLEAN column that it holds true and false, and a side
+    that wrote a number there has changed the type of the answer.
+
+    As with the integers, both sides widening alike is not a divergence: a hole
+    costs a pandas boolean column its type on whichever path went through
+    pandas, and if both did they still agree.
+    """
+    import pandas as pd
+
+    actual = _raw_column(actual_path, columns)
+    expected = _raw_column(expected_path, columns)
+    _assert_sides_agree(actual, expected, columns, "boolean")
+
+    def arrays(values):
+        out = {}
+        for column, cells in values.items():
+            kept = all(c is None or isinstance(c, bool) for c in cells)
+            out[column] = pd.array(cells, dtype="boolean" if kept else 
"float64")
+        return out
+
+    return arrays(actual), arrays(expected)
+
+
+_DOUBLE_TEXT = {"NaN": "nan", "Infinity": "inf", "-Infinity": "-inf", "-0.0": 
"-0.0"}
+
+
+def _double_kind(cell) -> str:
+    """Which of the values a float64 comparison cannot tell apart this cell is.
+
+    `read_json` reads a null and a NaN as one NaN, and -0.0 equals 0.0, so a 
side
+    that answered NaN where the other answered null, or flipped a zero's sign,
+    compared equal. Each side spells the four as the engine's writer does.
+    """
+    import math
+
+    if cell is None:
+        return "null"
+    if isinstance(cell, str):
+        return cell
+    if cell != cell:
+        return "NaN"
+    if cell in (math.inf, -math.inf):
+        return "Infinity" if cell > 0 else "-Infinity"
+    if cell == 0.0 and math.copysign(1.0, cell) < 0:
+        return "-0.0"
+    return "number"
+
+
+def _declared_doubles(actual_path: str, expected_path: str, columns: list) -> 
tuple:
+    """Both sides' declared DOUBLE columns as numbers, plus what kind of value
+    each cell is. The numbers keep the tolerance; the kinds are compared 
exactly."""
+
+    def split(values):
+        numbers, kinds = {}, {}
+        for column, cells in values.items():
+            kinds[column] = [_double_kind(c) for c in cells]
+            numbers[column] = [
+                float(_DOUBLE_TEXT.get(c, "nan")) if isinstance(c, str)
+                else float("nan") if c is None
+                else float(c)
+                for c in cells
+            ]
+        return numbers, kinds
+
+    return split(_raw_column(actual_path, columns)), 
split(_raw_column(expected_path, columns))
+
+
+def _run_comparison(
+    actual_path: str,
+    expected_path: str,
+    unordered: bool,
+    ignore_cols: list,
+    model_cols: list,
+    probe_path,
+) -> "str | None":
+    """Compare two JSONL DataFrames. Returns None if they match, or a human
+    diff string if they differ (exit-1 condition). Unexpected errors (e.g. a
+    bad input file) propagate to the caller. This is the single source of
+    comparison truth shared by the CLI and the --serve loop."""
+    import pandas as pd
+
+    # A string column has to be READ as one on both sides. Left to itself,
+    # `read_json` infers a type per file, so a column the engine wrote as "6"
+    # and the script wrote as "6.0" both arrive as the number 6, and a null
+    # beside the text "nan" both arrive as NaN -- two genuinely different
+    # answers compared as one. The engine writes a schema next to its output;
+    # it names which columns are strings, and both sides are read that way.
+    declared = _declared_types(actual_path)
+    str_cols = {name: str for name, kind in declared.items() if kind == 
"string"}
+    actual = pd.read_json(actual_path, lines=True, dtype=str_cols or None)
+    expected = pd.read_json(expected_path, lines=True, dtype=str_cols or None)
+
+    # `dtype=str` above settles the spelling, which a text column needs, but it
+    # also turns a JSON number into text, so a side that wrote 6 where the 
engine
+    # declared text compared equal to "6". Re-read those columns from the raw
+    # JSON, where a number is still a number and so still a divergence.
+    raw_str_cols = [
+        name for name in str_cols if name in actual.columns and name in 
expected.columns
+    ]
+    if raw_str_cols:
+        try:
+            for frame, path in ((actual, actual_path), (expected, 
expected_path)):
+                for column, values in _declared_strings(path, 
raw_str_cols).items():
+                    frame[column] = values
+        except AssertionError as exc:
+            return str(exc)
+
+    # Both sides take the ENGINE's declared type, which also settles a column a
+    # hole widened to float on one path and not the other.
+    int_cols = [
+        name
+        for name, kind in declared.items()
+        if kind in ("integer", "long") and name in actual.columns and name in 
expected.columns
+    ]
+    if int_cols:
+        try:
+            exact_a, exact_e = _exact_integers(actual_path, expected_path, 
int_cols)
+        except AssertionError as exc:
+            return str(exc)
+        for column in int_cols:
+            actual[column] = exact_a[column]
+            expected[column] = exact_e[column]
+
+    # numpy counts True as 1 and the dtype check is off, so a column of 
booleans
+    # compared equal to a column of ones. The engine says a BOOLEAN column 
holds
+    # true and false; a side that wrote a number there changed the answer's 
type.
+    bool_cols = [
+        name
+        for name, kind in declared.items()
+        if kind == "boolean" and name in actual.columns and name in 
expected.columns
+    ]
+    if bool_cols:
+        try:
+            bool_a, bool_e = _declared_booleans(actual_path, expected_path, 
bool_cols)
+        except AssertionError as exc:
+            return str(exc)
+        for column in bool_cols:
+            actual[column] = bool_a[column]
+            expected[column] = bool_e[column]
+
+    double_cols = [
+        name
+        for name, kind in declared.items()
+        if kind == "double" and name in actual.columns and name in 
expected.columns
+    ]
+    double_kinds_a, double_kinds_e = {}, {}
+    if double_cols:
+        (numbers_a, double_kinds_a), (numbers_e, double_kinds_e) = 
_declared_doubles(
+            actual_path, expected_path, double_cols
+        )
+        for column in double_cols:
+            actual[column] = pd.array(numbers_a[column], dtype="float64")
+            expected[column] = pd.array(numbers_e[column], dtype="float64")
+
+    # A BINARY column is not always a model: File Scan hands back a file's 
bytes.
+    # Bytes neither side can unpickle are plain data, compared exactly with the
+    # rest of the frame. A column one side lacks, or one side can unpickle, 
stays
+    # a model column, so a model on one side only still fails as one.
+    model_cols = [
+        col
+        for col in model_cols
+        if col not in actual.columns
+        or col not in expected.columns
+        or _holds_pickle(actual, col)
+        or _holds_pickle(expected, col)
+    ]
+
+    # Two outputs without a row hold no model to ask, and read back from an
+    # empty file they hold no column either.
+    probe = None
+    if model_cols and (len(actual) or len(expected)):
+        try:
+            probe = _load_probe(probe_path)
+        except AssertionError as exc:
+            return str(exc)
+
+    # Rows are paired before anything compares them. The models below are
+    # compared row by row, so a model has to stay beside the row it belongs to.
+    if unordered:
+        unsorted = model_cols + ignore_cols
+        actual, double_kinds_a = _sorted_rows(actual, double_kinds_a, unsorted)
+        expected, double_kinds_e = _sorted_rows(expected, double_kinds_e, 
unsorted)
+        expected, double_kinds_e = _paired_rows(
+            actual, expected, double_kinds_a, double_kinds_e, unsorted, 
model_cols, probe
+        )
+
+    # Model columns: compare behavior (predictions) rather than bytes, then 
drop
+    # the raw columns so the frame comparison covers everything else exactly.
+    if model_cols:
+        if probe is not None:
+            try:
+                _compare_model_predictions(actual, expected, model_cols, probe)
+            except AssertionError as exc:
+                return str(exc)
+        actual = actual.drop(columns=model_cols, errors="ignore")
+        expected = expected.drop(columns=model_cols, errors="ignore")
+
+    if ignore_cols:
+        actual = actual.drop(columns=ignore_cols, errors="ignore")
+        expected = expected.drop(columns=ignore_cols, errors="ignore")
+
+    # The column list is part of the answer, and neither half of it was being
+    # checked. The comparison took its columns from `actual` and selected those
+    # out of `expected`, so a column only `expected` carried was never looked
+    # at. Order went unchecked too, under `check_like`, and order is what a
+    # positional UDF reads by, what a file export writes out, and what code
+    # asking for the first column gets.
+    if list(actual.columns) != list(expected.columns):
+        only_actual = [c for c in actual.columns if c not in 
set(expected.columns)]
+        only_expected = [c for c in expected.columns if c not in 
set(actual.columns)]
+        detail = []
+        if only_actual:
+            detail.append(f"  only in actual:   {only_actual}")
+        if only_expected:
+            detail.append(f"  only in expected: {only_expected}")
+        if not detail:
+            detail.append("  the same columns in a different order")
+        return "\n".join(
+            [
+                "column mismatch",
+                f"  actual:   {list(actual.columns)}",
+                f"  expected: {list(expected.columns)}",
+            ]
+            + detail
+        )
+
+    # Kept beside the frame, not in it. A column added under a made-up name
+    # overwrote an output column that had the same name, and both sides then
+    # agreed on it. Each rode with its row through the sort above.
+    kind_cols = [column for column in double_cols if column in actual.columns]
+    kinds_a = {column: double_kinds_a[column] for column in kind_cols}
+    kinds_e = {column: double_kinds_e[column] for column in kind_cols}
+
+    # The tolerance was letting integers through with it: at rtol=1e-5, LONG
+    # 100000 and 100001 compare equal. Integer columns are compared exactly.
+    exact_cols = [c for c in int_cols if c in actual.columns]
+    loose_cols = [c for c in actual.columns if c not in exact_cols]
+    # No `check_like`: it sorts both frames' columns before comparing, which is
+    # what let a reordering through. The lists are known equal by here, so each
+    # of these two selections holds the same columns in the same order.
+    try:
+        if exact_cols:
+            pd.testing.assert_frame_equal(
+                actual[exact_cols],
+                expected[exact_cols],
+                check_dtype=False,
+                check_exact=True,
+            )
+        pd.testing.assert_frame_equal(
+            actual[loose_cols],
+            expected[loose_cols],
+            check_dtype=False,
+            rtol=1e-5,
+        )
+    except AssertionError as exc:
+        return str(exc)
+
+    # Compared exactly: the numbers above cannot tell these values apart.
+    for column in kind_cols:
+        for row, (one, other) in enumerate(zip(kinds_a[column], 
kinds_e[column])):
+            if one != other:
+                return (
+                    f"column '{column}' is declared double and the two sides "
+                    f"differ at row {row}\n"
+                    f"  actual:   {one}\n"
+                    f"  expected: {other}"
+                )
+    return None
+
+
+def _sorted_rows(frame, kinds: dict, unsorted: list) -> tuple:
+    """The frame's rows sorted by its exact columns, then its float columns,
+    then every kind, with the kinds put in the same order. A float sorted first
+    pairs rows by a value the tolerance lets differ, so a row within tolerance
+    on the other side can land beside the wrong ID. `unsorted` columns ride
+    along without ordering anything. The sort key labels its columns by
+    position, so no kind can take the place of an output column."""
+    import pandas as pd
+
+    keyed = [column for column in frame.columns if column not in unsorted]
+    floats = [column for column in keyed if 
pd.api.types.is_float_dtype(frame[column])]
+    key = frame[[column for column in keyed if column not in floats] + floats]
+    key = key.reset_index(drop=True)
+    key.columns = range(len(key.columns))
+    for offset, column in enumerate(c for c in kinds if c not in unsorted):
+        key[len(keyed) + offset] = kinds[column]
+    if not len(key.columns):
+        return frame, kinds
+    order = list(
+        key.sort_values(by=list(key.columns), kind="mergesort", 
na_position="last").index
+    )
+    return (
+        frame.iloc[order].reset_index(drop=True),
+        {column: [cells[i] for i in order] for column, cells in kinds.items()},
+    )
+
+
+def _paired_rows(actual, expected, kinds_a, kinds_e, unsorted, model_cols, 
probe) -> tuple:
+    """`expected`'s rows reordered so each sits beside an `actual` row it
+    matches, with its kinds put in the same order. Sorting alone cannot pair
+    rows that tie on every exact column, or whose floats differ within the
+    tolerance: two such rows on one side can sort the other way round on the
+    other. Rows are grouped by their exact columns and kinds, and within a
+    group each is paired with a row whose floats are within tolerance and whose
+    models answer alike. When no such pairing exists, the sorted order stays,
+    and the comparison that follows reports the difference."""
+    from collections import defaultdict
+
+    import pandas as pd
+
+    if len(actual) != len(expected) or not len(actual):
+        return expected, kinds_e
+    keyed = [c for c in actual.columns if c not in unsorted and c in 
expected.columns]
+    floats = [
+        c
+        for c in keyed
+        if pd.api.types.is_float_dtype(actual[c]) and 
pd.api.types.is_float_dtype(expected[c])
+    ]
+    exact = [c for c in keyed if c not in floats]
+    kind_cols = [c for c in kinds_a if c not in unsorted and c in kinds_e]
+
+    def groups(frame, kinds) -> dict:
+        cells = [frame[c].tolist() for c in exact] + [kinds[c] for c in 
kind_cols]
+        found = defaultdict(list)
+        for row in range(len(frame)):
+            found[tuple(_cell_key(column[row]) for column in 
cells)].append(row)
+        return found
+
+    groups_a, groups_e = groups(actual, kinds_a), groups(expected, kinds_e)
+    if any(len(rows) != len(groups_e.get(key, ())) for key, rows in 
groups_a.items()):
+        return expected, kinds_e
+
+    numbers_a = actual[floats].to_numpy(dtype="float64")
+    numbers_e = expected[floats].to_numpy(dtype="float64")
+    shared = [c for c in model_cols if c in actual.columns and c in 
expected.columns]
+    answers = {}
+
+    def answer(side, frame, column, row):
+        if (side, column, row) not in answers:
+            try:
+                answers[side, column, row] = 
_model_answer(frame[column].iloc[row], probe)
+            except Exception:
+                answers[side, column, row] = None
+        return answers[side, column, row]
+
+    def agree(i, j) -> bool:
+        for column in shared:
+            one = answer("actual", actual, column, i)
+            other = answer("expected", expected, column, j)
+            if one is None or other is None or _answers_differ(one, other):
+                return False
+        return True
+
+    partner = [None] * len(actual)
+    for key, rows_a in groups_a.items():
+        rows_e = groups_e[key]
+        close = _close(numbers_a[rows_a][:, None, :], numbers_e[rows_e][None, 
:, :]).all(axis=2)
+        options = [
+            [j for j in range(len(rows_e)) if close[i, j] and agree(rows_a[i], 
rows_e[j])]
+            for i in range(len(rows_a))
+        ]
+        pairing = _matching(options)
+        if pairing is None:
+            return expected, kinds_e
+        for i, j in enumerate(pairing):
+            partner[rows_a[i]] = rows_e[j]
+    return (
+        expected.iloc[partner].reset_index(drop=True),
+        {column: [cells[i] for i in partner] for column, cells in 
kinds_e.items()},
+    )
+
+
+def _cell_key(cell):
+    """A cell as a grouping key: every null is one key, and a cell that cannot
+    be hashed is keyed by its spelling."""
+    import pandas as pd
+
+    try:
+        if pd.isna(cell) is True:
+            return None
+    except (TypeError, ValueError):
+        pass
+    try:
+        hash(cell)
+        return cell
+    except TypeError:
+        return repr(cell)
+
+
+def _close(one, other):
+    """Whether two float arrays agree within the tolerance the frame comparison
+    uses, element by element: math.isclose at rtol=1e-5, atol=1e-8, with NaN
+    equal to NaN."""
+    import numpy as np
+
+    with np.errstate(invalid="ignore"):
+        bound = np.maximum(1e-5 * np.maximum(np.abs(one), np.abs(other)), 1e-8)
+        same = (one == other) | (np.isnan(one) & np.isnan(other))
+        return same | (np.abs(one - other) <= bound)
+
+
+def _matching(options) -> "list | None":
+    """A distinct partner for every row, chosen from the partners that row may
+    take, or None when there is no such choice. Each row starts beside the row
+    at its own position, so sorted rows that already match cost no search."""
+    mine = [None] * len(options)
+    theirs = [None] * len(options)
+    for i, choices in enumerate(options):
+        if i in choices:
+            mine[i] = theirs[i] = i
+    for start in range(len(options)):
+        if mine[start] is not None:
+            continue
+        reached_from = {}
+        frontier = [start]
+        end = None
+        while frontier and end is None:
+            following = []
+            for i in frontier:
+                for j in options[i]:
+                    if j in reached_from:
+                        continue
+                    reached_from[j] = i
+                    if theirs[j] is None:
+                        end = j
+                        break
+                    following.append(theirs[j])
+                if end is not None:
+                    break
+            frontier = following
+        if end is None:
+            return None
+        j = end
+        while j is not None:
+            i = reached_from[j]
+            mine[i], theirs[j], j = j, i, mine[i]
+    return mine
+
+
+def _load_actual_plots(path) -> list:
+    """Every chart the run drew: a row per chart, or a row holding a page of
+    them, which is how an operator that draws a chart per input row hands them
+    over."""
+    import json
+
+    with open(path, "r", encoding="utf-8") as fh:
+        lines = [raw for raw in fh if raw.strip()]
+    if not lines:
+        raise AssertionError(f"{path} is empty")
+
+    plots = []
+    for number, line in enumerate(lines, start=1):
+        row = json.loads(line)
+        if "json-content" in row and row["json-content"]:
+            value = row["json-content"]
+            plots.append(json.loads(value) if isinstance(value, str) else 
value)
+        elif "html-content" in row and row["html-content"]:
+            plots.extend(_plotly_payloads_from_html(row["html-content"]))
+        else:
+            raise AssertionError(
+                f"{path} row {number} has neither html-content nor 
json-content"
+            )
+    return plots
+
+
+def _plotly_payloads_from_html(html: str) -> list:
+    """Pull the data/layout arguments out of every Plotly.newPlot(...) call.
+
+    Every call, because a page can hold a chart per input row and reading the
+    first would leave the rest of them uncompared.
+
+    Scanned with a JSON decoder rather than a regex because the payload is
+    arbitrary nested JSON that no bracket-matching pattern handles reliably.
+    """
+    import json
+
+    marker = "Plotly.newPlot("
+    index = html.find(marker)
+    if index < 0:
+        raise AssertionError("html-content does not contain 
Plotly.newPlot(...)")
+
+    decoder = json.JSONDecoder()
+    plots: list = []
+    while index >= 0:
+        index += len(marker)
+        args: list = []
+        while len(args) < 4:
+            while index < len(html) and html[index] in " \t\r\n,":
+                index += 1
+            value, consumed = decoder.raw_decode(html[index:])
+            args.append(value)
+            index += consumed
+        plots.append({"data": args[1], "layout": args[2]})
+        index = html.find(marker, index)
+
+    return plots
+
+
+def _load_expected_plots(path) -> list:
+    """Every chart the exported script drew. An operator that draws one writes 
a
+    lone figure, and one that draws a chart per row writes the sequence. A page
+    is read for every chart on it."""
+    import json
+
+    with open(path, "r", encoding="utf-8") as fh:
+        text = fh.read()
+    if str(path).endswith(".html"):
+        return _plotly_payloads_from_html(text)
+    value = json.loads(text)
+    figures = value if isinstance(value, list) else [value]
+    return [
+        {"data": fig.get("data", []), "layout": fig.get("layout", {})}
+        for fig in figures
+    ]
+
+
+def _strip_unstable(value):
+    """Remove display-only fields that are unrelated to chart semantics."""
+    if isinstance(value, dict):
+        return {
+            key: _strip_unstable(child)
+            for key, child in value.items()
+            if key not in {"uid"}
+        }
+    if isinstance(value, list):
+        return [_strip_unstable(child) for child in value]
+    return value
+
+
+def _plots_equal(actual, expected) -> bool:
+    import math
+
+    # Before the numeric branch, because `bool` is a subclass of `int` and a
+    # boolean fell into it: True and 1 went through math.isclose and compared
+    # equal. A trace says things with booleans that a number does not, and a
+    # column whose declared type changed from boolean to integer reaches the
+    # figure as exactly this difference.
+    if isinstance(actual, bool) or isinstance(expected, bool):
+        return isinstance(actual, bool) and isinstance(expected, bool) and 
actual == expected
+    if isinstance(actual, (int, float)) and isinstance(expected, (int, float)):
+        return math.isclose(float(actual), float(expected), rel_tol=1e-9, 
abs_tol=1e-12)
+    if isinstance(actual, dict) and isinstance(expected, dict):
+        return actual.keys() == expected.keys() and all(
+            _plots_equal(actual[key], expected[key]) for key in actual.keys()
+        )
+    if isinstance(actual, list) and isinstance(expected, list):
+        return len(actual) == len(expected) and all(
+            _plots_equal(left, right) for left, right in zip(actual, expected)
+        )
+    return actual == expected
+
+
+def _run_plotly_comparison(actual_path, expected_path) -> "str | None":
+    """Compare two Plotly figures. Returns None if they match, or a human diff
+    string if they differ — the same contract as `_run_comparison`, so the CLI
+    and the --serve loop treat both kinds identically."""
+    import json
+
+    actual = [_strip_unstable(p) for p in _load_actual_plots(actual_path)]
+    expected = [_strip_unstable(p) for p in 
_load_expected_plots(expected_path)]
+
+    if len(actual) != len(expected):
+        return (
+            f"Plotly chart count mismatch: the run drew {len(actual)} and the "
+            f"exported script drew {len(expected)}"
+        )
+
+    for index, (one, other) in enumerate(zip(actual, expected)):
+        if _plots_equal(one, other):
+            continue
+        return "\n".join(
+            [
+                f"Plotly JSON mismatch on chart {index + 1} of {len(actual)}",
+                "--- actual ---",
+                json.dumps(one, indent=2, sort_keys=True),
+                "--- expected ---",
+                json.dumps(other, indent=2, sort_keys=True),
+            ]
+        )
+    return None
+
+
+def main() -> None:
+    args = sys.argv[1:]
+    unordered = False
+    ignore_cols: list = []
+    model_cols: list = []
+    probe_path = None
+
+    if args and args[0] == "--plotly":
+        if len(args) != 3:
+            print(
+                f"usage: {sys.argv[0]} --plotly <actual.jsonl> 
<expected.json>",
+                file=sys.stderr,
+            )
+            sys.exit(2)
+        msg = _run_plotly_comparison(args[1], args[2])
+        if msg is not None:
+            print(msg, file=sys.stderr)
+            sys.exit(1)
+        return
+
+    while args and args[0].startswith("--"):
+        if args[0] == "--unordered":
+            unordered = True
+            args = args[1:]
+        elif args[0] == "--ignore-cols":
+            if len(args) < 2:
+                print("--ignore-cols requires an argument", file=sys.stderr)
+                sys.exit(2)
+            ignore_cols = [c for c in args[1].split(",") if c]
+            args = args[2:]
+        elif args[0] == "--model-cols":
+            if len(args) < 2:
+                print("--model-cols requires an argument", file=sys.stderr)
+                sys.exit(2)
+            model_cols = [c for c in args[1].split(",") if c]
+            args = args[2:]
+        elif args[0] == "--probe":
+            if len(args) < 2:
+                print("--probe requires an argument", file=sys.stderr)
+                sys.exit(2)
+            probe_path = args[1]
+            args = args[2:]
+        else:
+            print(f"unknown flag: {args[0]}", file=sys.stderr)
+            sys.exit(2)
+    if len(args) != 2:
+        print(
+            f"usage: {sys.argv[0]} [--unordered] [--ignore-cols c1,c2] "
+            f"[--model-cols c1,c2 --probe features.jsonl] "
+            f"<actual.jsonl> <expected.jsonl>",
+            file=sys.stderr,
+        )
+        sys.exit(2)
+
+    msg = _run_comparison(
+        args[0], args[1], unordered, ignore_cols, model_cols, probe_path
+    )
+    if msg is not None:
+        print(msg, file=sys.stderr)
+        sys.exit(1)
+
+
+def serve() -> None:
+    """Persistent comparison server. See the module docstring for the protocol.
+
+    Each job runs the same function the CLI calls for its kind. A comparison
+    error is reported as exit 1 with the diff on `stderr`; only closing stdin
+    ends the loop.
+    """
+    import io
+    import json
+    import traceback
+    from contextlib import redirect_stderr, redirect_stdout
+
+    # Eagerly, before signalling ready: the point of a persistent worker is 
that
+    # this cost is paid once per worker instead of once per comparison, and
+    # `ready` should mean the worker is warm.
+    import pandas  # noqa: F401
+
+    sys.stdout.write(json.dumps({"ready": True}) + "\n")
+    sys.stdout.flush()
+
+    for line in sys.stdin:
+        line = line.strip()
+        if not line:
+            continue
+        out_buf, err_buf = io.StringIO(), io.StringIO()
+        try:
+            job = json.loads(line)
+            with redirect_stdout(out_buf), redirect_stderr(err_buf):
+                if job.get("kind", "dataframe") == "plotly":
+                    msg = _run_plotly_comparison(job["actual"], 
job["expected"])
+                else:
+                    msg = _run_comparison(
+                        job["actual"],
+                        job["expected"],
+                        job.get("unordered", False),
+                        job.get("ignoreCols", []),
+                        job.get("modelCols", []),
+                        job.get("probe"),
+                    )
+            resp = {
+                "exit": 0 if msg is None else 1,
+                "stdout": out_buf.getvalue(),
+                "stderr": err_buf.getvalue() + ("" if msg is None else msg),
+            }
+        except BaseException:  # noqa: BLE001 — a bad job must not kill the 
server
+            resp = {
+                "exit": 1,
+                "stdout": out_buf.getvalue(),
+                "stderr": err_buf.getvalue() + traceback.format_exc(),
+            }
+        sys.stdout.write(json.dumps(resp) + "\n")
+        sys.stdout.flush()
+
+
+if __name__ == "__main__":
+    if len(sys.argv) > 1 and sys.argv[1] == "--serve":
+        serve()
+    else:
+        main()
diff --git 
a/workflow-compiling-service/src/test/scala/org/apache/texera/amber/translator/verify/Comparator.scala
 
b/workflow-compiling-service/src/test/scala/org/apache/texera/amber/translator/verify/Comparator.scala
new file mode 100644
index 0000000000..ae67d5c478
--- /dev/null
+++ 
b/workflow-compiling-service/src/test/scala/org/apache/texera/amber/translator/verify/Comparator.scala
@@ -0,0 +1,184 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.texera.amber.translator.verify
+
+import com.typesafe.scalalogging.LazyLogging
+import org.apache.texera.amber.util.JSONUtils.objectMapper
+import org.apache.texera.amber.util.python.PythonWorkerPool
+
+import java.nio.file.{Files, Path, StandardCopyOption}
+import scala.collection.mutable.ArrayBuffer
+import scala.sys.process._
+
+/**
+  * Runs `compare.py` on the two JSONL files [[OpExecHarness]] and
+  * [[StandaloneRunner]] wrote, and throws [[ComparatorMismatchException]]
+  * carrying the pandas diff when they differ. What counts as equal is
+  * compare.py's to say.
+  *
+  * The one thing decided here is row order: an operator that does not declare
+  * itself order-sensitive is compared with `--unordered`, which lex-sorts both
+  * frames first.
+  */
+object Comparator extends LazyLogging {
+
+  // Resource path is absolute (leading slash) so getResourceAsStream resolves
+  // against the classpath root regardless of caller's package.
+  private val ScriptResourcePath = "/python/compare.py"
+
+  def assertEqual(
+      actual: Path,
+      expected: Path,
+      orderSensitive: Boolean = true,
+      ignoreColumns: Seq[String] = Seq.empty,
+      modelColumns: Seq[String] = Seq.empty,
+      probePath: Option[Path] = None,
+      pythonExe: String = resolvePython()
+  ): Unit = {
+    val (exit, stdout, stderr) =
+      compare(actual, expected, orderSensitive, ignoreColumns, modelColumns, 
probePath, pythonExe)
+    if (exit != 0) {
+      throw new ComparatorMismatchException(
+        actual = actual,
+        expected = expected,
+        exitCode = exit,
+        stdout = stdout,
+        stderr = stderr
+      )
+    }
+  }
+
+  // Prefer a pooled persistent worker (imports pandas once via `compare.py
+  // --serve`, so the ~214 ms import isn't repaid per comparison — the diff
+  // itself is ~ms). A rare hard worker crash falls back to the one-shot CLI so
+  // behavior is never worse than the original path. Both invoke the same
+  // `_run_comparison`, so results are identical.
+  private def compare(
+      actual: Path,
+      expected: Path,
+      orderSensitive: Boolean,
+      ignoreColumns: Seq[String],
+      modelColumns: Seq[String],
+      probePath: Option[Path],
+      pythonExe: String
+  ): (Int, String, String) = {
+    if (PythonWorkerPool.enabled) {
+      try {
+        val req = objectMapper.createObjectNode()
+        req.put("actual", actual.toString)
+        req.put("expected", expected.toString)
+        req.put("unordered", !orderSensitive)
+        val ignoreArr = req.putArray("ignoreCols")
+        ignoreColumns.foreach(ignoreArr.add)
+        val modelArr = req.putArray("modelCols")
+        modelColumns.foreach(modelArr.add)
+        // --probe only applies with --model-cols (mirrors the CLI's guard).
+        probePath.filter(_ => modelColumns.nonEmpty) match {
+          case Some(p) => req.put("probe", p.toString)
+          case None    => req.putNull("probe")
+        }
+        val o = PythonWorkerPool.run(ScriptResourcePath, Seq("--serve"), 
pythonExe, req)
+        return (o.exit, o.stdout, o.stderr)
+      } catch {
+        case e: PythonWorkerPool.WorkerDiedException =>
+          logger.warn(
+            s"Comparator worker unavailable; falling back to one-shot CLI: 
${e.getMessage}"
+          )
+      }
+    }
+    runCli(actual, expected, orderSensitive, ignoreColumns, modelColumns, 
probePath, pythonExe)
+  }
+
+  // Original one-subprocess-per-comparison CLI path. Retained as the fallback
+  // and as the behavior selected by TEXERA_TEST_PYTHON_WORKER=0.
+  private def runCli(
+      actual: Path,
+      expected: Path,
+      orderSensitive: Boolean,
+      ignoreColumns: Seq[String],
+      modelColumns: Seq[String],
+      probePath: Option[Path],
+      pythonExe: String
+  ): (Int, String, String) = {
+    val scriptPath = extractScript()
+    val outBuf = ArrayBuffer.empty[String]
+    val errBuf = ArrayBuffer.empty[String]
+    val procLogger = ProcessLogger(line => outBuf += line, line => errBuf += 
line)
+    // --unordered tells compare.py to lex-sort both DataFrames by all columns
+    // before assert_frame_equal — needed for set-semantics ops whose JVM
+    // emission order doesn't match the pandas equivalent. Default stays
+    // positional so deterministic-order ops still catch row-order regressions.
+    // --ignore-cols drops opaque columns whose value isn't compared.
+    // --model-cols + --probe compare a model column by behavior: unpickle both
+    // sides and assert their predictions on the probe feature set match (two
+    // independently-trained models are functionally equal but not bit-equal).
+    val baseArgs = Seq(pythonExe, scriptPath.toString)
+    val flagArgs = if (!orderSensitive) Seq("--unordered") else Seq.empty
+    val ignoreArgs =
+      if (ignoreColumns.nonEmpty) Seq("--ignore-cols", 
ignoreColumns.mkString(",")) else Seq.empty
+    val modelArgs =
+      if (modelColumns.nonEmpty) Seq("--model-cols", 
modelColumns.mkString(",")) else Seq.empty
+    val probeArgs =
+      probePath
+        .filter(_ => modelColumns.nonEmpty)
+        .map(p => Seq("--probe", p.toString))
+        .getOrElse(Seq.empty)
+    val cmd =
+      baseArgs ++ flagArgs ++ ignoreArgs ++ modelArgs ++ probeArgs ++ Seq(
+        actual.toString,
+        expected.toString
+      )
+    val exit = Process(cmd).!(procLogger)
+    (exit, outBuf.mkString("\n"), errBuf.mkString("\n"))
+  }
+
+  // Resources may live inside a jar at runtime; copy to a temp file so Python
+  // can exec it. deleteOnExit so test runs don't accumulate /tmp clutter.
+  private def extractScript(): Path = {
+    val stream = getClass.getResourceAsStream(ScriptResourcePath)
+    require(
+      stream != null,
+      s"compare.py not found on classpath at $ScriptResourcePath"
+    )
+    try {
+      val tmp = Files.createTempFile("compare-", ".py")
+      Files.copy(stream, tmp, StandardCopyOption.REPLACE_EXISTING)
+      tmp.toFile.deleteOnExit()
+      tmp
+    } finally stream.close()
+  }
+
+  private def resolvePython(): String =
+    sys.env.get("UDF_PYTHON_PATH").filter(_.nonEmpty).getOrElse("python3.12")
+}
+
+final class ComparatorMismatchException(
+    val actual: Path,
+    val expected: Path,
+    val exitCode: Int,
+    val stdout: String,
+    val stderr: String
+) extends RuntimeException(
+      s"""DataFrame mismatch (compare.py exit $exitCode):
+         |  actual:   $actual
+         |  expected: $expected
+         |--- stderr ---
+         |$stderr""".stripMargin
+    )
diff --git 
a/workflow-compiling-service/src/test/scala/org/apache/texera/amber/translator/verify/ComparatorSpec.scala
 
b/workflow-compiling-service/src/test/scala/org/apache/texera/amber/translator/verify/ComparatorSpec.scala
new file mode 100644
index 0000000000..da41526c34
--- /dev/null
+++ 
b/workflow-compiling-service/src/test/scala/org/apache/texera/amber/translator/verify/ComparatorSpec.scala
@@ -0,0 +1,702 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.texera.amber.translator.verify
+
+import org.apache.texera.amber.core.tuple.{Attribute, AttributeType, Schema, 
Tuple}
+import org.apache.texera.amber.translator.verify.tags.IntegrationTest
+import org.apache.texera.amber.util.JSONUtils.objectMapper
+import org.scalatest.flatspec.AnyFlatSpec
+import org.scalatest.matchers.should.Matchers
+
+import java.nio.file.{Files, Path, StandardCopyOption}
+import java.util.concurrent.TimeUnit
+import scala.io.Source
+
+// Tagged @IntegrationTest: Comparator.assertEqual shells out to compare.py, so
+// this spec needs Python and must run in the Python-provisioned integration 
job.
+@IntegrationTest
+class ComparatorSpec extends AnyFlatSpec with Matchers {
+
+  private val schema: Schema = Schema()
+    .add(new Attribute("id", AttributeType.INTEGER))
+    .add(new Attribute("name", AttributeType.STRING))
+
+  private val idAttr = new Attribute("id", AttributeType.INTEGER)
+  private val nameAttr = new Attribute("name", AttributeType.STRING)
+
+  private def row(id: Int, name: String): Tuple =
+    Tuple
+      .builder(schema)
+      .add(idAttr, Int.box(id))
+      .add(nameAttr, name)
+      .build()
+
+  private def writeJsonl(dir: Path, name: String, rows: Seq[Tuple]): Path = {
+    val p = dir.resolve(name)
+    TupleIO.writeTuples(p, rows.iterator, schema)
+    p
+  }
+
+  // Written by hand rather than through TupleIO: these cases need a column set
+  // the fixed schema above does not carry.
+  private def writeLines(dir: Path, name: String, lines: Seq[String]): Path = {
+    val p = dir.resolve(name)
+    Files.writeString(p, lines.map(_ + "\n").mkString)
+    p
+  }
+
+  "Comparator.assertEqual" should "pass when JSONL files contain identical 
rows" in {
+    val dir = Files.createTempDirectory("comparator-spec-equal-")
+    val rows = Seq(row(1, "alice"), row(2, "bob"))
+    val a = writeJsonl(dir, "a.jsonl", rows)
+    val b = writeJsonl(dir, "b.jsonl", rows)
+    noException should be thrownBy Comparator.assertEqual(a, b)
+  }
+
+  it should "throw ComparatorMismatchException when JSONL files differ" in {
+    val dir = Files.createTempDirectory("comparator-spec-diff-")
+    val a = writeJsonl(dir, "a.jsonl", Seq(row(1, "alice"), row(2, "bob")))
+    val b = writeJsonl(dir, "b.jsonl", Seq(row(1, "alice"), row(2, "carol")))
+    intercept[ComparatorMismatchException] {
+      Comparator.assertEqual(a, b)
+    }
+  }
+
+  it should "treat row-reordered files as unequal under positional comparison" 
in {
+    val dir = Files.createTempDirectory("comparator-spec-reorder-strict-")
+    val a = writeJsonl(dir, "a.jsonl", Seq(row(1, "alice"), row(2, "bob")))
+    val b = writeJsonl(dir, "b.jsonl", Seq(row(2, "bob"), row(1, "alice")))
+    intercept[ComparatorMismatchException] {
+      Comparator.assertEqual(a, b)
+    }
+  }
+
+  it should "treat row-reordered files as equal under orderSensitive=false" in 
{
+    val dir = Files.createTempDirectory("comparator-spec-reorder-loose-")
+    val a = writeJsonl(dir, "a.jsonl", Seq(row(1, "alice"), row(2, "bob")))
+    val b = writeJsonl(dir, "b.jsonl", Seq(row(2, "bob"), row(1, "alice")))
+    noException should be thrownBy Comparator.assertEqual(a, b, orderSensitive 
= false)
+  }
+
+  it should "still report value mismatches under orderSensitive=false" in {
+    // orderSensitive=false relaxes row ORDER, not row CONTENT — a genuinely
+    // different cell must still fail.
+    val dir = 
Files.createTempDirectory("comparator-spec-reorder-content-diff-")
+    val a = writeJsonl(dir, "a.jsonl", Seq(row(1, "alice"), row(2, "bob")))
+    val b = writeJsonl(dir, "b.jsonl", Seq(row(2, "bob"), row(1, "carol")))
+    intercept[ComparatorMismatchException] {
+      Comparator.assertEqual(a, b, orderSensitive = false)
+    }
+  }
+
+  // Sorting on the float first paired 1.0 with 1.0 across the two sides, which
+  // put "a" beside "b". The exact column has to decide the pairing.
+  it should "pair rows by their exact columns before a float under 
orderSensitive=false" in {
+    val dir = Files.createTempDirectory("comparator-spec-reorder-float-")
+    val a = writeLines(dir, "a.jsonl", Seq("""{"x":1.0,"s":"a"}""", 
"""{"x":1.000001,"s":"b"}"""))
+    val b = writeLines(dir, "b.jsonl", Seq("""{"x":1.000001,"s":"a"}""", 
"""{"x":1.0,"s":"b"}"""))
+    noException should be thrownBy Comparator.assertEqual(a, b, orderSensitive 
= false)
+  }
+
+  // With no exact column, sorting on x put 1.0 first on both sides, which put
+  // y = 10.0 beside y = 100.0. Rows are paired within tolerance on every 
float.
+  it should "pair rows within tolerance across every float under 
orderSensitive=false" in {
+    val dir = Files.createTempDirectory("comparator-spec-reorder-two-floats-")
+    val doubles = Schema()
+      .add(new Attribute("x", AttributeType.DOUBLE))
+      .add(new Attribute("y", AttributeType.DOUBLE))
+    def write(name: String, rows: Seq[(Double, Double)]): Path = {
+      val p = dir.resolve(name)
+      val tuples = rows.map {
+        case (x, y) =>
+          Tuple
+            .builder(doubles)
+            .add(doubles.getAttribute("x"), Double.box(x))
+            .add(doubles.getAttribute("y"), Double.box(y))
+            .build()
+      }
+      TupleIO.writeTuples(p, tuples.iterator, doubles)
+      p
+    }
+    val a = write("a.jsonl", Seq((1.0, 10.0), (1.000001, 100.0)))
+    noException should be thrownBy Comparator.assertEqual(
+      a,
+      write("b.jsonl", Seq((1.000001, 10.0), (1.0, 100.0))),
+      orderSensitive = false
+    )
+    intercept[ComparatorMismatchException] {
+      Comparator.assertEqual(
+        a,
+        write("c.jsonl", Seq((1.000001, 10.0), (1.0, 99.0))),
+        orderSensitive = false
+      )
+    }
+  }
+
+  // The tolerance a double needs was being applied to integers as well, so two
+  // whole numbers a workflow would never call the same compared equal. The
+  // declared type is what separates them: a double keeps the tolerance.
+  private val longSchema: Schema = Schema().add(new Attribute("n", 
AttributeType.LONG))
+
+  private def writeLongs(dir: Path, name: String, values: 
Seq[java.lang.Long]): Path = {
+    val p = dir.resolve(name)
+    val rows =
+      values.map(v => 
Tuple.builder(longSchema).add(longSchema.getAttribute("n"), v).build())
+    TupleIO.writeTuples(p, rows.iterator, longSchema)
+    p
+  }
+
+  it should "reject two integers the float tolerance would have accepted" in {
+    val dir = Files.createTempDirectory("comparator-spec-long-tolerance-")
+    val a = writeLongs(dir, "a.jsonl", Seq(100000L))
+    val b = writeLongs(dir, "b.jsonl", Seq(100001L))
+    intercept[ComparatorMismatchException] {
+      Comparator.assertEqual(a, b)
+    }
+  }
+
+  it should "reject a nullable integer that only a rounding read made equal" 
in {
+    // A null widens the column to float on the way into pandas, and 
9007199254740993
+    // is already 9007199254740992 before anything compares it.
+    val dir = Files.createTempDirectory("comparator-spec-long-precision-")
+    val a = writeLongs(dir, "a.jsonl", Seq(9007199254740993L, null))
+    val b = writeLongs(dir, "b.jsonl", Seq(9007199254740992L, null))
+    intercept[ComparatorMismatchException] {
+      Comparator.assertEqual(a, b)
+    }
+  }
+
+  it should "keep the tolerance a double needs" in {
+    val dir = Files.createTempDirectory("comparator-spec-double-tolerance-")
+    val doubleSchema = Schema().add(new Attribute("x", AttributeType.DOUBLE))
+    def write(name: String, v: Double): Path = {
+      val p = dir.resolve(name)
+      val row =
+        Tuple.builder(doubleSchema).add(doubleSchema.getAttribute("x"), 
Double.box(v)).build()
+      TupleIO.writeTuples(p, Iterator(row), doubleSchema)
+      p
+    }
+    noException should be thrownBy Comparator.assertEqual(
+      write("a.jsonl", 1.000001),
+      write("b.jsonl", 1.0000011)
+    )
+  }
+
+  it should "reject an integer column only one side widened to a float" in {
+    // This passed on the grounds that 6.0 and 6 spell the same integer. They 
do
+    // not survive the same: a later cast to text writes "6" from one and "6.0"
+    // from the other.
+    val dir = Files.createTempDirectory("comparator-spec-int-spelling-")
+    val a = writeLongs(dir, "a.jsonl", Seq(6L))
+    val b = writeLines(dir, "b.jsonl", Seq("""{"n":6.0}"""))
+    intercept[ComparatorMismatchException] {
+      Comparator.assertEqual(a, b)
+    }.getMessage should include("the two sides wrote it differently")
+  }
+
+  it should "accept an integer column both sides widened alike" in {
+    // Where the engine's own path is a Python operator its table goes through
+    // pandas too, so a hole widens the column on both paths and the two still
+    // agree. What is asked here is whether the paths match, not whether pandas
+    // kept the type.
+    val dir = Files.createTempDirectory("comparator-spec-int-both-widened-")
+    // writeLongs for the schema sidecar it leaves; the rows are then rewritten
+    // as the widened form both paths would have produced. The null is the hole
+    // that widened it, and float64 has to hold it too.
+    val a = writeLongs(dir, "a.jsonl", Seq(6L, null))
+    Files.writeString(a, "{\"n\":6.0}\n{\"n\":null}\n")
+    val b = writeLines(dir, "b.jsonl", Seq("""{"n":6.0}""", """{"n":null}"""))
+    noException should be thrownBy Comparator.assertEqual(a, b)
+  }
+
+  // The comparison took its columns from the actual side and selected those 
out
+  // of the expected one, so a column only the expected side carried was never
+  // looked at.
+  it should "report a column only one side carries" in {
+    val dir = Files.createTempDirectory("comparator-spec-extra-column-")
+    val a = writeLines(dir, "a.jsonl", Seq("""{"id":1,"name":"alice"}"""))
+    val b = writeLines(dir, "b.jsonl", 
Seq("""{"id":1,"name":"alice","extra":9}"""))
+
+    intercept[ComparatorMismatchException] {
+      Comparator.assertEqual(a, b)
+    }.getMessage should include("only in expected")
+
+    intercept[ComparatorMismatchException] {
+      Comparator.assertEqual(b, a)
+    }.getMessage should include("only in actual")
+  }
+
+  // Column order is part of the schema: it decides what a positional UDF 
reads,
+  // what a file export writes, and what code asking for the first column gets.
+  it should "treat column-reordered files as unequal" in {
+    val dir = Files.createTempDirectory("comparator-spec-column-order-")
+    val a = writeLines(dir, "a.jsonl", Seq("""{"a":1,"b":2}"""))
+    val b = writeLines(dir, "b.jsonl", Seq("""{"b":2,"a":1}"""))
+    intercept[ComparatorMismatchException] {
+      Comparator.assertEqual(a, b)
+    }.getMessage should include("different order")
+  }
+
+  // Reading both sides with `dtype=str` settles them on one spelling, which a
+  // text column needs, but it reads the JSON number 6 as "6" just as readily, 
so
+  // a side that wrote a number where the engine declared text compared equal 
to
+  // the text. What the file actually holds is what separates them.
+  it should "reject a number written where the schema declares text" in {
+    val dir = Files.createTempDirectory("comparator-spec-text-number-")
+    val textSchema = Schema().add(new Attribute("code", AttributeType.STRING))
+    val a = dir.resolve("a.jsonl")
+    TupleIO.writeTuples(
+      a,
+      Iterator(Tuple.builder(textSchema).add(textSchema.getAttribute("code"), 
"6").build()),
+      textSchema
+    )
+    val b = writeLines(dir, "b.jsonl", Seq("""{"code":6}"""))
+
+    intercept[ComparatorMismatchException] {
+      Comparator.assertEqual(a, b)
+    }.getMessage should include("declared text but holds 6")
+  }
+
+  // numpy counts True as 1 and the frame comparison is asked not to check
+  // dtypes, so a column of booleans compared equal to a column of ones. The
+  // engine says a BOOLEAN column holds true and false.
+  it should "reject a number written where the schema declares a boolean" in {
+    val dir = Files.createTempDirectory("comparator-spec-bool-number-")
+    val boolSchema = Schema().add(new Attribute("flag", AttributeType.BOOLEAN))
+    val a = dir.resolve("a.jsonl")
+    TupleIO.writeTuples(
+      a,
+      Iterator(
+        Tuple.builder(boolSchema).add(boolSchema.getAttribute("flag"), 
Boolean.box(true)).build()
+      ),
+      boolSchema
+    )
+    val b = writeLines(dir, "b.jsonl", Seq("""{"flag":1}"""))
+
+    intercept[ComparatorMismatchException] {
+      Comparator.assertEqual(a, b)
+    }.getMessage should include("the two sides wrote it differently")
+  }
+
+  it should "accept a boolean column both sides widened alike" in {
+    // A hole costs a pandas boolean column its type on both paths alike, so
+    // both write the true as 1.0 next to the null.
+    val dir = Files.createTempDirectory("comparator-spec-bool-both-widened-")
+    val boolSchema = Schema().add(new Attribute("flag", AttributeType.BOOLEAN))
+    val a = dir.resolve("a.jsonl")
+    TupleIO.writeTuples(
+      a,
+      Iterator(
+        Tuple.builder(boolSchema).add(boolSchema.getAttribute("flag"), 
Boolean.box(true)).build()
+      ),
+      boolSchema
+    )
+    Files.writeString(a, "{\"flag\":1.0}\n{\"flag\":null}\n")
+    val b = writeLines(dir, "b.jsonl", Seq("""{"flag":1.0}""", 
"""{"flag":null}"""))
+    noException should be thrownBy Comparator.assertEqual(a, b)
+  }
+
+  // Both files are UTF-8. Read with the platform's encoding, a text value
+  // outside ASCII failed to decode, and a LONG column whose name is outside
+  // ASCII lost its declared type and went back under the float tolerance.
+  it should "read a name and a value outside ASCII as the UTF-8 they are" in {
+    val dir = Files.createTempDirectory("comparator-spec-utf8-")
+    val utf8Schema = Schema()
+      .add(new Attribute("é", AttributeType.LONG))
+      .add(new Attribute("v", AttributeType.STRING))
+    def write(name: String, n: Long): Path = {
+      val p = dir.resolve(name)
+      val row = Tuple
+        .builder(utf8Schema)
+        .add(utf8Schema.getAttribute("é"), Long.box(n))
+        .add(utf8Schema.getAttribute("v"), "ひ")
+        .build()
+      TupleIO.writeTuples(p, Iterator(row), utf8Schema)
+      p
+    }
+    val a = write("a.jsonl", 100000L)
+
+    noException should be thrownBy Comparator.assertEqual(a, 
write("same.jsonl", 100000L))
+    intercept[ComparatorMismatchException] {
+      Comparator.assertEqual(a, write("b.jsonl", 100001L))
+    }.getMessage should include("100001")
+  }
+
+  // What kind of value each DOUBLE cell holds used to be added to the frame as
+  // a column with a made-up name. An output column of that name was 
overwritten
+  // on both sides alike, so a difference in it went unseen.
+  it should "not let a DOUBLE column's kinds hide an output column" in {
+    val dir = Files.createTempDirectory("comparator-spec-double-kind-name-")
+    val collidingSchema = Schema()
+      .add(new Attribute("v", AttributeType.DOUBLE))
+      .add(new Attribute("v (null/NaN/±Infinity/-0.0)", AttributeType.STRING))
+    def write(name: String, text: String): Path = {
+      val p = dir.resolve(name)
+      val row = Tuple
+        .builder(collidingSchema)
+        .add(collidingSchema.getAttribute("v"), Double.box(1.0))
+        .add(collidingSchema.getAttribute("v (null/NaN/±Infinity/-0.0)"), text)
+        .build()
+      TupleIO.writeTuples(p, Iterator(row), collidingSchema)
+      p
+    }
+    val a = write("a.jsonl", "before")
+    val b = write("b.jsonl", "after")
+
+    intercept[ComparatorMismatchException] {
+      Comparator.assertEqual(a, b)
+    }.getMessage should include("after")
+    intercept[ComparatorMismatchException] {
+      Comparator.assertEqual(a, b, orderSensitive = false)
+    }.getMessage should include("after")
+  }
+
+  it should "report a model column only one side produced" in {
+    // Model columns are compared by behavior and then dropped from both 
frames,
+    // so a side that never wrote one has to fail here: once the column is 
gone,
+    // the frame diff sees two identical column sets and passes.
+    val dir = Files.createTempDirectory("comparator-spec-model-missing-")
+    val withModel = writeLines(dir, "with-model.jsonl", 
Seq("""{"model":"eA==","score":1.0}"""))
+    val withoutModel = writeLines(dir, "without-model.jsonl", 
Seq("""{"score":1.0}"""))
+    val probe = writeLines(dir, "probe.jsonl", 
Seq("""{"petal_length":1.0,"label":0}"""))
+
+    intercept[ComparatorMismatchException] {
+      Comparator.assertEqual(
+        withModel,
+        withoutModel,
+        modelColumns = Seq("model"),
+        probePath = Some(probe)
+      )
+    }.getMessage should include("missing from expected")
+
+    intercept[ComparatorMismatchException] {
+      Comparator.assertEqual(
+        withoutModel,
+        withModel,
+        modelColumns = Seq("model"),
+        probePath = Some(probe)
+      )
+    }.getMessage should include("missing from actual")
+  }
+
+  /** A model column holds a pickled estimator, which only Python can fit. 
Writes
+    * the two one-row frames the comparison reads and the probe it predicts on,
+    * each side's model fitted on its own targets and its own feature column.
+    * The probe carries both columns, with the same values.
+    */
+  private def writeFittedModels(
+      dir: Path,
+      estimator: String,
+      actualTargets: String,
+      expectedTargets: String,
+      actualFeature: String = "petal_length",
+      expectedFeature: String = "petal_length"
+  ): (Path, Path, Path) = {
+    val program =
+      s"""import base64, json, pickle
+         |import pandas as pd
+         |from sklearn.tree import $estimator as Estimator
+         |
+         |x = pd.DataFrame({"petal_length": [1.0, 2.0, 3.0], "petal_width": 
[1.0, 2.0, 3.0]})
+         |x.to_json(r"$dir/probe.jsonl", orient="records", lines=True)
+         |for name, y, feature in (
+         |    ("actual.jsonl", $actualTargets, "$actualFeature"),
+         |    ("expected.jsonl", $expectedTargets, "$expectedFeature"),
+         |):
+         |    model = 
base64.b64encode(pickle.dumps(Estimator().fit(x[[feature]], y))).decode()
+         |    with open(rf"$dir/{name}", "w", encoding="utf-8") as handle:
+         |        handle.write(json.dumps({"model": model, "score": 1.0}) + 
"\\n")
+         |""".stripMargin
+    runPython(program)
+    (dir.resolve("actual.jsonl"), dir.resolve("expected.jsonl"), 
dir.resolve("probe.jsonl"))
+  }
+
+  private def runPython(program: String): Unit = {
+    val script = Files.createTempFile("comparator-spec-fit-", ".py")
+    script.toFile.deleteOnExit()
+    Files.writeString(script, program)
+
+    val python = 
sys.env.get("UDF_PYTHON_PATH").filter(_.nonEmpty).getOrElse("python3")
+    val process =
+      new ProcessBuilder(python, 
script.toString).redirectErrorStream(true).start()
+    val said = Source.fromInputStream(process.getInputStream).mkString
+    process.waitFor(120, TimeUnit.SECONDS)
+    require(process.exitValue() == 0, s"fitting the models failed:\n$said")
+  }
+
+  // A classifier predicts a class, and a class that changed is a different
+  // answer however near the two labels sit. Numbered classes went through the
+  // numeric tolerance, where 100000 and 100001 are one part in 1e5 apart and
+  // compared equal, so every row's class could change and the models still 
pass.
+  it should "catch a classifier whose predicted classes all changed" in {
+    val dir = Files.createTempDirectory("comparator-spec-model-classes-")
+    val (actual, expected, probe) =
+      writeFittedModels(dir, "DecisionTreeClassifier", "[100000] * 3", 
"[100001] * 3")
+
+    intercept[ComparatorMismatchException] {
+      Comparator.assertEqual(
+        actual,
+        expected,
+        modelColumns = Seq("model"),
+        probePath = Some(probe)
+      )
+    }.getMessage should include("predictions differ")
+  }
+
+  // What a model was fitted on is part of the model. Two fitted on different
+  // columns answer alike on a probe carrying both, so only the names part 
them.
+  it should "catch two models fitted on different columns that predict alike" 
in {
+    val dir = Files.createTempDirectory("comparator-spec-model-features-")
+    val (actual, expected, probe) =
+      writeFittedModels(
+        dir,
+        "DecisionTreeClassifier",
+        "[0, 1, 1]",
+        "[0, 1, 1]",
+        expectedFeature = "petal_width"
+      )
+
+    intercept[ComparatorMismatchException] {
+      Comparator.assertEqual(
+        actual,
+        expected,
+        modelColumns = Seq("model"),
+        probePath = Some(probe)
+      )
+    }.getMessage should include("fitted feature names differ")
+  }
+
+  // The tolerance still has to reach what it was for: a regressor computes its
+  // answer, so the two paths can land a float's last bits apart on the same 
fit.
+  it should "allow a regressor's predictions to differ within tolerance" in {
+    val dir = Files.createTempDirectory("comparator-spec-model-regressor-")
+    val (actual, expected, probe) =
+      writeFittedModels(
+        dir,
+        "DecisionTreeRegressor",
+        "[1.0, 2.0, 3.0]",
+        "[1.0, 2.0, 3.0 + 1e-12]"
+      )
+
+    noException should be thrownBy Comparator.assertEqual(
+      actual,
+      expected,
+      modelColumns = Seq("model"),
+      probePath = Some(probe)
+    )
+  }
+
+  // Unordered rows were paired only after the models had been compared by
+  // position, so a model could change rows and still pass.
+  it should "keep each model beside its row under orderSensitive=false" in {
+    val dir = Files.createTempDirectory("comparator-spec-model-unordered-")
+    runPython(
+      s"""import base64, json, pickle
+         |import pandas as pd
+         |from sklearn.tree import DecisionTreeClassifier
+         |
+         |x = pd.DataFrame({"petal_length": [1.0, 2.0, 3.0]})
+         |x.to_json(r"$dir/probe.jsonl", orient="records", lines=True)
+         |def predicting(c):
+         |    model = DecisionTreeClassifier().fit(x, [c] * 3)
+         |    return base64.b64encode(pickle.dumps(model)).decode()
+         |for name, rows in (
+         |    ("rows.jsonl", [(1, 0), (2, 1)]),
+         |    ("reversed.jsonl", [(2, 1), (1, 0)]),
+         |    ("swapped.jsonl", [(2, 0), (1, 1)]),
+         |    ("tied.jsonl", [(1, 0), (1, 1)]),
+         |    ("tied-reversed.jsonl", [(1, 1), (1, 0)]),
+         |    ("tied-changed.jsonl", [(1, 1), (1, 1)]),
+         |):
+         |    with open(rf"$dir/{name}", "w", encoding="utf-8") as handle:
+         |        for id, c in rows:
+         |            handle.write(json.dumps({"id": id, "model": 
predicting(c)}) + "\\n")
+         |""".stripMargin
+    )
+    def compare(expected: String, actual: String = "rows.jsonl"): Unit =
+      Comparator.assertEqual(
+        dir.resolve(actual),
+        dir.resolve(expected),
+        orderSensitive = false,
+        modelColumns = Seq("model"),
+        probePath = Some(dir.resolve("probe.jsonl"))
+      )
+
+    noException should be thrownBy compare("reversed.jsonl")
+    intercept[ComparatorMismatchException] {
+      compare("swapped.jsonl")
+    }.getMessage should include("predictions differ")
+    // Two rows with the same id tie on every sorted column, so the sort kept
+    // them in file order and compared their models the wrong way round.
+    noException should be thrownBy compare("tied-reversed.jsonl", "tied.jsonl")
+    intercept[ComparatorMismatchException] {
+      compare("tied-changed.jsonl", "tied.jsonl")
+    }.getMessage should include("predictions differ")
+  }
+
+  // An operator that draws a chart per row writes one JSONL row per chart on 
the
+  // runtime side and an array on the exported one. Reading a single figure 
from
+  // each, as this did, left every chart after the first unread.
+  private def plotlyFigure(value: Int): String =
+    s"""{"data": [{"type": "indicator", "value": $value}], "layout": {}}"""
+
+  /** compare.py --plotly, as its own process: the exit code and what it said. 
*/
+  private def runPlotly(actual: Path, expected: Path): (Int, String) = {
+    val script = Files.createTempFile("compare-", ".py")
+    script.toFile.deleteOnExit()
+    val stream = getClass.getResourceAsStream("/python/compare.py")
+    require(stream != null, "compare.py not found at /python/compare.py")
+    try Files.copy(stream, script, StandardCopyOption.REPLACE_EXISTING)
+    finally stream.close()
+
+    val python = 
sys.env.get("UDF_PYTHON_PATH").filter(_.nonEmpty).getOrElse("python3")
+    val process = new ProcessBuilder(
+      python,
+      script.toString,
+      "--plotly",
+      actual.toString,
+      expected.toString
+    ).redirectErrorStream(true).start()
+    val said = Source.fromInputStream(process.getInputStream).mkString
+    process.waitFor(120, TimeUnit.SECONDS)
+    (process.exitValue(), said)
+  }
+
+  "Comparator's plotly comparison" should "read every chart on both sides" in {
+    val dir = Files.createTempDirectory("comparator-spec-plotly-all-")
+    val actual = writeLines(
+      dir,
+      "actual.jsonl",
+      Seq(1, 2, 3).map(v => s"""{"json-content": ${plotlyFigure(v)}}""")
+    )
+    val expected = writeLines(
+      dir,
+      "expected.json",
+      Seq(Seq(1, 2, 3).map(plotlyFigure).mkString("[", ",", "]"))
+    )
+    val (exit, said) = runPlotly(actual, expected)
+    withClue(s"compare.py said:\n$said") { exit shouldBe 0 }
+  }
+
+  it should "catch a chart that differs after the first" in {
+    val dir = Files.createTempDirectory("comparator-spec-plotly-second-")
+    val actual = writeLines(
+      dir,
+      "actual.jsonl",
+      Seq(1, 2, 3).map(v => s"""{"json-content": ${plotlyFigure(v)}}""")
+    )
+    val expected = writeLines(
+      dir,
+      "expected.json",
+      Seq(Seq(1, 99, 3).map(plotlyFigure).mkString("[", ",", "]"))
+    )
+    val (exit, said) = runPlotly(actual, expected)
+    withClue(s"compare.py said:\n$said") {
+      exit should not be 0
+      said should include("chart 2 of 3")
+    }
+  }
+
+  it should "catch an exported script that drew fewer charts than the run" in {
+    val dir = Files.createTempDirectory("comparator-spec-plotly-count-")
+    val actual = writeLines(
+      dir,
+      "actual.jsonl",
+      Seq(1, 2, 3).map(v => s"""{"json-content": ${plotlyFigure(v)}}""")
+    )
+    val expected = writeLines(dir, "expected.json", Seq(plotlyFigure(1)))
+    val (exit, said) = runPlotly(actual, expected)
+    withClue(s"compare.py said:\n$said") {
+      exit should not be 0
+      said should include("drew 3")
+      said should include("drew 1")
+    }
+  }
+
+  // The operators that draw one chart write a lone figure, and there are far
+  // more of those than there are of the other kind.
+  it should "still read a lone figure as the one chart it is" in {
+    val dir = Files.createTempDirectory("comparator-spec-plotly-one-")
+    val actual = writeLines(dir, "actual.jsonl", Seq(s"""{"json-content": 
${plotlyFigure(7)}}"""))
+    val expected = writeLines(dir, "expected.json", Seq(plotlyFigure(7)))
+    val (exit, said) = runPlotly(actual, expected)
+    withClue(s"compare.py said:\n$said") { exit shouldBe 0 }
+  }
+
+  // A bullet or gauge chart draws its charts onto one page and yields that 
page
+  // as a single row. Every call on a page is a chart to compare, whichever 
side
+  // the page is on.
+  private def plotlyPage(values: Int*): String =
+    values
+      .map(v =>
+        s"""<div><script>Plotly.newPlot("div$v", """ +
+          s"""[{"type": "indicator", "value": $v}], {}, {"responsive": 
true})</script></div>"""
+      )
+      .mkString
+
+  /** A page as the runtime path hands it over: one JSONL row, markup escaped. 
*/
+  private def plotlyPageRow(values: Int*): String = {
+    val node = objectMapper.createObjectNode()
+    node.put("html-content", plotlyPage(values: _*))
+    objectMapper.writeValueAsString(node)
+  }
+
+  it should "read every chart on a page the run drew as one row" in {
+    val dir = Files.createTempDirectory("comparator-spec-plotly-page-")
+    val actual = writeLines(dir, "actual.jsonl", Seq(plotlyPageRow(1, 2, 3)))
+    val expected = writeLines(dir, "expected.html", Seq(plotlyPage(1, 2, 3)))
+    val (exit, said) = runPlotly(actual, expected)
+    withClue(s"compare.py said:\n$said") { exit shouldBe 0 }
+  }
+
+  it should "catch a chart after the first on a page the script wrote" in {
+    val dir = Files.createTempDirectory("comparator-spec-plotly-page-second-")
+    val actual = writeLines(dir, "actual.jsonl", Seq(plotlyPageRow(1, 2, 3)))
+    val expected = writeLines(dir, "expected.html", Seq(plotlyPage(1, 99, 3)))
+    val (exit, said) = runPlotly(actual, expected)
+    withClue(s"compare.py said:\n$said") {
+      exit should not be 0
+      said should include("chart 2 of 3")
+    }
+  }
+
+  // `bool` is a subclass of `int` in Python, so a boolean setting fell into 
the
+  // numeric branch and True compared equal to 1. A column whose declared type
+  // changed from boolean to integer reaches a figure as exactly that.
+  it should "treat a boolean setting and the number 1 as different" in {
+    val dir = Files.createTempDirectory("comparator-spec-plotly-bool-")
+    val actual = writeLines(
+      dir,
+      "actual.jsonl",
+      Seq("""{"json-content": {"data": [{"visible": true}], "layout": {}}}""")
+    )
+    def expected(visible: String): Path =
+      writeLines(
+        dir,
+        s"expected-$visible.json",
+        Seq(s"""{"data": [{"visible": $visible}], "layout": {}}""")
+      )
+
+    val (asNumber, said) = runPlotly(actual, expected("1"))
+    withClue(s"compare.py said:\n$said") { asNumber should not be 0 }
+    val (asBoolean, alsoSaid) = runPlotly(actual, expected("true"))
+    withClue(s"compare.py said:\n$alsoSaid") { asBoolean shouldBe 0 }
+  }
+}

Reply via email to