CP-SAT: incompatible-linear implication counts grow across presolve iterations with unchanged model size (9.15)

Aperta
#5,559 1 commento 0 reazioni 1 assegnatario Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

@lperron ci sta già lavorando.

Dal 3/11/2026.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
18/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
cpp, python
Ambito
backend

Direzione di ricerca

Start by running the reproduce.py script from the issue and comparing the presolve-1/2/3 logs. The relevant code is DetectDifferentVariables() in ortools/sat/cp_model_presolve.cc, PresolveContext::AddImplication() in ortools/sat/presolve_context.cc, the duplicate-removal rule counter, and the outer presolve iteration loop. Any fix needs to avoid re-emitting existing implications without changing presolve strength, and the maintainers must agree on the approach first.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Bug Lang: Python Solver: CP-SAT Solver
Version and environment
  • Official Python wheel: OR-Tools 9.15.6755, CP-SAT.
  • Standalone reproduction below: Python 3.10.20, macOS/arm64.
  • No OR-Tools source modifications. I have not built or tested the current development branch.
Observed behavior

A small synthetic model repeatedly triggers incompatible linear: add implication and subsequent duplicate-constraint removal when the maximum presolve iteration count increases. The final reported variable, constraint, and term counts remain unchanged.

Maximum iterations Actual iterations incompatible linear: add implication duplicate: removed constraint Presolved variables Constraints Terms
1 1 15 0 36 60 150
2 2 30 15 36 60 150
3 3 45 30 36 60 150

With the limit set to 3, DetectDuplicateConstraints reports #duplicates=15 at the start of both later iterations. The model starts with 51 variables, 15 exactly-one constraints, and 30 enforced linear constraints. Each of its 15 unordered pairs has two incompatible guarded time inequalities and a third skip choice.

The script intentionally uses stop_after_presolve=True: UNKNOWN is expected here, and search is not performed. Each solve has a one-second limit. This tiny example demonstrates the counter pattern, not a meaningful wall-time regression.

Standalone reproducer

Install ortools==9.15.6755, save the following as reproduce.py, and run python reproduce.py. It writes the three full logs in the current directory and prints the table fields above.

"""Small CP-SAT presolve-only reproducer; no application code or input data."""
import itertools
import json
import platform
import re
from pathlib import Path

import ortools
from ortools.sat.python import cp_model


def build_model():
    model = cp_model.CpModel()
    times = [model.new_int_var(0, 100, f"t{i}") for i in range(6)]
    skips = []
    for i, j in itertools.combinations(range(6), 2):
        before = model.new_bool_var(f"before_{i}_{j}")
        after = model.new_bool_var(f"before_{j}_{i}")
        skip = model.new_bool_var(f"skip_{i}_{j}")
        model.add_exactly_one(before, after, skip)
        model.add(times[i] + 3 <= times[j]).only_enforce_if(before)
        model.add(times[j] + 3 <= times[i]).only_enforce_if(after)
        skips.append(skip)
    model.minimize(sum(skips))
    return model


def count_rule(log, name):
    match = re.search(
        r"rule '" + re.escape(name) + r"' was applied ([\d']+) time", log
    )
    return int(match[1].replace("'", "")) if match else 0


def main():
    print(json.dumps({"python": platform.python_version(),
                      "ortools": ortools.__version__,
                      "os": platform.system(), "arch": platform.machine()}))
    for limit in (1, 2, 3):
        model = build_model()
        solver = cp_model.CpSolver()
        solver.parameters.cp_model_presolve = True
        solver.parameters.max_presolve_iterations = limit
        solver.parameters.stop_after_presolve = True
        solver.parameters.max_time_in_seconds = 1.0
        solver.parameters.num_search_workers = 1
        solver.parameters.random_seed = 0
        solver.parameters.log_search_progress = True
        solver.parameters.log_to_stdout = False
        messages = []
        solver.log_callback = messages.append
        status = solver.solve(model)
        log = "\n".join(messages)
        Path(f"presolve-{limit}.log").write_text(log)
        print(json.dumps({
            "max_iterations": limit,
            "status": solver.status_name(status),
            "actual_iterations": count_rule(log, "presolve: iteration"),
            "add_implication": count_rule(log, "incompatible linear: add implication"),
            "remove_duplicate": count_rule(log, "duplicate: removed constraint"),
            "presolved": dict(re.findall(r"(PresolvedNum\w+): (\d+)", log)),
        }))


if __name__ == "__main__":
    main()
Suspected source-level mechanism

In the v9.15 sources:

  1. DetectDifferentVariables() updates the incompatible linear: add implication rule counter and calls AddImplication(lit1, NegatedRef(lit2)) for incompatible guarded linear constraints.
  2. PresolveContext::AddImplication() appends an enforced BoolAnd constraint, with no existing-implication lookup on this path apart from skipping a == b.
  3. Duplicate removal also updates a rule counter.
  4. The outer loop breaks on zero additional presolve operations. Thus repeated insertion/removal can contribute a nonzero continuation signal even without net size reduction. The nearby TODO and the counter documentation already acknowledge that this is an imperfect progress measure.

The counter pattern is consistent with regenerated implications being removed and regenerated again. I have not instrumented individual literal identities or constraint lifetimes, so this is a suspected mechanism rather than a proof that every insertion is the same relationship. Equal aggregate sizes also do not establish identical models, domains, or propagation strength.

Question / expected behavior

Is the repeated implication-generation/removal pattern intentional, or is there an opportunity to avoid re-emitting already represented relationships and counting that work as progress toward another expensive presolve iteration?

I am not suggesting globally limiting presolve to one iteration or removing useful implications. I would appreciate guidance on whether a targeted deduplication or progress-accounting fix is appropriate, and what additional trace would help establish the exact mechanism.

Related general discussion: SAT Presolve time limit #4280; this report focuses on a specific implication/duplicate-removal pattern rather than a global time cap.

Lingua principale
C++
Stelle
14.5k
Fork
2.6k
Merge medio
9h 43m
PR unite (30g)
53

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di google/or-tools

Tutte le issue di google/or-tools

Issue simili

Altre issue su C++

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.