The behavioral fixture in this playbook has not been run; all case outcomes are EXPECTED / NOT EXECUTED. The source-inspection record reports that the installed scikit-learn 1.8.0 implementation used a deterministic stride of max(1, n_rows // 100) for its inverse sanity check, performed that check only when both func and inverse_func were non-None, and compared through a helper using rtol=1e-7 and atol=1e-9. The recorded SHA-256 for the inspected functiontransformer.py was 3dbc32841cd438de0d1e59a9a5d2e1813b8fc60beb465c0d2939db68960ab2d0. Those are preparation records, not behavioral observations.
The central counterexample is deliberately small in concept and large enough to cross the inspected sampling boundary. Start with 200 source rows containing positive integers 1..200, square them, and use square root as the inverse. Now replace row r001 with -2. Mathematically, sqrt((-2)^2) is +2, so that source record is not reconstructed. Under the inspected stride-two fit-time selection, position one is omitted. The expected result is therefore uncomfortable but useful: no inverse warning from fit, while an independent all-row gate rejects r001 with absolute error 4.
That is the operational question here: not whether FunctionTransformer(check_inverse=True) is useful (it is), but whether the evidence it produces is sufficient for a stricter application contract requiring every retained source row to survive a forward/inverse round-trip. The answer requires three distinct evidence classes: what the library sampled, what warning policy did with the result, and what a separately retained complete population demonstrates.
The release vocabulary is equally strict. ACCEPT means the bounded population and controls pass. REPAIR means the domain, callables, or gate is known to be wrong. RERUN means evidence identity changed. HOLD means provenance or semantic suitability remains unresolved.
Define the source-row reconstruction contract
The contract is intentionally narrower than “the transform is invertible.” For this laboratory, the source population is an ordered sequence of immutable records with sidecar identifiers r000 through r199 and one numeric feature per record. The baseline feature array is dense NumPy float64, shape (200, 1), finite throughout. The independently retained source values are the authority; neither transformed values nor inverse output may be used to regenerate the expected source.
The ordinary admitted domain for the initial positive control is x > 0. The sign-loss counterexample deliberately introduces one record outside that positive domain so that the review can distinguish a domain breach from a fit-time sampling miss. If the application subsequently chooses a nonnegative-only policy, that admission rule becomes an explicit contract rather than an accidental property of the test data.
The complete application gate requires the same row population, the same IDs in the same order, one feature, float64, finite values, and reconstruction within rtol=0, atol=1e-12, equal_nan=False. Shape and dtype are checked strictly before numerical acceptance. That tolerance is an authored policy for these small, exactly representable fixture values. It is not a recommendation for arbitrary engineering units.
This distinction matters because scikit-learn documents check_inverse=True as a sanity check that can warn when func followed by inverse_func does not lead back to the original inputs. It does not document the parameter as an exhaustive mathematical proof or a complete application-level row audit.
Nor does every useful preprocessing operation need to preserve every source value. This playbook applies only where reconstruction is itself an acceptance requirement. That is a different problem from categorical representation collisions, where category identity can become ambiguous through encoding policy. Here, feature identity stays fixed; the question is whether a numeric record was actually reconstructed.
Freeze the runtime and identify the inspected implementation
Treat the requested package set as a reproducibility baseline, not as a “latest versions” recommendation. scikit-learn’s own 1.8 release notes identify 1.8.0 as a December 2025 release. The controlled runtime is CPython 3.12.14 with scikit-learn 1.8.0, NumPy 2.3.5, SciPy 1.17.0, joblib 1.5.3, and threadpoolctl 3.6.0.
Create the environment outside any production interpreter:
python3.12 -m venv .venv-check-inverse
. .venv-check-inverse/bin/activate
python -m pip install --upgrade pip
python -m pip install \
numpy==2.3.5 \
scipy==1.17.0 \
joblib==1.5.3 \
threadpoolctl==3.6.0 \
scikit-learn==1.8.0
python check_inverse_repro.pyThe executable must reject the wrong Python patch level or dependency versions before evaluating a case. It must also record actual runtime facts (sys.version, platform.platform(), platform.machine(), package versions, Python executable, source path, and the SHA-256 of the installed functiontransformer.py) rather than replacing them with expected strings.
The source distinction is important. The exact-version implementation was inspected locally during preparation. Separately, the official moving main branch currently shows checkinverse_transform building idx_selected = slice(None, None, max(1, X.shape[0] // 100)), round-tripping only X[idx_selected], and calling the check from fit only when check_inverse is true and neither callable is None. The moving branch corroborates the recorded structure; it is not proof of the exact installed 1.8.0 file.
Before reproducing implementation-specific sampling behavior, recompute the local hash. A different hash means investigate and RERUN. It does not, by itself, prove behavior changed. Likewise, do not couple production code to private helpers or private sampling internals.
That source-identity discipline is related to fitted-transformer provenance, but this laboratory does not reproduce caching or cloned-estimator behavior. Its provenance problem is narrower: identify exactly which FunctionTransformer implementation was inspected and which runtime produced the evidence.
Author the fixture and expected manifest before execution
Write the expected outcomes before running the harness. That prevents a warning count, mismatch location, or accidental pass from silently becoming the specification.
The immutable source starts as integers 1..200 converted once to float64 and reshaped to (200, 1). IDs are independent strings. Every case receives a fresh array copy and a fresh transformer instance. The canonical source record remains unchanged outside those copies.
BASE_VALUES = np.arange(1, 201, dtype=np.float64).reshape(-1, 1)
BASE_IDS = tuple(f"r{i:03d}" for i in range(200))
BASE_VALUES.setflags(write=False)Input digests should cover bytes, dtype, and shape; order digests should cover the ordered sidecar IDs. Callable identity should be represented by explicit names and a reviewed revision string, not anonymous lambdas. The API documentation notes that func=None and inverse_func=None each mean identity behavior, and that validate=True converts input to a two-dimensional NumPy array or sparse matrix if possible. This fixture uses dense arrays only.
Keep expected failures outside the transformer
Every row below is EXPECTED / NOT EXECUTED.
Case | Controlled change | Expected evidence and application outcome |
C01 | All 200 positive inputs; square then square root | EXPECTED / NOT EXECUTED: No inverse warning; complete round-trip accepted for this bounded control. |
C02 | Replace value 2 at position 1, ID r001, with -2 | EXPECTED / NOT EXECUTED: Stride-two check omits r001; no inverse warning; full result returns +2 there; reject reconstruction. |
C03 | Swap positions 0 and 1 in C02, moving IDs with values | EXPECTED / NOT EXECUTED: Same records, negative now sampled; UserWarning under capture policy; fit normally returns; full gate still rejects r001. |
C04 | Apply scoped warning-to-error policy separately to C03 and C02 | EXPECTED / NOT EXECUTED: C03 raises the inverse warning as an exception; C02 has no such warning to promote and still fails full validation. |
C05 | 199-row version with the negative at position 1 | EXPECTED / NOT EXECUTED: Stride one examines all 199 rows; warning expected; full gate rejects. |
C06 | 201-row version with the negative at position 1 | EXPECTED / NOT EXECUTED: Stride two examines 101 rows; negative remains omitted; full gate rejects. |
C07 | C03 with check_inverse=False | EXPECTED / NOT EXECUTED: Sanity check bypassed; absence of its warning changes no reconstructed values; reject. |
C08 | C01 with inverse_func=None and square as func | EXPECTED / NOT EXECUTED: Pinned fit skips inverse check; inverse method acts as identity; squared values violate source contract. |
C09 | Explicit nonnegative-domain admission before square/root | EXPECTED / NOT EXECUTED: Positive fixture admitted; negative fixture rejected before transformation; no clamping, dropping, or absolute-value conversion. |
C10 | Replace pair with f(x)=2*x+3, inverse (z-3)/2 | EXPECTED / NOT EXECUTED: Signed fixture restored under declared tolerance; complete gate and controls still required. |
C04 has two subarms, C04-C03-error and C04-C02-error; they are not extra top-level cases. The harness should reject an evidence package unless all top-level IDs C01 through C10 and both C04 subarms are present.
The manifest is independent of scikit-learn’s warning. It states application expectations about complete source reconstruction. That distinction lets a case “pass” as a diagnostic test because it correctly catches a bad candidate while the candidate itself receives REPAIR or HOLD.
Read check_inverse as a bounded sanity check
The API wording should control interpretation: check_inverse is described as checking whether func followed by inverse_func leads to the original inputs, usable as a “sanity check,” with a warning when the condition is not fulfilled. The custom-transformer guide uses broader prose (“ensure that func and inverse_func are the inverse of each other”) and demonstrates that the warning can be promoted to an exception. Read that convenience wording together with the API and implementation rather than as a claim of exhaustive mathematical certification.
The inspected implementation makes the limitation concrete. On current main, fit first performs its configured validation, then calls checkinverse_transform only when check_inverse is enabled and both callables are explicit. The check constructs a deterministic slice and computes the round-trip only on that slice.
Under the recorded 1.8.0 formula:
stride = max(1, n_rows // 100)
selected positions = 0, stride, 2*stride, ...For 200 rows, 200 // 100 == 2, so positions 0, 2, 4, ..., 198 are selected. There are 100 selected positions. Position 1 is not among them.
Do not generalize that into “FunctionTransformer always checks 100 rows.” For 201 rows the same stride is two but positions 0..200 inclusive at even indices produce 101 rows. For 199 rows, integer division gives one, so every row is selected.
This is deterministic slicing, not random sampling. Row order therefore affects detection under this implementation. That is an implementation-specific observation to verify at reproduction time, not a public compatibility promise.
Establish the positive numeric baseline
C01 answers a basic but necessary question: can the harness recognize a bounded case that should reconstruct successfully?
For the authored values 1..200, square(x) = x*x produces finite nonnegative values. sqrt(square(x)) equals the original values because every source value is positive. That is a mathematical property of this fixture, not an executed scikit-learn observation.
The expected evidence is:
C01: EXPECTED / NOT EXECUTED
input shape: (200, 1)
forward shape: (200, 1)
inverse shape: (200, 1)
input dtype: float64
inverse dtype: float64
captured inverse warning: none expected
mismatch IDs: []
application decision: ACCEPT for this bounded controlA positive control is not ceremonial. If C01 fails the independent gate, there is no basis for interpreting C02 as a sampling-specific failure. The likely suspects would include fixture construction, callable implementation, order reconciliation, dtype policy, environment drift, or the gate itself.
Shape alone is not acceptance. A transformation can preserve (200, 1) while changing values. That is why this workflow is deliberately separate from imputer output-schema validation: schema preservation asks whether the feature interface remains acceptable; the present gate asks whether retained numeric source records are reconstructed.
Likewise, a warning-free fit is only one column in the evidence ledger. It cannot substitute for a full source comparison.
Reproduce the omitted negative row
C02 changes exactly one source value: at position one, sidecar ID r001, replace +2 with -2. Do not change its identifier. Do not drop it. Do not reorder the population.
The forward operation gives:
square(-2) = 4The nominal inverse gives:
sqrt(4) = 2Therefore the expected reconstruction error for that source record is:
|2 - (-2)| = 4The forward array remains finite. Its shape remains (200, 1). Neither fact answers whether the inverse preserved the record.
Under the recorded 1.8.0 slice formula, position one is omitted when n_rows=200, so the fit-time check is expected not to see this negative row. Thus C02 is the key separation:
library sanity-check warning: EXPECTED absent
complete source reconstruction: EXPECTED failureThat does not make the warning mechanism defective. It means its evidence scope is narrower than the application contract.
Trace fit-time inputs without changing the transformation
Instrumentation should observe, not repair. Wrap the forward callable so it logs which source IDs correspond to values received during the fit-time inverse check, then return exactly the same square operation. Keep row IDs outside the feature matrix.
The cleanest trace is phase-scoped. Before fit, set the observer phase to "fit". After fit, freeze that trace and switch to "full" before any complete transformation. Never mingle the fit-time sample with later calls made by the acceptance gate.
Because the source values in these fixtures are unique, an observer can map each received source value back to the retained value -> ID sidecar. If that assumption changes, use a separately constructed positional reconciliation table rather than relying on value uniqueness.
Expected C02 trace:
C02 fit trace: EXPECTED / NOT EXECUTED
selected IDs:
r000, r002, r004, ..., r198
omitted IDs include:
r001
negative source record:
r001 = -2.0
negative observed during fit:
EXPECTED falseThe trace is independent evidence that the relevant record was or was not presented to the user callable during the check. It should not call a private scikit-learn selector to decide what it “ought” to have seen; that would duplicate the implementation instead of observing it.
Change row order and cross the sampling boundaries
C03 preserves the same records as C02 but swaps positions zero and one, moving IDs with values. The negative record r001 now occupies position zero. Under stride two, position zero is selected, so the inverse mismatch becomes visible to the fit-time sanity check.
The expected result is a UserWarning, while ordinary fit still returns unless warning policy changes. The moving implementation calls warnings.warn(..., UserWarning) when its comparison fails. Python warning handling is policy-controlled: matching warnings may be displayed, ignored, always emitted, or promoted to exceptions.
Crucially, moving the record did not repair the transformation. The complete gate should still report r001 and absolute error 4. Detection changed; semantic failure did not.
C05 and C06 show why the row count belongs in the evidence ledger. For a 199-row fixture, the recorded formula gives 199 // 100 == 1, so every source position is inspected. A negative at position one is therefore expected to generate the warning. For 201 rows, 201 // 100 == 2, so the sampled indices are even positions from zero through 200; position one remains omitted.
Count selected rows instead of repeating a convenient limit
The expected counts are mechanically derived:
Rows | Stride | Selected positions | Selected count | Status |
199 | 1 | 0..198 | 199 | EXPECTED / NOT EXECUTED |
200 | 2 | 0,2,...,198 | 100 | EXPECTED / NOT EXECUTED |
201 | 2 | 0,2,...,200 | 101 | EXPECTED / NOT EXECUTED |
That table is specific to the inspected formula. The reproduction must compute the installed source hash first and retain the actual observer trace. If the hash differs, do not “adjust expectations until green.” Mark implementation-dependent cases RERUN, inspect the local source, revise the expected manifest in review, and then execute a new evidence run.
No probability language belongs here. This is not a random sample with a detection probability. It is a deterministic row selection whose membership follows from row count and order.
Build a complete independent acceptance gate
The application gate must be deliberately stronger than check_inverse. It should reject incomplete populations, rearranged identities, shape or dtype drift, non-finite values, and numerically incorrect reconstruction before emitting an acceptance decision.
Start with identity and completeness. The observed ID tuple must exactly equal the retained source ID tuple. A set comparison is insufficient because it cannot detect order changes or duplicates. The source array and reconstructed array must have identical shape and float64 dtype.
Then require finiteness on source, forward output, and inverse output. Finally compare the entire reconstructed array against the independently retained source with np.testing.assert_allclose(..., rtol=0, atol=1e-12, equal_nan=False, strict=True).
NumPy documents that assert_allclose raises when values exceed the chosen tolerance, and that strict=True additionally rejects shape or dtype mismatch. Its documentation also notes the default equal_nan=True, which is why this gate must explicitly override it with False.
This is preferable to using a naked np.allclose boolean as the sole gate. np.allclose uses broadcasting, so differently shaped arrays can compare true when broadcast-compatible; its relative term is referenced to the second operand, and its defaults are not a universal application policy.
The independent gate should still compute element-level diagnostics itself so rejected cases retain mismatch IDs and absolute errors rather than only an exception string.
The reconstruction problem here is distinct from original-length evidence for FFT reconstruction. That workflow depends on reconstructing a commissioned signal with original-length metadata. This one keeps array width unchanged and demonstrates a value-level information loss that a sampled check may not encounter.
Keep identity and completeness separate from numeric closeness
An acceptance sequence should look like this:
Reconcile required case and subarm IDs.
Reconcile ordered source IDs exactly.
Verify source and reconstructed shape exactly.
Verify declared dtype exactly.
Require finite source, forward, and inverse arrays.
Run strict full-array comparison.
Derive every mismatching row ID and absolute error.
Verify that negative controls actually fail.
Emit the application decision only after evidence completeness succeeds.
Do not compare a subset against a full source through broadcasting. Do not sort rows to make values align. Do not infer expected source values from inverse output. Do not ask the transformer’s private selector which records need validation.
A missing case is evidence failure, not a pass. If C06 was never executed because C05 raised unexpectedly, the final report must say C06 NOT EXECUTED and the release decision must be RERUN or HOLD.
Declare the tolerance and its limits
The gate’s rtol=0, atol=1e-12 policy is intentionally different from the preparation record for the library helper (rtol=1e-7, atol=1e-9). The library comparison answers the library’s sanity-check question. The application comparison answers a narrower, reviewed source-reconstruction question.
The fixture values are small integers, and the two callable pairs are chosen so expected behavior is easy to derive. That does not justify copying 1e-12 into measurements expressed in volts, dollars, probabilities, concentrations, timestamps, or other domains.
Include a deliberate wrong-value control inside the gate:
wrong = original.copy()
wrong[10, 0] += 1.0The gate must reject it and identify r010. If it accepts that control, the evidence harness is defective and all candidate decisions become HOLD until repaired.
Separate warning policy from inverse configuration
C04, C07, and C08 prevent three common category errors.
First, a warning can only be promoted if it is issued. Python’s warning filter supports an "error" action that turns matching warnings into exceptions, while catch_warnings provides scoped control so global warning behavior need not be modified. Therefore the expected C04 behavior is asymmetric: the reordered C03 arm issues the inverse warning and the scoped rule raises it; the C02 arm does not issue that warning, so there is nothing to promote.
Second, C07 sets check_inverse=False. That intentionally bypasses the library sanity check. The reconstructed value of r001 remains wrong. A quieter fit is not a semantic repair.
Third, C08 keeps func=square but sets inverse_func=None. The public API documents None as identity behavior for an absent callable. The inspected implementation calls the fit-time inverse check only when both callables are non-None. Thus the expected fit-time result is no inverse sanity check, followed by an inverse_transform that leaves squared values squared. That violates the declared reconstruction contract for almost every source row.
Configuration evidence must therefore record both callable names and check_inverse. “No warning” without those fields is uninterpretable.
Repair the domain contract or replace the callable pair
C09 and C10 represent two legitimate but different repairs.
C09 says square/root is approved only for a declared nonnegative input domain. Before creating the transformer, an admission guard checks every retained source row. Negative values cause an explicit domain exception tied to their source IDs. There is no clamping to zero, no abs, no dropping, and no silent substitution.
That repair is valid only if the application’s actual source contract excludes negative values. It is not valid to redefine the contract merely because the chosen inverse cannot recover signs.
C10 handles the alternative: signed values are legitimate, so select a pair that preserves them. For this controlled comparison:
def affine_forward(x):
return 2.0 * x + 3.0
def affine_inverse(z):
return (z - 3.0) / 2.0For the bounded authored fixture, algebra gives exact source recovery in real arithmetic. The implementation must still pass the complete numeric gate because floating-point execution, runtime identity, row completeness, and harness correctness remain evidence questions.
The affine pair is not asserted to be better preprocessing in general. It is simply a signed-domain control showing that an appropriate callable design can satisfy this particular reconstruction contract.
Whichever policy is chosen, version the domain rule and callable revision together. Then rerun C01–C10 and both C04 subarms. A policy repair does not inherit acceptance from an earlier candidate.
Reconcile all ten cases in one evidence ledger
The following script is the complete proposed reproduction. It is NOT EXECUTED here. It uses fresh FunctionTransformer instances, dense finite float64 arrays, sidecar IDs, scoped warning handling, source hashing, an environment guard, observer traces, strict all-row reconciliation, and a final required-case check.
# check_inverse_repro.py
# STATUS: NOT EXECUTED
from future import annotations
import hashlib
import importlib.metadata as md
import inspect
import json
import os
import platform
import sys
import warnings
from dataclasses import dataclass
from pathlib import Path
import numpy as np
import sklearn
from numpy.testing import assert_allclose
from sklearn.preprocessing import FunctionTransformer
import sklearn.preprocessing._function_transformer as ftmod
EXPECTED_PYTHON = (3, 12, 14)
EXPECTED = {
"numpy": "2.3.5",
"scipy": "1.17.0",
"joblib": "1.5.3",
"threadpoolctl": "3.6.0",
"scikit-learn": "1.8.0",
}
EXPECTED_FT_SHA256 = (
"3dbc32841cd438de0d1e59a9a5d2e181"
"3b8fc60beb465c0d2939db68960ab2d0"
)
REQUIRED = {
"C01", "C02", "C03",
"C04-C03-error", "C04-C02-error",
"C05", "C06", "C07", "C08",
"C09-positive", "C09-negative", "C10",
}
ARTIFACT_DIR = Path("check_inverse_evidence")
BASE_VALUES = np.arange(1, 201, dtype=np.float64).reshape(-1, 1)
BASE_IDS = tuple(f"r{i:03d}" for i in range(200))
BASE_VALUES.setflags(write=False)
CALLABLE_REVISION = "fixture-v1"
ATOL = 1e-12
def sha256_bytes(b: bytes) -> str:
return hashlib.sha256(b).hexdigest()
def array_digest(x: np.ndarray) -> str:
h = hashlib.sha256()
h.update(str(x.shape).encode())
h.update(str(x.dtype).encode())
h.update(np.ascontiguousarray(x).tobytes())
return h.hexdigest()
def ids_digest(ids: tuple[str, ...]) -> str:
return sha256_bytes("\n".join(ids).encode())
def environment_guard() -> dict:
if sys.version_info[:3] != EXPECTED_PYTHON:
raise RuntimeError(
f"Python mismatch: got {sys.version_info[:3]}, "
f"expected {EXPECTED_PYTHON}"
)
actual_versions = {k: md.version(k) for k in EXPECTED}
if actual_versions != EXPECTED:
raise RuntimeError(
f"Package mismatch: {actual_versions!r} != {EXPECTED!r}"
)
source_path = Path(inspect.getsourcefile(ftmod)).resolve()
source_hash = sha256_bytes(source_path.read_bytes())
runtime = {
"python_version": sys.version,
"python_executable": sys.executable,
"platform": platform.platform(),
"machine": platform.machine(),
"processor": platform.processor(),
"packages": actual_versions,
"function_transformer_source": str(source_path),
"function_transformer_sha256": source_hash,
"expected_function_transformer_sha256": EXPECTED_FT_SHA256,
"hash_matches_preparation_record":
source_hash == EXPECTED_FT_SHA256,
"callable_revision": CALLABLE_REVISION,
}
if source_hash != EXPECTED_FT_SHA256:
raise RuntimeError(
"Installed functiontransformer.py hash differs from "
"the preparation record. Investigate before running "
"implementation-specific sampling cases."
)
return runtime
def square(x):
return np.square(x)
def root(x):
return np.sqrt(x)
def affine_forward(x):
return 2.0 x + 3.0
def affine_inverse(z):
return (z - 3.0) / 2.0
@dataclass
class Observer:
ids: tuple[str, ...]
source: np.ndarray
seen_fit_ids: list[str]
phase: str = "fit"
def map_rows(self, x: np.ndarray) -> list[str]:
mapping = {
float(v): rid
for rid, v in zip(self.ids, self.source[:, 0])
}
return [mapping[float(v)] for v in x[:, 0]]
def forward_square(self, x):
if self.phase == "fit":
self.seen_fit_ids.extend(self.map_rows(x))
return square(x)
def forward_affine(self, x):
if self.phase == "fit":
self.seen_fit_ids.extend(self.map_rows(x))
return affine_forward(x)
def make_records(n=200):
values = np.arange(1, n + 1, dtype=np.float64).reshape(-1, 1)
ids = tuple(f"r{i:03d}" for i in range(n))
return values, ids
def put_negative(values, position=1):
out = values.copy()
out[position, 0] = -abs(out[position, 0])
return out
def strict_gate(source, source_ids, reconstructed):
if tuple(source_ids) != tuple(source_ids):
raise RuntimeError("Internal ID reconciliation failure")
if source.shape != reconstructed.shape:
raise RuntimeError(
f"Shape mismatch: {source.shape} != {reconstructed.shape}"
)
if source.dtype != np.dtype(np.float64):
raise RuntimeError(f"Source dtype changed: {source.dtype}")
if reconstructed.dtype != np.dtype(np.float64):
raise RuntimeError(
f"Reconstructed dtype changed: {reconstructed.dtype}"
)
if not np.isfinite(source).all():
raise RuntimeError("Source contains non-finite values")
if not np.isfinite(reconstructed).all():
raise RuntimeError("Inverse output contains non-finite values")
delta = np.abs(reconstructed - source)[:, 0]
bad = delta > ATOL
mismatch_ids = [
rid for rid, flag in zip(source_ids, bad) if flag
]
max_error = float(delta.max(initial=0.0))
accepted = True
try:
assert_allclose(
reconstructed,
source,
rtol=0,
atol=ATOL,
equal_nan=False,
strict=True,
)
except AssertionError:
accepted = False
return {
"accepted": accepted,
"mismatch_ids": mismatch_ids,
"max_abs_error": max_error,
"shape": list(reconstructed.shape),
"dtype": str(reconstructed.dtype),
}
def capture_fit(transformer, x, promote=False):
records = []
outcome = "returned"
exception = None
try:
with warnings.catch_warnings(record=True) as caught:
if promote:
warnings.filterwarnings(
"error",
message=r".provided functions.*inverse.*",
category=UserWarning,
)
else:
warnings.simplefilter("always")
transformer.fit(x)
records = [
{
"category": w.category.__name__,
"message": str(w.message),
}
for w in caught
]
except Warning as exc:
outcome = "warning-raised-as-exception"
exception = {
"type": type(exc).__name__,
"message": str(exc),
}
except Exception as exc:
outcome = "exception"
exception = {
"type": type(exc).__name__,
"message": str(exc),
}
return outcome, records, exception
def roundtrip_direct(x, forward, inverse):
forward_out = np.asarray(forward(x.copy()), dtype=np.float64)
if not np.isfinite(forward_out).all():
raise RuntimeError("Forward output is non-finite")
inverse_out = np.asarray(inverse(forward_out.copy()), dtype=np.float64)
return forward_out, inverse_out
def run_case(
case_id,
x,
ids,
*,
forward,
inverse,
check_inverse=True,
promote=False,
inverse_is_none=False,
):
x = np.asarray(x, dtype=np.float64).copy()
ids = tuple(ids)
source = x.copy()
source.setflags(write=False)
observer = Observer(ids, source, [])
observed_forward = (
observer.forward_affine
if forward is affine_forward
else observer.forward_square
)
transformer = FunctionTransformer(
func=observed_forward,
inverse_func=None if inverse_is_none else inverse,
validate=True,
check_inverse=check_inverse,
)
fit_outcome, warning_records, exception = capture_fit(
transformer, x.copy(), promote=promote
)
fit_trace = tuple(observer.seen_fit_ids)
observer.phase = "full"
if inverse_is_none:
fwd = transformer.transform(x.copy())
inv = transformer.inverse_transform(fwd.copy())
else:
fwd, inv = roundtrip_direct(x, forward, inverse)
gate = strict_gate(source, ids, np.asarray(inv, dtype=np.float64))
return {
"case_id": case_id,
"input_digest": array_digest(source),
"order_digest": ids_digest(ids),
"n_rows": len(ids),
"check_inverse": check_inverse,
"inverse_is_none": inverse_is_none,
"fit_sampled_ids": list(fit_trace),
"fit_sampled_count": len(fit_trace),
"fit_outcome": fit_outcome,
"warnings": warning_records,
"exception": exception,
"forward_shape": list(np.asarray(fwd).shape),
"forward_dtype": str(np.asarray(fwd).dtype),
"gate": gate,
}
def domain_guard_nonnegative(x, ids):
bad = [
rid
for rid, value in zip(ids, x[:, 0])
if value < 0
]
if bad:
raise ValueError(f"Negative source rows rejected: {bad}")
def main():
ARTIFACT_DIR.mkdir(exist_ok=False)
runtime = environment_guard()
(ARTIFACT_DIR / "runtime.json").write_text(
json.dumps(runtime, indent=2)
)
ledger = []
# C01
x, ids = make_records(200)
ledger.append(run_case(
"C01", x, ids, forward=square, inverse=root
))
# C02
x2 = put_negative(x, 1)
ledger.append(run_case(
"C02", x2, ids, forward=square, inverse=root
))
# C03: move IDs with values
x3 = x2.copy()
x3[[0, 1]] = x3[[1, 0]]
ids3 = list(ids)
ids3[0], ids3[1] = ids3[1], ids3[0]
ids3 = tuple(ids3)
ledger.append(run_case(
"C03", x3, ids3, forward=square, inverse=root
))
# C04 subarms
ledger.append(run_case(
"C04-C03-error", x3, ids3,
forward=square, inverse=root, promote=True
))
ledger.append(run_case(
"C04-C02-error", x2, ids,
forward=square, inverse=root, promote=True
))
# C05
x5, ids5 = make_records(199)
x5 = put_negative(x5, 1)
ledger.append(run_case(
"C05", x5, ids5, forward=square, inverse=root
))
# C06
x6, ids6 = make_records(201)
x6 = put_negative(x6, 1)
ledger.append(run_case(
"C06", x6, ids6, forward=square, inverse=root
))
# C07
ledger.append(run_case(
"C07", x3, ids3, forward=square, inverse=root,
check_inverse=False
))
# C08
ledger.append(run_case(
"C08", x, ids, forward=square, inverse=root,
inverse_is_none=True
))
# C09 positive and negative admission
domain_guard_nonnegative(x, ids)
ledger.append(run_case(
"C09-positive", x, ids, forward=square, inverse=root
))
try:
domain_guard_nonnegative(x2, ids)
neg_status = "unexpectedly-admitted"
except ValueError as exc:
neg_status = f"rejected: {exc}"
ledger.append({
"case_id": "C09-negative",
"domain_outcome": neg_status,
"input_digest": array_digest(x2),
"order_digest": ids_digest(ids),
})
# C10 signed-domain replacement
ledger.append(run_case(
"C10", x2, ids,
forward=affine_forward, inverse=affine_inverse
))
# Gate negative control: must fail
wrong = x.copy()
wrong[10, 0] += 1.0
wrong_gate = strict_gate(x, ids, wrong)
if wrong_gate["accepted"]:
raise RuntimeError("Negative gate control unexpectedly passed")
if wrong_gate["mismatch_ids"] != ["r010"]:
raise RuntimeError(
f"Wrong negative-control mismatch IDs: "
f"{wrong_gate['mismatch_ids']}"
)
present = {row["case_id"] for row in ledger}
missing = sorted(REQUIRED - present)
report = {
"runtime": runtime,
"required_case_ids": sorted(REQUIRED),
"present_case_ids": sorted(present),
"missing_case_ids": missing,
"negative_gate_control": wrong_gate,
"ledger": ledger,
}
(ARTIFACT_DIR / "ledger.json").write_text(
json.dumps(report, indent=2)
)
if missing:
raise RuntimeError(f"Required evidence missing: {missing}")
print(json.dumps({
"status": "completed",
"artifact_dir": str(ARTIFACT_DIR),
"cases_present": len(present),
}, indent=2))
if name == "__main__":
main()The proposed evidence schema should retain, per case or subarm: input digest, order digest, configuration, expected and observed sampled IDs, fit outcome, warning records, output shape and dtype, mismatch IDs, maximum absolute error, application decision, execution status, and artifact path.
Expected application disposition, still NOT EXECUTED, is:
Evidence item | Expected candidate result |
C01 | control accepted |
C02 | bad square/root candidate rejected despite no expected warning |
C03 | warning detected; bad candidate still rejected |
C04-C03-error | warning expected to become exception |
C04-C02-error | no warning expected to promote; full gate rejects |
C05 | warning expected; full gate rejects |
C06 | warning expected absent; full gate rejects |
C07 | no inverse check; full gate rejects |
C08 | missing inverse configuration; full gate rejects |
C09 | domain policy accepts positive arm, rejects negative admission |
C10 | replacement pair expected to pass bounded complete gate |
A test “passes” when it produces its expected diagnostic behavior. That must never be confused with accepting the transformation under test.
Recover from retained source evidence
Recovery begins with preservation, not deletion. Keep the rejected output, warning records, trace, source and order digests, runtime manifest, callable revision, and mismatch diagnostics. They explain why a candidate failed and prevent a later rerun from erasing the evidence trail.
Build the repaired candidate from the immutable retained source records, not from the failed reconstruction. If the approved policy becomes nonnegative-only, re-admit the original records under that domain rule. If signed values are valid, use the reviewed replacement callable pair. In either case, instantiate a fresh transformer and generate a new evidence ledger.
Keep the previously accepted artifact in place until the replacement candidate has complete evidence. The release handoff belongs to the same general discipline as the broader MLOps artifact lifecycle, but this playbook limits itself to the preprocessing candidate and its bounded reconstruction evidence.
Cleanup should remove only temporary fixture outputs owned by this run and only after required evidence has been retained elsewhere. The disposable environment can then be deleted.
Do not recover lost signs from squared values
Once only a squared value remains, the source sign is not identifiable from that value. Both -2 and +2 map to 4. Applying square root later chooses the nonnegative magnitude; it does not recover the original sign.
Therefore a failed square/root round-trip cannot be repaired by changing an inverse setting after source provenance is lost. Recovery requires the retained immutable source record or another independently authoritative source.
If neither exists, the correct decision is HOLD. Guessing a sign, copying the inverse result into the source ledger, or declaring the value reconstructed because its magnitude matches would destroy the very provenance the gate is designed to protect.
Assign ownership and choose the release decision
The release decision should be produced from evidence, not from warning presence alone.
Decision | Release rule |
ACCEPT | Complete bounded source population passes identity, completeness, shape, dtype, finiteness, strict numerical reconstruction, and effective positive/negative controls. Required case evidence is complete. |
REPAIR | A specific callable, domain rule, warning policy, or acceptance-gate defect is demonstrated and has an identifiable correction. |
RERUN | Runtime, implementation hash, source population, row order, callable revision, tolerance policy, or required evidence changed. |
HOLD | Source provenance is unresolved, domain suitability is undecided, evidence is incomplete or contradictory, or discarded information cannot be authoritatively recovered. |
Assign three independent responsibilities. The callable/domain owner defines which inputs are legitimate and which forward/inverse semantics are approved. The fixture/evidence owner maintains immutable source construction, expected manifest, guards, controls, traces, digests, and artifact retention. The release reviewer verifies that acceptance follows the declared contract and that no expected failure was relabeled as a candidate pass.
The expected disposition for the original unrestricted square/root candidate is REPAIR or HOLD, not ACCEPT, because signed input loses information. A reviewed nonnegative-domain policy could become ACCEPT for an admitted finite population after execution. The affine replacement can likewise become ACCEPT only after its full evidence package actually passes.
Even then, the claim remains bounded. Acceptance of these retained rows under one runtime and one tolerance is not a proof that the callables are inverse functions for all possible floating-point inputs. Nor is it evidence of downstream estimator quality.
Develop reproducible preprocessing practice with Refonte Learning
The engineering habits in this playbook (explicit Python environments, NumPy array discipline, scikit-learn transformer behavior, statistical reasoning about numerical comparisons, and reproducible evidence) overlap with foundations listed for the Refonte Learning Data Science program. Its reviewed program page describes a three-month format at 12–14 hours per week and names Python Data Science, statistical modelling, machine learning and predictive modelling, model optimization, exploratory analysis, and industry projects; its FAQ also names Python, Jupyter Notebook, Pandas, NumPy, Matplotlib, scikit-learn, and TensorFlow.
Coverage of dedicated FunctionTransformer sampled-inverse auditing and this exact laboratory has not been confirmed. Engineers considering structured study can review the Data Science program syllabus and verify those specialized topics directly rather than assuming they are included.
