Skip to content

fix: TEST_MODE bypass crashes on ordered-parameter assertion ties #1519

Closed

Description

@Jammy2211

Overview

PYAUTO_TEST_MODE=2/3 bypasses the sampler and evaluates the model at the prior
medians. A model whose components carry identical priors plus an ordering
assertion — the standard idiom for breaking exchange degeneracy, e.g. PyAutoCTI
trap models with model.add_assertion(trap_0.release_timescale < trap_1.release_timescale)
— ties exactly at those medians, so check_assertions raises
exc.FitException("N assertions failed!") and the script hard-fails. A real
sampler absorbs this by resampling; the bypass has no sampler, so a purely
bypass-path artifact takes down the run.

This blocks autocti_workspace smoke coverage of modeling/start_here.py-class
scripts (CTI resurrection epic, Phase 5). The workspace currently documents the
artifact in its AGENTS.md as a workaround.

Plan

  • Reuse the deterministic valid-point search that TEST_MODE=1 already has
    (_test_mode_samples_after_rejected_fit): prior medians first, then a
    fixed-seed sequence of prior draws, validating each candidate.
  • Extract that search into a shared helper on NonLinearSearch and have the
    bypass pick its evaluation point through it, instead of hard-coding the
    medians.
  • Because the point the bypass stores is then assertion-valid, TEST_MODE=2,
    TEST_MODE=3 and the downstream result.max_log_likelihood_instance all work
    without changing what assertions mean.
  • Keep the existing FitException guard around the likelihood call — it covers a
    different failure (a pathological likelihood, not an invalid instance).
  • Regression tests for a tied ordering assertion at TEST_MODE 2 and 3, plus a
    negative case where no valid point exists.
Detailed implementation plan

Work Classification

Library — PyAutoFit source only. No workspace changes in this task.

Affected Repositories

  • PyAutoFit (primary)

Branch Survey

Repository Current Branch Dirty?
./PyAutoFit main (d3625a8) clean

Suggested branch: feature/test-mode-bypass-assertion-ties

Worktree root: ~/Code/PyAutoLabs-wt/test-mode-bypass-assertion-ties/
(created later by /start_library)

worktree_check_conflict test-mode-bypass-assertion-ties PyAutoFit → exit 0, no
conflict; no active.md entry claims PyAutoFit.

Root cause (verified against main @ d3625a8)

Three sites, not one. The prompt's own 2026-08-09 note found the first; the
other two mean the suggested one-liners do not get a run to completion.

  1. autofit/non_linear/search/abstract_search.py:1007-1008 — the model
    instantiation sits outside the try that catches exc.FitException:

    if call_likelihood:
        instance = model.instance_from_vector(vector=parameter_vector)   # <-- outside
        try:
            log_likelihood = float(analysis.log_likelihood_function(instance))
        except exc.FitException as e:
            ...

    instance_from_vector → instance_for_arguments → check_assertions
    (autofit/mapper/prior_model/abstract.py:193) is exactly what raises on a
    tie, so the assertion exception escapes the guard entirely.

  2. _build_fake_samples (abstract_search.py:1112) — the four fake samples
    are the median vector scaled by 1.001 / 0.999 / 1.002. A uniform scale
    preserves an ordering tie, so every stored sample fails the same
    assertion, not just the first.

  3. SamplesSummary.max_log_likelihood
    (autofit/non_linear/samples/interface.py:122)
    — decorated @to_instance(),
    i.e. recover="raise" (SamplesSummary extends SamplesInterface directly and
    does not inherit Samples' next-valid recovery). So
    result.max_log_likelihood_instance re-instantiates the stored vector and
    raises exc.SamplesException; Result.instance
    (autofit/non_linear/result.py:115) catches only AttributeError, so it
    propagates.

Consequence: PYAUTO_TEST_MODE=3 is broken too. Mode 3 never calls
instance_from_vector inside the bypass, so it survives the fit and then dies at
the first result.max_log_likelihood_instance. Neither of the prompt's suggested
one-liners (move the call into the try; pass ignore_assertions=True) covers
mode 3 or site 3.

Chosen approach

Make the bypass evaluate and store a point that satisfies the assertions,
rather than tolerating an invalid one. This keeps the assertion contract intact
(a tied median is simply not a point the bypass should evaluate) and fixes all
three sites at once, because sites 2 and 3 both derive from the stored vector.

Precedent: _test_mode_samples_after_rejected_fit (abstract_search.py:786-860)
already implements exactly this search for TEST_MODE=1 — medians first, then
np.random.default_rng(seed=0) prior draws, each candidate validated before
return, capped at TEST_MODE_REPRESENTATIVE_MAX_ATTEMPTS. Deterministic, so
smoke runs stay reproducible.

Implementation Steps

  1. autofit/non_linear/search/abstract_search.py — add
    _test_mode_valid_parameter_vector(model) returning the first
    assertion-valid parameter_vector: attempt 0 is [0.5] * model.prior_count,
    attempts 1..TEST_MODE_REPRESENTATIVE_MAX_ATTEMPTS are
    np.random.default_rng(seed=0) draws mapped through
    model.vector_from_unit_vector. Validate each candidate with
    model.instance_from_vector(...), catching only exc.FitException. Exhausting
    the budget raises exc.FitException naming the attempt count, chained to the
    last rejection (mirrors the existing :857 behaviour).

  2. _fit_bypass_test_mode (:1000-1006) — replace the hard-coded
    unit_vector = [0.5] * model.prior_count / vector_from_unit_vector pair with
    the helper. Log once at WARNING when attempt 0 was rejected, so a tied model
    is visible in smoke output rather than silently relocated.

  3. _test_mode_samples_after_rejected_fit — refactor onto the same helper.
    Behaviour-preserving; removes the duplicated draw loop.

  4. Leave the likelihood-call guard at :1013 in place. It catches a
    pathological likelihood (non-PD inversion, degenerate mesh) and is a
    separate contract from an invalid instance; TestBypassToleratesFitException
    must keep passing.

  5. Do not perturb the fake-sample vectors. Sample 0 stays the unperturbed
    valid base and carries the highest likelihood, which is what every downstream
    accessor reads.

  6. test_autofit/non_linear/search/test_abstract_search.py — new
    TestBypassToleratesAssertionTies alongside TestBypassToleratesFitException
    (:434):

    • a af.Collection of two components with identical priors plus
      model.add_assertion(a.value < b.value);
    • at PYAUTO_TEST_MODE=2 and at =3: search.fit(...) completes and
      result.max_log_likelihood_instance materialises;
    • negative case: an assertion no draw can satisfy still raises after the
      attempt budget, chained to the last rejection.

Key Files

  • autofit/non_linear/search/abstract_search.py — the bypass
    (_fit_bypass_test_mode), the fake samples (_build_fake_samples), and the
    mode-1 valid-point search to be shared.
  • autofit/mapper/prior_model/abstract.py:193 — check_assertions, the raise
    site.
  • autofit/non_linear/samples/interface.py:11,122 — to_instance recovery
    policy and SamplesSummary.max_log_likelihood.
  • autofit/non_linear/result.py:115 — Result.instance, which does not absorb
    SamplesException.
  • test_autofit/non_linear/search/test_abstract_search.py — bypass test home.

Testing

  • pytest test_autofit/non_linear/search/test_abstract_search.py
  • Full test_autofit suite — assertions sit on the mapper hot path.
  • Ship gate: vitals faculty → PyAutoHeart readiness before PR.

Out of scope / follow-up

  • autocti_workspace documents this artifact in its AGENTS.md. Once this
    ships, that note should be deleted rather than left behind — the
    testmode-env-drift precedent ("delete the trap, don't document it"). Separate
    task, separate repo.
  • Re-enabling autocti_workspace smoke coverage of the modeling/start_here.py
    class of scripts (CTI epic Phase 5) is the downstream unblock, not part of this
    PR.

Original Prompt

Click to expand starting prompt

TEST_MODE bypass crashes on ordered-parameter assertion ties

Type: bug
Target: PyAutoFit
Repos:

  • @PyAutoFit
    Difficulty: small
    Autonomy: supervised
    Priority: normal
    Status: formalised — STILL REPRODUCES; see the 2026-08-09 note before grading this against main
    Filed: 2026-07-17 (backfilled from git)

2026-08-09 — do NOT mistake the adjacent FitException catch for this fix

Checked by the draft/ sweep against PyAutoFit main (3b960609). The bypass path
in abstract_search.py now catches exc.FitException and continues with the
-1e99 sentinel, logging "TEST MODE 2: likelihood verification raised
FitException … treating as a resample-rejected instance". That reads exactly like
this prompt's suggested fix. It is not. The bug below still reproduces.

The catch wraps only the likelihood call. The model instantiation is on the line
before the try:

if call_likelihood:
    instance = model.instance_from_vector(vector=parameter_vector)   # <-- outside
    try:
        log_likelihood = float(analysis.log_likelihood_function(instance))
    except exc.FitException as e:
        ...

and instance_from_vector → instance_for_arguments → check_assertions
(autofit/mapper/prior_model/abstract.py:193) is precisely what raises
exc.FitException("N assertions failed!") when an ordering assertion ties at the
prior medians. ignore_assertions defaults to False and the bypass does not
pass it. So the assertion exception escapes the guard entirely and still
hard-fails the run.

The upside: the fix is now a one-liner rather than the "catch and retry with a
perturbation" design sketched below. Two options, both cheap and both
deterministic:

  • move the instance_from_vector call inside the existing try — the sentinel
    path already does the right thing for a rejected instance; or
  • pass ignore_assertions=True at the bypass instantiation, on the grounds that
    a verification eval at the medians is not a sampled point and assertions exist
    to steer sampling.

The second is probably the better semantics (a tied median is not a pathological
model), but it changes what the verification eval attests to — pick deliberately.
Prefer either over adding perturbation logic.

Difficulty: stays small. The § Blocks note below still holds.


Found during the CTI resurrection epic (Phase 4, 2026-07-17). PYAUTO_TEST_MODE=2/3
bypass evaluates the model at the prior medians. A model whose components have
identical priors plus an ordering assertion (the standard idiom for breaking
exchange degeneracy, e.g. PyAutoCTI trap models with
model.add_assertion(trap_0.release_timescale < trap_1.release_timescale))
ties exactly at the medians, so the bypass evaluation raises
autofit.exc.FitException: GreaterThanLessThanAssertion and the script crashes.

Real samplers resample assertion-failing points gracefully — this is purely a
bypass-path artifact, and it makes every ordered-trap CTI workspace script
un-smokeable at TEST_MODE=2 (reproduced with a bare
model.instance_from_prior_medians(); TEST_MODE=1 passes).

Suggested fix: at the bypass evaluation, catch FitException from assertions
and retry with a small deterministic perturbation of the unit-cube point (or a
seeded random draw), mirroring what a real sampler does. Keep it deterministic
so smoke runs stay reproducible.

Blocks: autocti_workspace smoke coverage of modeling/start_here.py-class
scripts (CTI epic Phase 5); the workspace documents the artifact in its
AGENTS.md meanwhile.

Activity

  1. Jammy2211 commented on Aug 24, 2026

    @Jammy2211
    CollaboratorAuthor

    Shipped

    PR: #1520 — merged as 438f56fac (branch feature/test-mode-bypass-assertion-ties proven an ancestor of main, 0 unmerged commits).

    CI at merge: Docs ✅ · Tests ✅ — all three legs (unittest (3.12), unittest (3.13), unittest-nojax) green on head d49275c33.

    What shipped

    The bypass now picks its evaluation point through _test_mode_valid_parameter_vector — prior medians first, then np.random.default_rng(seed=0) prior draws, each candidate validated — instead of hard-coding the medians. Because the accepted vector is also what gets stored in the fake samples, this closes all three failure sites at once, not just the reported one.

    Notes worth keeping

    • The reported one-liner would not have fixed it. Both options in the original prompt (move instance_from_vector into the try; pass ignore_assertions=True) address only site 1. Sites 2 and 3 — uniformly-scaled fake samples preserving the tie, and SamplesSummary.max_log_likelihood being @to_instance() with recover="raise" — would still have killed the run at result.max_log_likelihood_instance.
    • PYAUTO_TEST_MODE=3 was broken too, which nothing had noticed: it never calls the likelihood, so it survived the fit and died later at result access. Reproduced before the fix and verified after.
    • Behaviour change to flag for downstream: mode 3 now instantiates the model once (previously zero times). A model whose constructor raises a non-FitException at the medians now fails at fit time rather than result time — same failure, surfaced earlier.
    • Mode 1's recovery path was refactored onto the same helper but is behaviour-preserving, including its exact failure message.

    Verification

    Reproduced on clean main first (mode 2 died in the fit; mode 3 died at result access), then confirmed fixed with both modes selecting the identical vector. All 5 new tests in TestBypassToleratesAssertionTies fail against the un-patched source. Full suite: 2016 passed / 34 skipped / 0 failed locally, and green on all CI legs.

    Gate caveat: pyauto-heart was unreachable from the shipping session, so the readiness gate ran in the WORKFLOW.md fallback form (full library suite as the gate). CI green on merge is the stronger confirmation, but no Heart verdict was recorded for this task.

    Follow-up (not in this PR)

    autocti_workspace documents this artifact in its AGENTS.md as a workaround. That note should now be deleted rather than left behind — the testmode-env-drift precedent, "delete the trap, don't document it". Separate task, separate repo. Re-enabling the Phase 5 smoke coverage this unblocks is likewise its own task.


    Generated by Claude Code

  2. added a commit that references this issue on Aug 27, 2026
    d49275c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions